Overte C++ Documentation
BitVectorHelpers.h
1 //
2 // BitVectorHelpers.h
3 // libraries/shared/src
4 //
5 // Created by Anthony Thibault on 1/19/18.
6 // Copyright 2018 High Fidelity, Inc.
7 //
8 // Distributed under the Apache License, Version 2.0.
9 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10 //
11 
12 #ifndef hifi_BitVectorHelpers_h
13 #define hifi_BitVectorHelpers_h
14 
15 #include "NumericalConstants.h"
16 
17 int calcBitVectorSize(int numBits) {
18  return ((numBits - 1) >> 3) + 1;
19 }
20 
21 // func should be of type bool func(int index)
22 template <typename F>
23 int writeBitVector(uint8_t* destinationBuffer, int numBits, const F& func) {
24  int totalBytes = calcBitVectorSize(numBits);
25  uint8_t* cursor = destinationBuffer;
26  uint8_t byte = 0;
27  uint8_t bit = 0;
28 
29  for (int i = 0; i < numBits; i++) {
30  if (func(i)) {
31  byte |= (1 << bit);
32  }
33  if (++bit == BITS_IN_BYTE) {
34  *cursor++ = byte;
35  byte = 0;
36  bit = 0;
37  }
38  }
39  // write the last byte, if necessary
40  if (bit != 0) {
41  *cursor++ = byte;
42  }
43 
44  assert((int)(cursor - destinationBuffer) == totalBytes);
45  return totalBytes;
46 }
47 
48 // func should be of type 'void func(int index, bool value)'
49 template <typename F>
50 int readBitVector(const uint8_t* sourceBuffer, int numBits, const F& func) {
51  int totalBytes = calcBitVectorSize(numBits);
52  const uint8_t* cursor = sourceBuffer;
53  uint8_t bit = 0;
54 
55  for (int i = 0; i < numBits; i++) {
56  bool value = (bool)(*cursor & (1 << bit));
57  func(i, value);
58  if (++bit == BITS_IN_BYTE) {
59  cursor++;
60  bit = 0;
61  }
62  }
63  return totalBytes;
64 }
65 
66 #endif