Andrew Top | 0d1858f | 2019-05-15 22:01:47 -0700 | [diff] [blame] | 1 | // Copyright (c) 2016 The Chromium Authors. All rights reserved. |
| 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 <vector> |
| 9 | |
| 10 | #include "base/macros.h" |
| 11 | #include "starboard/types.h" |
| 12 | |
| 13 | namespace net { |
| 14 | |
| 15 | namespace huffman_trie { |
| 16 | |
| 17 | // BitWriter acts as a buffer to which bits can be written. The bits are stored |
| 18 | // as bytes in a vector. BitWriter will buffer bits until it contains 8 bits at |
| 19 | // which point they will be appended to the vector automatically. |
| 20 | class BitWriter { |
| 21 | public: |
| 22 | BitWriter(); |
| 23 | ~BitWriter(); |
| 24 | |
| 25 | // Appends |bit| to the end of the buffer. |
| 26 | void WriteBit(uint8_t bit); |
| 27 | |
| 28 | // Appends the |number_of_bits| least-significant bits of |bits| to the end of |
| 29 | // the buffer. |
| 30 | void WriteBits(uint32_t bits, uint8_t number_of_bits); |
| 31 | |
| 32 | // Appends the buffered bits in |current_byte_| to the |bytes_| vector. When |
| 33 | // there are less than 8 bits in the buffer, the empty bits will be filled |
| 34 | // with zero's. |
| 35 | void Flush(); |
| 36 | uint32_t position() const { return position_; } |
| 37 | |
| 38 | // Returns a reference to |bytes_|. Make sure to call Flush() first so that |
| 39 | // the buffered bits are written to |bytes_| as well. |
| 40 | const std::vector<uint8_t>& bytes() const { return bytes_; } |
| 41 | |
| 42 | private: |
| 43 | // Buffers bits until they fill a whole byte. |
| 44 | uint8_t current_byte_ = 0; |
| 45 | |
| 46 | // The number of bits currently in |current_byte_|. |
| 47 | uint8_t used_ = 0; |
| 48 | |
| 49 | // Total number of bits written to this BitWriter. |
| 50 | uint32_t position_ = 0; |
| 51 | |
| 52 | std::vector<uint8_t> bytes_; |
| 53 | |
| 54 | DISALLOW_COPY_AND_ASSIGN(BitWriter); |
| 55 | }; |
| 56 | |
| 57 | } // namespace huffman_trie |
| 58 | |
| 59 | } // namespace net |
| 60 | |
| 61 | #endif // NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_ |