15 static_assert(std::is_integral_v<T> && std::is_signed_v<T>);
17 using state_t = T
const *;
39 void add(
int symbol,
int code,
int code_length)
noexcept {
40 tt_axiom(code_length >= 1);
43 while (--code_length > 0) {
44 int select = (code >> code_length) & 1;
47 int value = tree[offset];
54 value = -(
static_cast<int>(std::ssize(tree)) - offset);
56 tree[offset] = narrow_cast<T>(value);
66 int select = code & 1;
69 tt_axiom(tree[offset] == 0);
70 tree[offset] = narrow_cast<T>(symbol + 1);
73 [[nodiscard]] state_t start() const noexcept {
89 [[nodiscard]]
int get(
bool code_bit, state_t &state)
const {
90 state +=
static_cast<ptrdiff_t
>(code_bit);
97 state -=
static_cast<ptrdiff_t
>(value);
101 [[nodiscard]]
int get_symbol(std::span<std::byte const> bytes,
ssize_t &bit_offset)
const noexcept {
102 auto state = start();
105 if ((symbol =
get(get_bit(bytes, bit_offset), state)) >= 0) {
114 struct symbol_length_t {
118 symbol_length_t(
int symbol,
int length) : symbol(symbol), length(length) {}
122 symbol_lengths.
reserve(nr_symbols);
124 for (
int symbol = 0; symbol != nr_symbols; ++symbol) {
130 if (a.length == b.length) {
131 return a.symbol < b.symbol;
133 return a.length < b.length;
141 for (
auto &&entry: symbol_lengths) {
142 if (entry.length != 0) {
143 code <<= (entry.length - prev_length);
145 r.
add(entry.symbol, code, entry.length);
149 prev_length = entry.length;
155 [[nodiscard]]
static huffman_tree from_lengths(
std::vector<int> const &lengths) {
156 return from_lengths(lengths.
data(), std::ssize(lengths));
Exception thrown during parsing on an error.
Definition exception.hpp:26
Definition huffman.hpp:14
void add(int symbol, int code, int code_length) noexcept
Add a symbol to the huffman_tree.
Definition huffman.hpp:39
static huffman_tree from_lengths(int const *lengths, ssize_t nr_symbols)
Build a canonical-huffman table from a set of lengths.
Definition huffman.hpp:113
int get(bool code_bit, state_t &state) const
Get a symbol from the huffman-tree.
Definition huffman.hpp:89
T emplace_back(T... args)