blob: 7927dec09a11f54b71977538101d613cc9c77805 [file] [log] [blame]
Avi Drissman64595482022-09-14 20:52:291// Copyright 2016 The Chromium Authors
martijn40db4b762016-12-14 00:26:452// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Mustafa Emre Acera7152b862018-06-14 20:57:475#ifndef NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_
6#define NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_
martijn40db4b762016-12-14 00:26:457
8#include <stdint.h>
9
10#include <vector>
11
Tsuyoshi Horo4f516be2022-06-14 11:53:1312namespace net::huffman_trie {
martijn40db4b762016-12-14 00:26:4513
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.
17class BitWriter {
18 public:
19 BitWriter();
Peter Boström293b1342021-09-22 17:31:4320
21 BitWriter(const BitWriter&) = delete;
22 BitWriter& operator=(const BitWriter&) = delete;
23
martijn40db4b762016-12-14 00:26:4524 ~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:
martijn40db4b762016-12-14 00:26:4544 // 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_;
martijn40db4b762016-12-14 00:26:4554};
55
Tsuyoshi Horo4f516be2022-06-14 11:53:1356} // namespace net::huffman_trie
martijn40db4b762016-12-14 00:26:4557
Mustafa Emre Acera7152b862018-06-14 20:57:4758#endif // NET_TOOLS_HUFFMAN_TRIE_BIT_WRITER_H_