Avi Drissman | 6459548 | 2022-09-14 20:52:29 | [diff] [blame^] | 1 | // Copyright 2016 The Chromium Authors |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
Mustafa Emre Acer | a7152b86 | 2018-06-14 20:57:47 | [diff] [blame] | 5 | #ifndef NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ |
| 6 | #define NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 7 | |
| 8 | #include <stdint.h> |
| 9 | |
| 10 | #include <vector> |
| 11 | |
Tsuyoshi Horo | 4f516be | 2022-06-14 11:53:13 | [diff] [blame] | 12 | namespace net::huffman_trie { |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 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(); |
Peter Boström | 293b134 | 2021-09-22 17:31:43 | [diff] [blame] | 20 | |
| 21 | BitWriter(const BitWriter&) = delete; |
| 22 | BitWriter& operator=(const BitWriter&) = delete; |
| 23 | |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 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(); |
| 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. |
| 41 | const std::vector<uint8_t>& bytes() const { return bytes_; } |
| 42 | |
| 43 | private: |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 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_; |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 54 | }; |
| 55 | |
Tsuyoshi Horo | 4f516be | 2022-06-14 11:53:13 | [diff] [blame] | 56 | } // namespace net::huffman_trie |
martijn | 40db4b76 | 2016-12-14 00:26:45 | [diff] [blame] | 57 | |
Mustafa Emre Acer | a7152b86 | 2018-06-14 20:57:47 | [diff] [blame] | 58 | #endif // NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ |