11namespace hi::inline v1 {
15 static_assert(std::is_integral_v<T> && std::is_signed_v<T>);
17 using state_t = T
const *;
40 void add(
int symbol,
int code,
int code_length)
noexcept
42 hi_axiom(code_length >= 1);
45 while (--code_length > 0) {
46 hilet select = (code >> code_length) & 1;
49 int value = tree[offset];
56 value = -(narrow_cast<int>(ssize(tree)) - offset);
58 tree[offset] = narrow_cast<T>(value);
68 hilet select = code & 1;
71 hi_axiom(tree[offset] == 0);
72 tree[offset] = narrow_cast<T>(symbol + 1);
75 [[nodiscard]] state_t start() const noexcept
92 [[nodiscard]]
int get(
bool code_bit, state_t &state)
const
94 state +=
static_cast<ptrdiff_t
>(code_bit);
101 state -=
static_cast<ptrdiff_t
>(value);
105 [[nodiscard]]
std::size_t get_symbol(std::span<std::byte const> bytes,
std::size_t &bit_offset)
const noexcept
107 auto state = start();
110 if ((symbol = get(get_bit(bytes, bit_offset), state)) >= 0) {
120 hi_axiom(lengths !=
nullptr);
123 struct symbol_length_t {
127 symbol_length_t(T symbol, uint8_t length) : symbol(symbol), length(length) {}
131 symbol_lengths.
reserve(nr_symbols);
133 for (T symbol = T{0}; symbol != narrow_cast<T>(nr_symbols); ++symbol) {
139 if (a.length == b.length) {
140 return a.symbol < b.symbol;
142 return a.length < b.length;
150 for (
auto &&entry : symbol_lengths) {
151 if (entry.length != 0) {
152 code <<= (entry.length - prev_length);
154 r.add(entry.symbol, code, entry.length);
158 prev_length = entry.length;
166 return from_lengths(lengths.
data(), lengths.
size());
This file includes required definitions.
#define hilet
Invariant should be the default for variables.
Definition required.hpp:23
Exception thrown during parsing on an error.
Definition exception.hpp:25
Definition huffman.hpp:14
int get(bool code_bit, state_t &state) const
Get a symbol from the huffman-tree.
Definition huffman.hpp:92
void add(int symbol, int code, int code_length) noexcept
Add a symbol to the huffman_tree.
Definition huffman.hpp:40
static huffman_tree from_lengths(uint8_t const *lengths, std::size_t nr_symbols)
Build a canonical-huffman table from a set of lengths.
Definition huffman.hpp:118
T emplace_back(T... args)