libfly  6.2.2
C++20 utility library for Linux, macOS, and Windows
huffman_encoder.hpp
1 #pragma once
2 
3 #include "fly/coders/coder.hpp"
4 #include "fly/coders/huffman/types.hpp"
5 
6 #include <array>
7 #include <istream>
8 #include <memory>
9 
10 namespace fly {
11 class BitStreamWriter;
12 } // namespace fly
13 
14 namespace fly::coders {
15 
16 class CoderConfig;
17 
26 {
27 public:
33  explicit HuffmanEncoder(const std::shared_ptr<CoderConfig> &config) noexcept;
34 
35 protected:
92  bool encode_binary(std::istream &decoded, fly::BitStreamWriter &encoded) override;
93 
94 private:
103  std::uint32_t read_stream(std::istream &decoded) const;
104 
110  void create_tree(std::uint32_t chunk_size);
111 
116  void create_codes();
117 
123  void insert_code(HuffmanCode &&code);
124 
131  void limit_code_lengths();
132 
137  void convert_to_canonical_form();
138 
144  void encode_header(fly::BitStreamWriter &encoded) const;
145 
151  void encode_codes(fly::BitStreamWriter &encoded) const;
152 
160  void encode_symbols(std::uint32_t chunk_size, fly::BitStreamWriter &encoded);
161 
162  // Configuration.
163  const std::uint32_t m_chunk_size;
164  const length_type m_max_code_length;
165 
166  std::unique_ptr<symbol_type[]> m_chunk_buffer;
167 
168  // Sized to fit 8-bit ASCII symbols.
169  std::array<HuffmanCode, 1 << 8> m_huffman_codes;
170  std::uint16_t m_huffman_codes_size;
171 
172  // Sized to fit a complete Huffman tree. With 8-bit symbols, a complete tree
173  // will have a height of 9, and 2^9 - 1 = 511 nodes (round to 512).
174  std::array<HuffmanNode, 1 << 9> m_huffman_tree;
175 };
176 
177 } // namespace fly::coders
Definition: bit_stream_writer.hpp:24
Definition: coder.hpp:71
Definition: huffman_encoder.hpp:26
bool encode_binary(std::istream &decoded, fly::BitStreamWriter &encoded) override
Definition: huffman_encoder.cpp:32
HuffmanEncoder(const std::shared_ptr< CoderConfig > &config) noexcept
Definition: huffman_encoder.cpp:24
Definition: types.hpp:91