1 // Copyright 2016 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ 6 #define NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ 7 8 #include <stdint.h> 9 10 #include <vector> 11 12 namespace net::huffman_trie { 13 14 // BitWriter acts as a buffer to which bits can be written. The bits are stored 15 // as bytes in a vector. BitWriter will buffer bits until it contains 8 bits at 16 // which point they will be appended to the vector automatically. 17 class BitWriter { 18 public: 19 BitWriter(); 20 21 BitWriter(const BitWriter&) = delete; 22 BitWriter& operator=(const BitWriter&) = delete; 23 24 ~BitWriter(); 25 26 // Appends |bit| to the end of the buffer. 27 void WriteBit(uint8_t bit); 28 29 // Appends the |number_of_bits| least-significant bits of |bits| to the end of 30 // the buffer. 31 void WriteBits(uint32_t bits, uint8_t number_of_bits); 32 33 // Appends the buffered bits in |current_byte_| to the |bytes_| vector. When 34 // there are less than 8 bits in the buffer, the empty bits will be filled 35 // with zero's. 36 void Flush(); position()37 uint32_t position() const { return position_; } 38 39 // Returns a reference to |bytes_|. Make sure to call Flush() first so that 40 // the buffered bits are written to |bytes_| as well. bytes()41 const std::vector<uint8_t>& bytes() const { return bytes_; } 42 43 private: 44 // Buffers bits until they fill a whole byte. 45 uint8_t current_byte_ = 0; 46 47 // The number of bits currently in |current_byte_|. 48 uint8_t used_ = 0; 49 50 // Total number of bits written to this BitWriter. 51 uint32_t position_ = 0; 52 53 std::vector<uint8_t> bytes_; 54 }; 55 56 } // namespace net::huffman_trie 57 58 #endif // NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ 59