Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Adaptive_Huffman.H
Go to the documentation of this file.
1/*
2 Aleph-w: Data structures & Algorithms
3 Copyright (c) 2026 Leandro Rabindranath Leon
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 SOFTWARE.
22*/
23
48#ifndef ALEPH_ADAPTIVE_HUFFMAN_H
49#define ALEPH_ADAPTIVE_HUFFMAN_H
50
51#include <climits>
52#include <cstddef>
53#include <cstdint>
54#include <limits>
55#include <string>
56#include <string_view>
57
58#include <ah-errors.H>
59#include <bitArray.H>
60
61namespace Aleph {
63namespace adaptive_huffman_detail {
64static_assert(CHAR_BIT == 8, "Adaptive Huffman requires eight-bit bytes");
65
67struct Model
68{
69 static constexpr int alphabet_size = 256;
70 static constexpr int max_nodes = 2 * alphabet_size + 1;
71 static constexpr int root = 0;
72
74 struct Node
75 {
76 std::uint64_t weight = 0;
77 int parent = -1;
78 int left = -1;
79 int right = -1;
80 int order = 0;
81 unsigned char symbol = 0;
82
86 [[nodiscard]] bool is_leaf() const noexcept
87 {
88 return left == -1;
89 }
90 };
91
92 // The alphabet bounds every table at compile time. Native fixed arrays
93 // keep the model allocation-free, including updates, reset and copying.
95 int by_order[max_nodes] = {};
97 int nyt = root;
98 int used = 1;
99 size_t distinct = 0;
100
102 Model() noexcept
103 {
104 reset();
105 }
106
108 void reset() noexcept
109 {
110 for (int i = 0; i < max_nodes; ++i)
111 {
112 nodes[i] = Node{};
113 by_order[i] = -1;
114 }
115 for (int &leaf : leaves)
116 leaf = -1;
117 nodes[root].order = max_nodes - 1;
118 by_order[max_nodes - 1] = root;
119 nyt = root;
120 used = 1;
121 distinct = 0;
122 }
123
127 void check_capacity() const
128 {
129 ah_overflow_error_if(nodes[root].weight == std::numeric_limits<std::uint64_t>::max())
130 << "Adaptive Huffman frequency limit reached; reset both codecs";
131 }
132
140 [[nodiscard]] int block_leader(const int node) const noexcept
141 {
142 int low = nodes[node].order;
143 int high = max_nodes;
144 const auto weight = nodes[node].weight;
145 while (low + 1 < high)
146 if (const int mid = low + (high - low) / 2; nodes[by_order[mid]].weight <= weight)
147 low = mid;
148 else
149 high = mid;
150 return by_order[low];
151 }
152
157 void swap_nodes(const int a, const int b) noexcept
158 {
159 const int pa = nodes[a].parent;
160 const int pb = nodes[b].parent;
161 const bool a_left = nodes[pa].left == a;
162 const bool b_left = nodes[pb].left == b;
163 (a_left ? nodes[pa].left : nodes[pa].right) = b;
164 (b_left ? nodes[pb].left : nodes[pb].right) = a;
165 nodes[a].parent = pb;
166 nodes[b].parent = pa;
167
168 const int order_a = nodes[a].order;
169 const int order_b = nodes[b].order;
170 nodes[a].order = order_b;
171 nodes[b].order = order_a;
172 by_order[order_a] = b;
173 by_order[order_b] = a;
174 }
175
181 void update(const unsigned char symbol) noexcept
182 {
183 int node = leaves[symbol];
184 if (node == -1)
185 {
186 const int old_nyt = nyt;
187 const int order = nodes[old_nyt].order;
188 nyt = used++;
189 node = used++;
190 nodes[nyt].parent = old_nyt;
191 nodes[nyt].order = order - 2;
192 nodes[node].parent = old_nyt;
193 nodes[node].order = order - 1;
194 nodes[node].weight = 1;
195 nodes[node].symbol = symbol;
196 by_order[order - 2] = nyt;
197 by_order[order - 1] = node;
198 nodes[old_nyt].left = nyt;
199 nodes[old_nyt].right = node;
200 nodes[old_nyt].weight = 1;
201 leaves[symbol] = node;
202 ++distinct;
203 node = nodes[old_nyt].parent;
204 }
205
206 while (node != -1)
207 {
208 const int leader = block_leader(node);
209 // The only possible ancestor of equal weight is the NYT parent.
210 if (leader != node and leader != nodes[node].parent)
211 swap_nodes(node, leader);
212 ++nodes[node].weight;
213 node = nodes[node].parent;
214 }
215 }
216};
217} // namespace adaptive_huffman_detail
218
241{
243
244public:
246 Adaptive_Huffman_Encoder() noexcept = default;
247
249 void reset() noexcept
250 {
251 model.reset();
252 }
253
257 [[nodiscard]] std::uint64_t symbols_processed() const noexcept
258 {
259 return model.nodes[model.root].weight;
260 }
261
265 [[nodiscard]] size_t distinct_symbols() const noexcept
266 {
267 return model.distinct;
268 }
269
274 [[nodiscard]] std::uint64_t frequency(const unsigned char symbol) const noexcept
275 {
276 const int leaf = model.leaves[symbol];
277 return leaf == -1 ? 0 : model.nodes[leaf].weight;
278 }
279
294 size_t encode(const unsigned char symbol, BitArray &output)
295 {
297 const bool unseen = model.leaves[symbol] == -1;
298 int node = unseen ? model.nyt : model.leaves[symbol];
300 size_t length = 0;
301 while (model.nodes[node].parent != -1)
302 {
303 const int parent = model.nodes[node].parent;
304 path[length++] = model.nodes[parent].right == node ? 1 : 0;
305 node = parent;
306 }
307 const size_t count = length + (unseen ? 8 : 0);
308 ah_overflow_error_if(output.size() > std::numeric_limits<size_t>::max() - count)
309 << "Adaptive Huffman output bit count overflow";
310 while (length != 0)
311 output.push(path[--length]);
312 if (unseen)
313 for (int shift = 7; shift >= 0; --shift)
314 output.push((symbol >> shift) & 1u);
315 model.update(symbol);
316 return count;
317 }
318
331 size_t encode(const std::string_view input, BitArray &output)
332 {
333 const size_t initial_size = output.size();
334 for (const unsigned char symbol : input)
335 encode(symbol, output);
336 return output.size() - initial_size;
337 }
338};
339
362{
365 unsigned int literal = 0;
366 unsigned int literal_bits = 0;
367 bool failed = false;
368
369public:
371 Adaptive_Huffman_Decoder() noexcept = default;
372
374 void reset() noexcept
375 {
376 model.reset();
378 literal = literal_bits = 0;
379 failed = false;
380 }
381
385 [[nodiscard]] std::uint64_t symbols_processed() const noexcept
386 {
387 return model.nodes[model.root].weight;
388 }
389
393 [[nodiscard]] size_t distinct_symbols() const noexcept
394 {
395 return model.distinct;
396 }
397
402 [[nodiscard]] std::uint64_t frequency(const unsigned char symbol) const noexcept
403 {
404 const int leaf = model.leaves[symbol];
405 return leaf == -1 ? 0 : model.nodes[leaf].weight;
406 }
407
411 [[nodiscard]] bool has_pending_symbol() const noexcept
412 {
413 return current != model.root or literal_bits != 0;
414 }
415
430 bool decode_bit(const unsigned int bit, unsigned char &symbol)
431 {
432 ah_out_of_range_error_if(bit > 1) << "Adaptive Huffman expects a binary bit";
434 << "Reset the adaptive Huffman decoder after malformed input or a lost byte";
436
437 unsigned char value;
438 if (not model.nodes[current].is_leaf())
439 {
441 if (current == model.nyt)
442 {
444 {
445 failed = true;
446 ah_invalid_argument() << "Adaptive Huffman NYT used with a full alphabet";
447 }
448 return false;
449 }
450 if (not model.nodes[current].is_leaf())
451 return false;
453 }
454 else
455 {
456 literal = (literal << 1) | bit;
457 if (++literal_bits < 8)
458 return false;
459 value = static_cast<unsigned char>(literal);
460 if (model.leaves[value] != -1)
461 {
462 failed = true;
463 ah_invalid_argument() << "Adaptive Huffman NYT introduced a known byte";
464 }
465 }
466
469 literal = literal_bits = 0;
470 symbol = value;
471 return true;
472 }
473
494 size_t decode(const BitArray &input, std::string &output)
495 {
496 const size_t initial_size = output.size();
497 for (size_t i = 0; i < input.size(); ++i)
498 {
499 unsigned char symbol;
500 if (decode_bit(static_cast<unsigned int>(input[i]), symbol))
501 try
502 {
503 output.push_back(static_cast<char>(symbol));
504 }
505 catch (...)
506 { // The model counted the byte: going on would lose it unseen.
507 failed = true;
508 throw;
509 }
510 }
511 return output.size() - initial_size;
512 }
513
522 void finish() const
523 {
525 << "Reset the adaptive Huffman decoder after malformed input or a lost byte";
526 ah_invalid_argument_if(has_pending_symbol()) << "Truncated adaptive Huffman codeword";
527 }
528};
529} // namespace Aleph
530
531#endif // ALEPH_ADAPTIVE_HUFFMAN_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_invalid_argument()
Throws std::invalid_argument unconditionally.
Definition ah-errors.H:819
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
Space-efficient bit array implementation.
size_t size_t int32_t value
Definition ca-c-api.h:116
Incremental FGK decoder accepting arbitrarily fragmented bits.
void reset() noexcept
Clear the tree, pending bits and error state in O(256) time.
std::uint64_t frequency(const unsigned char symbol) const noexcept
Return the current frequency of a decoded byte.
bool has_pending_symbol() const noexcept
Test whether a tree path or NYT literal is incomplete.
unsigned int literal_bits
Number of literal bits collected.
adaptive_huffman_detail::Model model
Owned adaptive tree.
std::uint64_t symbols_processed() const noexcept
Return the number of complete bytes decoded.
void finish() const
Verify that an externally framed message ended at a byte boundary.
Adaptive_Huffman_Decoder() noexcept=default
Construct a decoder with an empty model and no pending bits.
size_t decode(const BitArray &input, std::string &output)
Decode a bit chunk and append all complete bytes to a string.
size_t distinct_symbols() const noexcept
Return the number of different decoded byte values.
int current
Node reached by the partial codeword.
bool decode_bit(const unsigned int bit, unsigned char &symbol)
Consume one bit and emit a byte if its codeword is complete.
unsigned int literal
Partial, most-significant-bit-first byte.
bool failed
Malformed input or a lost output byte requires reset.
Stateful, one-pass FGK Huffman encoder for binary byte strings.
size_t encode(const unsigned char symbol, BitArray &output)
Append the current code for one byte, then update the tree.
size_t distinct_symbols() const noexcept
Return the number of different byte values seen.
std::uint64_t frequency(const unsigned char symbol) const noexcept
Return the current frequency of a byte.
adaptive_huffman_detail::Model model
Owned adaptive tree.
std::uint64_t symbols_processed() const noexcept
Return the number of bytes encoded since construction or reset.
void reset() noexcept
Reset the model in O(256) time; caller-owned output is untouched.
Adaptive_Huffman_Encoder() noexcept=default
Construct an encoder with an empty model.
size_t encode(const std::string_view input, BitArray &output)
Encode a chunk, retaining the model for subsequent chunks.
Contiguous array of bits.
Definition bitArray.H:201
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
Definition bitArray.H:350
Main namespace for Aleph-w library functions.
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
bool is_leaf() const noexcept
Test whether this node is a leaf.
std::uint64_t weight
Subtree frequency.
int parent
Parent index, or -1 at the root.
int order
Position in the sibling-property numbering.
int right
Right child index, or -1 at a leaf.
unsigned char symbol
Byte value, meaningful only at data leaves.
int left
Left child index, or -1 at a leaf.
static constexpr int root
Stable root node index.
void reset() noexcept
Restore the initial tree in O(alphabet_size) time.
void swap_nodes(const int a, const int b) noexcept
Exchange two non-ancestor subtrees and their order numbers.
int block_leader(const int node) const noexcept
Find the highest-order node of a node's weight block.
int leaves[alphabet_size]
Byte-to-leaf index, or -1 if unseen.
Node nodes[max_nodes]
Stable node storage.
int by_order[max_nodes]
Order-to-node index.
void update(const unsigned char symbol) noexcept
Insert an unseen byte or increment an existing byte's path.
static constexpr int max_nodes
Including NYT.
void check_capacity() const
Reject an update that would overflow the frequency counters.
Model() noexcept
Construct the initial tree containing only NYT.
static constexpr int alphabet_size
Number of possible bytes.
size_t distinct
Number of bytes seen so far.
ofstream output
Definition writeHeap.C:215