Belle II Software  release-08-01-10
BitStream.h
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 
9 #pragma once
10 #include <vector>
11 #include <framework/utilities/Utils.h>
12 
13 namespace Belle2::ECL {
14 
19  class BitStream {
20  public:
24  BitStream(): m_pos(0), m_store(1, 0) {}
25 
31  explicit BitStream(int n): m_pos(0), m_store(n, 0) {}
32 
37  void putNBits(unsigned int value, unsigned int n)
38  {
39  unsigned int bpos = m_pos % 32, wpos = m_pos / 32;
40  value &= 0xffffffffu >> (32 - n);
41 // check if we have enough space and double in size if necessary.
42  if (branch_unlikely(m_pos + n > m_store.size() * 32)) m_store.resize(2 * m_store.size(), 0);
43  m_store[wpos] |= value << bpos;
44  if (bpos + n > 32) m_store[wpos + 1] = value >> (32 - bpos);
45  m_pos += n;
46  }
47 
52  unsigned int getNBits(unsigned int n)
53  {
54  unsigned int bpos = m_pos % 32, wpos = m_pos / 32;
55 // make sure we don't access memory we don't own
56  if (branch_unlikely(m_pos + n > m_store.size() * 32)) throw std::range_error("Not enough bits in stream");
57  unsigned int res = m_store[wpos] >> bpos;
58  if (bpos + n > 32) res |= m_store[wpos + 1] << (32 - bpos);
59  m_pos += n;
60  return res & (0xffffffffu >> (32 - n));
61  }
62 
64  size_t getPos() const {return m_pos;}
65 
67  void setPos(size_t pos) {m_pos = pos;}
68 
70  std::vector<unsigned int>& getStore() {return m_store;}
71 
73  void resize()
74  {
75  m_store.resize((m_pos + 31) / 32);
76  }
77  protected:
78  size_t m_pos;
79  std::vector<unsigned int> m_store;
80  };
81 }
Bit stream struct.
Definition: BitStream.h:19
size_t getPos() const
Get current position in the stream.
Definition: BitStream.h:64
std::vector< unsigned int > m_store
The bit storage.
Definition: BitStream.h:79
void resize()
Resize data vector to the current position.
Definition: BitStream.h:73
void setPos(size_t pos)
Set position in the stream.
Definition: BitStream.h:67
BitStream(int n)
Constructor with the reserved and cleared storage prepared for incoming bits.
Definition: BitStream.h:31
BitStream()
Default constructor for ROOT.
Definition: BitStream.h:24
size_t m_pos
Current position in the storage.
Definition: BitStream.h:78
unsigned int getNBits(unsigned int n)
Fetch n bits.
Definition: BitStream.h:52
void putNBits(unsigned int value, unsigned int n)
Push n least significant bits of "value" to the stream.
Definition: BitStream.h:37
std::vector< unsigned int > & getStore()
Get data vector.
Definition: BitStream.h:70
#define branch_unlikely(x)
A macro to tell the compiler that the argument x will be very likely be false.
Definition: Utils.h:134