Pixie
Loading...
Searching...
No Matches
bit_stream.h
1#pragma once
2
3#include <cstdint>
4#include <cstdlib>
5#include <vector>
6
7namespace pixie {
8
9class OutputBitStream {
10 private:
11 size_t size_;
12 std::vector<uint64_t> data_;
13
14 public:
15 OutputBitStream() : size_(0) {}
16
20 OutputBitStream& operator<<(bool bit) {
21 if (size_ % 64 == 0) {
22 data_.push_back(bit);
23 } else if (bit) {
24 data_.back() |= 1ull << (size_ % 64);
25 }
26 size_++;
27 return *this;
28 }
29
33 template <std::integral T>
34 OutputBitStream& operator<<(T bits) {
35 using UT = std::make_unsigned_t<T>;
36 UT ubits = static_cast<UT>(bits);
37 constexpr size_t length = sizeof(T) * 8;
38 static_assert(length <= 64);
39 if (size_ % 64 == 0) {
40 data_.push_back(ubits);
41 } else {
42 const size_t prefix = std::min(length, 64 - (size_ % 64));
43 data_.back() |= static_cast<uint64_t>(ubits & ((1ull << prefix) - 1))
44 << (size_ % 64);
45 if (prefix < length) {
46 data_.push_back(ubits >> prefix);
47 }
48 }
49 size_ += length;
50 return *this;
51 }
52
57 size_t size() const { return size_; }
58
63 void reserve(size_t size) { data_.reserve((size + 63) / 64); }
64
69 std::vector<uint64_t> extract() { return std::move(data_); }
70};
71
72} // namespace pixie
size_t size() const
Returns the number of written bits.
Definition bit_stream.h:57
std::vector< uint64_t > extract()
Moves vector containing written bits. There must be no operator<< after extract()
Definition bit_stream.h:69
OutputBitStream & operator<<(T bits)
Writes bits of the integral number to the stream in little-endian.
Definition bit_stream.h:34
OutputBitStream & operator<<(bool bit)
Writes one bit to the stream.
Definition bit_stream.h:20
void reserve(size_t size)
Reserves memory for "size" bits.
Definition bit_stream.h:63