Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
adaptive_huffman_test.cc
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
28#include <Adaptive_Huffman.H>
29#include <gtest/gtest.h>
30
31#include <algorithm>
32#include <array>
33#include <cstddef>
34#include <cstdint>
35#include <functional>
36#include <limits>
37#include <queue>
38#include <random>
39#include <sstream>
40#include <stdexcept>
41#include <string>
42#include <string_view>
43#include <utility>
44#include <vector>
45
46using namespace Aleph;
47
48namespace
49{
51 using Counts = std::array<std::uint64_t, 256>;
52
59 BitArray slice(const BitArray &bits, const size_t begin, const size_t end)
60 {
61 BitArray chunk;
62 for (size_t i = begin; i < end; ++i)
63 chunk.push(bits[i]);
64 return chunk;
65 }
66
71 BitArray bit_literal(const std::string &text)
72 {
73 BitArray result;
74 result.set_bit_str(text);
75 return result;
76 }
77
86 void check_model(const Model &model, const Counts &counts)
87 {
88 std::uint64_t total = 0;
89 size_t distinct = 0;
90 for (size_t symbol = 0; symbol < counts.size(); ++symbol)
91 {
92 total += counts[symbol];
93 if (counts[symbol] == 0)
94 ASSERT_EQ(model.leaves[symbol], -1);
95 else
96 {
97 ++distinct;
98 const int leaf = model.leaves[symbol];
99 ASSERT_GE(leaf, 0);
100 ASSERT_LT(leaf, model.used);
101 ASSERT_TRUE(model.nodes[leaf].is_leaf());
102 ASSERT_EQ(model.nodes[leaf].symbol, symbol);
103 ASSERT_EQ(model.nodes[leaf].weight, counts[symbol]);
104 }
105 }
106 ASSERT_EQ(model.distinct, distinct);
107 ASSERT_EQ(model.used, 2 * distinct + 1);
108 ASSERT_EQ(model.nodes[Model::root].parent, -1);
109 ASSERT_EQ(model.nodes[Model::root].weight, total);
110 ASSERT_EQ(model.nodes[Model::root].order, Model::max_nodes - 1);
111 ASSERT_GE(model.nyt, 0);
112 ASSERT_LT(model.nyt, model.used);
113 ASSERT_TRUE(model.nodes[model.nyt].is_leaf());
114 ASSERT_EQ(model.nodes[model.nyt].weight, 0u);
115
116 const int first = Model::max_nodes - model.used;
117 for (int order = first; order < Model::max_nodes; ++order)
118 {
119 const int id = model.by_order[order];
120 ASSERT_GE(id, 0);
121 ASSERT_LT(id, model.used);
122 const auto &node = model.nodes[id];
123 ASSERT_EQ(node.order, order);
124 if (order != first)
125 ASSERT_LE(model.nodes[model.by_order[order - 1]].weight, node.weight);
126 if (id != Model::root)
127 {
128 ASSERT_GE(node.parent, 0);
129 ASSERT_LT(node.parent, model.used);
130 const auto &parent = model.nodes[node.parent];
131 ASSERT_GT(parent.order, order); // Also excludes cycles.
132 ASSERT_TRUE(parent.left == id or parent.right == id);
133 }
134 if (not node.is_leaf())
135 {
136 ASSERT_GE(node.left, 0);
137 ASSERT_LT(node.left, model.used);
138 ASSERT_GE(node.right, 0);
139 ASSERT_LT(node.right, model.used);
140 const auto &left = model.nodes[node.left];
141 const auto &right = model.nodes[node.right];
142 ASSERT_EQ(left.parent, id);
143 ASSERT_EQ(right.parent, id);
144 ASSERT_EQ(left.order + 1, right.order);
145 ASSERT_EQ(left.order % 2, 0);
146 ASSERT_EQ(node.weight, left.weight + right.weight);
147 }
148 }
149 for (int order = first; order + 1 < Model::max_nodes; order += 2)
150 ASSERT_EQ(model.nodes[model.by_order[order]].parent,
151 model.nodes[model.by_order[order + 1]].parent);
152 }
153
158 std::uint64_t optimal_cost(const Counts &counts)
159 {
160 std::priority_queue<std::uint64_t, std::vector<std::uint64_t>,
161 std::greater<std::uint64_t>> heap;
162 heap.push(0); // The retained NYT leaf is part of the coding alphabet.
163 for (const auto count : counts)
164 if (count != 0)
165 heap.push(count);
166 std::uint64_t cost = 0;
167 while (heap.size() > 1)
168 {
169 const auto a = heap.top();
170 heap.pop();
171 const auto b = heap.top();
172 heap.pop();
173 cost += a + b;
174 heap.push(a + b);
175 }
176 return cost;
177 }
178
183 std::uint64_t tree_cost(const Model &model)
184 {
185 std::uint64_t cost = 0;
186 for (const int leaf : model.leaves)
187 if (leaf != -1)
188 for (int node = leaf; model.nodes[node].parent != -1;
189 node = model.nodes[node].parent)
190 cost += model.nodes[leaf].weight;
191 return cost;
192 }
193
197 void check_round_trip(const std::string_view input)
198 {
202 const auto count = encoder.encode(input, bits);
203 EXPECT_EQ(count, bits.size());
204 std::string output;
205 EXPECT_EQ(decoder.decode(bits, output), input.size());
206 EXPECT_NO_THROW(decoder.finish());
207 EXPECT_EQ(output, input);
208 EXPECT_EQ(encoder.symbols_processed(), input.size());
209 EXPECT_EQ(decoder.symbols_processed(), input.size());
210 Counts counts{};
211 for (const unsigned char byte : input)
212 ++counts[byte];
213 for (size_t symbol = 0; symbol < counts.size(); ++symbol)
214 {
215 EXPECT_EQ(encoder.frequency(static_cast<unsigned char>(symbol)), counts[symbol]);
216 EXPECT_EQ(decoder.frequency(static_cast<unsigned char>(symbol)), counts[symbol]);
217 }
218 }
219
220 TEST(AdaptiveHuffman, EmptyInputAndExistingOutputPrefixes)
221 {
224 BitArray bits = bit_literal("101");
225 EXPECT_EQ(encoder.encode(std::string_view{}, bits), 0u);
226 EXPECT_EQ(bits.get_bit_str(), "101");
227 std::string output = "prefix";
228 EXPECT_EQ(decoder.decode(BitArray{}, output), 0u);
229 EXPECT_EQ(output, "prefix");
230 EXPECT_NO_THROW(decoder.finish());
231 EXPECT_FALSE(decoder.has_pending_symbol());
232 EXPECT_EQ(encoder.symbols_processed(), 0u);
233 EXPECT_EQ(decoder.symbols_processed(), 0u);
234 EXPECT_EQ(encoder.distinct_symbols(), 0u);
235 EXPECT_EQ(decoder.distinct_symbols(), 0u);
236 EXPECT_EQ(encoder.frequency('A'), 0u);
237 EXPECT_EQ(decoder.frequency('A'), 0u);
238
239 EXPECT_EQ(encoder.encode('A', bits), 8u);
240 EXPECT_EQ(bits.get_bit_str(), "10101000001");
241 EXPECT_EQ(decoder.decode(slice(bits, 3, bits.size()), output), 1u);
242 EXPECT_EQ(output, "prefixA");
243 EXPECT_NO_THROW(decoder.finish());
244 }
245
246 TEST(AdaptiveHuffman, GoldenBitSequences)
247 {
248 // These paths are determined manually from the NYT splits and FGK swaps.
249 const std::pair<std::string, std::string> cases[] = {
250 {"A", "01000001"},
251 {"AAAA", "01000001" "1" "1" "1"},
252 {"AB", "01000001" "0" "01000010"},
253 {"ABBA", "01000001" "0" "01000010" "01" "01"},
254 {"ABC", "01000001" "0" "01000010" "00" "01000011"},
255 {std::string("\0\xff\0", 3), "00000000" "0" "11111111" "1"}
256 };
257 for (const auto &[input, expected] : cases)
258 {
259 SCOPED_TRACE(expected);
262 encoder.encode(input, bits);
263 EXPECT_EQ(bits.get_bit_str(), expected);
264
265 // Decode the independent expected bits, not the encoder's output.
267 std::string output;
268 decoder.decode(bit_literal(expected), output);
269 EXPECT_NO_THROW(decoder.finish());
270 EXPECT_EQ(output, input);
271 }
272 }
273
274 TEST(AdaptiveHuffman, RepeatedSymbolNeedsOneBitAfterItsFirstOccurrence)
275 {
278 const std::string input(4096, '\0');
279 encoder.encode(input, bits);
280 EXPECT_EQ(bits.size(), 8 + input.size() - 1);
281 EXPECT_EQ(encoder.distinct_symbols(), 1u);
282 check_round_trip(input);
283 }
284
285 TEST(AdaptiveHuffman, AllByteValuesAndChangingDistributions)
286 {
287 std::string input;
288 for (int round = 0; round < 3; ++round)
289 for (int symbol = 0; symbol < 256; ++symbol)
290 input.push_back(static_cast<char>(round % 2 == 0 ? symbol : 255 - symbol));
291 input.append(5000, 'a');
292 input.append(7000, static_cast<char>(0xff));
293 input.append(9000, '\0');
294 check_round_trip(input);
295 }
296
297 TEST(AdaptiveHuffman, EmitsEachByteOnItsLastBit)
298 {
301 const std::string input = "abcdefghiaaf abracadabra\n\t";
302 for (const unsigned char byte : input)
303 {
305 encoder.encode(byte, bits);
306 unsigned char output = static_cast<unsigned char>(~byte);
307 for (size_t i = 0; i < bits.size(); ++i)
308 {
309 EXPECT_EQ(decoder.decode_bit(bits[i], output), i + 1 == bits.size());
310 EXPECT_EQ(output, i + 1 == bits.size() ? byte : static_cast<unsigned char>(~byte));
311 }
312 EXPECT_FALSE(decoder.has_pending_symbol());
313 EXPECT_EQ(decoder.frequency(byte), encoder.frequency(byte));
314 EXPECT_EQ(decoder.symbols_processed(), encoder.symbols_processed());
315 EXPECT_NO_THROW(decoder.finish());
316 }
317 }
318
319 TEST(AdaptiveHuffman, ArbitraryChunksMatchWholeMessage)
320 {
321 std::mt19937 rng(0xada971u);
322 const unsigned int alphabets[] = {1, 2, 3, 16, 128, 256};
323 for (const auto alphabet : alphabets)
324 for (int round = 0; round < 8; ++round)
325 {
326 SCOPED_TRACE(alphabet);
327 SCOPED_TRACE(round);
328 const size_t length = rng() % 1025;
329 std::string input;
330 for (size_t i = 0; i < length; ++i)
331 input.push_back(static_cast<char>(rng() % alphabet));
332
333 Adaptive_Huffman_Encoder whole_encoder, chunk_encoder;
334 BitArray whole_bits, chunk_bits;
335 whole_encoder.encode(input, whole_bits);
336 for (size_t i = 0; i < input.size();)
337 {
338 const size_t count = std::min<size_t>(1 + rng() % 23, input.size() - i);
339 chunk_encoder.encode(std::string_view(input).substr(i, count), chunk_bits);
340 i += count;
341 }
342 ASSERT_TRUE(chunk_bits == whole_bits);
343
345 std::string output;
346 for (size_t i = 0; i < chunk_bits.size();)
347 {
348 const size_t end = std::min<size_t>(i + 1 + rng() % 37, chunk_bits.size());
349 decoder.decode(slice(chunk_bits, i, end), output);
350 i = end;
351 }
352 EXPECT_NO_THROW(decoder.finish());
353 EXPECT_EQ(output, input);
354 }
355 }
356
357 TEST(AdaptiveHuffman, EveryPartialCodewordCanBeResumed)
358 {
361 const std::string input = "abcdefghiaaf abracadabra";
362 for (const unsigned char byte : input)
363 {
365 encoder.encode(byte, bits);
366 for (size_t cut = 1; cut < bits.size(); ++cut)
367 {
368 auto partial = decoder;
369 std::string output;
370 EXPECT_EQ(partial.decode(slice(bits, 0, cut), output), 0u);
371 EXPECT_TRUE(partial.has_pending_symbol());
372 EXPECT_THROW(partial.finish(), std::invalid_argument);
373 EXPECT_EQ(partial.decode(slice(bits, cut, bits.size()), output), 1u);
374 EXPECT_NO_THROW(partial.finish());
375 EXPECT_EQ(output, std::string(1, static_cast<char>(byte)));
376 }
377 std::string output;
378 decoder.decode(bits, output);
379 }
380 }
381
382 TEST(AdaptiveHuffman, RejectsNonBinaryBitsWithoutChangingState)
383 {
385 unsigned char output = 99;
386 for (const unsigned int bit : {0u, 1u, 0u})
387 EXPECT_FALSE(decoder.decode_bit(bit, output));
388 EXPECT_THROW(decoder.decode_bit(2, output), std::out_of_range);
389 EXPECT_EQ(output, 99);
390 EXPECT_TRUE(decoder.has_pending_symbol());
391 std::string text;
392 decoder.decode(bit_literal("00001"), text);
393 EXPECT_NO_THROW(decoder.finish());
394 EXPECT_EQ(text, "A");
395 }
396
397 TEST(AdaptiveHuffman, RejectsKnownByteIntroducedThroughNYT)
398 {
400 std::string output;
401 decoder.decode(bit_literal("01000001"), output);
402 EXPECT_THROW(decoder.decode(bit_literal("0" "01000001"), output), std::invalid_argument);
403 EXPECT_EQ(output, "A");
404 EXPECT_EQ(decoder.symbols_processed(), 1u);
405 EXPECT_EQ(decoder.distinct_symbols(), 1u);
406 EXPECT_EQ(decoder.frequency('A'), 1u);
407 unsigned char byte = 99;
408 EXPECT_THROW(decoder.decode_bit(1, byte), std::domain_error);
409 EXPECT_THROW(decoder.finish(), std::domain_error);
410 EXPECT_EQ(byte, 99);
411
412 decoder.reset();
413 output.clear();
414 decoder.decode(bit_literal("01000001"), output);
415 EXPECT_EQ(output, "A");
416 EXPECT_NO_THROW(decoder.finish());
417 }
418
419 TEST(AdaptiveHuffman, RejectsNYTAfterTheWholeAlphabetWasSeen)
420 {
423 Model model;
425 for (int symbol = 0; symbol < 256; ++symbol)
426 {
427 encoder.encode(static_cast<unsigned char>(symbol), bits);
428 model.update(static_cast<unsigned char>(symbol));
429 }
430 std::string output;
431 decoder.decode(bits, output);
432 ASSERT_EQ(decoder.distinct_symbols(), 256u);
433 std::string path;
434 for (int node = model.nyt; model.nodes[node].parent != -1;)
435 {
436 const int parent = model.nodes[node].parent;
437 path.push_back(model.nodes[parent].left == node ? '0' : '1');
438 node = parent;
439 }
440 std::reverse(path.begin(), path.end());
441 EXPECT_THROW(decoder.decode(bit_literal(path), output), std::invalid_argument);
442 EXPECT_EQ(output.size(), 256u);
443 EXPECT_EQ(decoder.symbols_processed(), 256u);
444
445 // The decoder asks for a reset, as after the escape of a known byte; a
446 // bit that is not binary is refused first, as on any decoder
447 unsigned char byte = 99;
448 EXPECT_THROW(decoder.decode_bit(0, byte), std::domain_error);
449 EXPECT_THROW(decoder.decode_bit(1, byte), std::domain_error);
450 EXPECT_THROW(decoder.decode_bit(2, byte), std::out_of_range);
451 EXPECT_THROW(decoder.finish(), std::domain_error);
452 EXPECT_EQ(byte, 99);
453 decoder.reset();
454 EXPECT_NO_THROW(decoder.finish());
455 }
456
457 // decode() keeps in the output the bytes that it decoded before the bad
458 // codeword of the same chunk, and the decoder counts exactly those
459 TEST(AdaptiveHuffman, MalformedChunkKeepsTheBytesBeforeTheBadCodeword)
460 {
462 BitArray chunk;
463 encoder.encode("AB", chunk);
464 for (const char c : std::string("00" "01000001")) // the NYT path, then A again
465 chunk.push(c == '1');
467 std::string output = "kept:";
468 EXPECT_THROW(decoder.decode(chunk, output), std::invalid_argument);
469 EXPECT_EQ(output, "kept:AB");
470 EXPECT_EQ(decoder.symbols_processed(), 2u);
471 EXPECT_THROW(decoder.finish(), std::domain_error);
472 EXPECT_EQ(decoder.decode(BitArray(), output), 0u); // an empty chunk consumes nothing
473 }
474
475 // encode(byte) returns the bits that it appended: for a known byte, and for
476 // an unseen one behind an NYT path that is not empty
477 TEST(AdaptiveHuffman, EncodeByteReturnsTheBitsItAppended)
478 {
480 BitArray bits = bit_literal("101");
481 size_t known = 0;
482 size_t unseen_deep = 0;
483 for (const unsigned char byte : std::string_view("abracadabra: every byte reports its own bits"))
484 {
485 const bool first = encoder.frequency(byte) == 0;
486 const size_t before = bits.size();
487 const size_t returned = encoder.encode(byte, bits);
488 EXPECT_EQ(returned, bits.size() - before);
489 if (first)
490 {
491 EXPECT_GE(returned, 8u);
492 unseen_deep += returned > 8;
493 }
494 else
495 {
496 EXPECT_GE(returned, 1u);
497 ++known;
498 }
499 }
500 EXPECT_GT(known, 0u); // both kinds were exercised
501 EXPECT_GT(unseen_deep, 0u);
502 }
503
504 // With Fibonacci counts the tree is a chain, and its codewords are as long
505 // as the number of distinct bytes: 17,710 bytes of 20 values give 20 bits.
506 // No other test goes deeper than 11 levels
507 TEST(AdaptiveHuffman, FibonacciFrequenciesGiveCodewordsAsDeepAsTheAlphabet)
508 {
509 constexpr int distinct = 20;
510 std::string input;
511 std::uint64_t a = 1;
512 std::uint64_t b = 1;
513 for (int symbol = 0; symbol < distinct; ++symbol)
514 {
515 input.append(a, static_cast<char>(200 + symbol));
516 const auto next = a + b;
517 a = b;
518 b = next;
519 }
522 encoder.encode(input, bits);
523 size_t longest = 0;
524 for (int symbol = 0; symbol < distinct; ++symbol)
525 {
526 auto probe = encoder; // the code of a known byte, without changing the encoder
528 longest = std::max(longest, probe.encode(static_cast<unsigned char>(200 + symbol), code));
529 }
530 EXPECT_EQ(longest, static_cast<size_t>(distinct));
532 std::string output;
533 EXPECT_EQ(decoder.decode(bits, output), input.size());
534 EXPECT_NO_THROW(decoder.finish());
535 EXPECT_EQ(output, input);
536 }
537
538 TEST(AdaptiveHuffman, ResetRestoresInitialWireFormatAndPendingState)
539 {
543 encoder.encode("many different bytes", bits);
544 std::string output;
545 decoder.decode(bits, output);
546 BitArray next_bits;
547 encoder.encode('\0', next_bits);
548 decoder.decode(slice(next_bits, 0, 1), output); // Begin the next codeword.
549 ASSERT_TRUE(decoder.has_pending_symbol());
550 encoder.reset();
551 decoder.reset();
552 EXPECT_EQ(encoder.symbols_processed(), 0u);
553 EXPECT_EQ(decoder.symbols_processed(), 0u);
554 EXPECT_EQ(encoder.distinct_symbols(), 0u);
555 EXPECT_EQ(decoder.distinct_symbols(), 0u);
556 EXPECT_EQ(encoder.frequency('m'), 0u);
557 EXPECT_EQ(decoder.frequency('m'), 0u);
558 EXPECT_FALSE(decoder.has_pending_symbol());
559 EXPECT_NO_THROW(decoder.finish());
560 bits.empty();
561 encoder.encode('A', bits);
562 EXPECT_EQ(bits.get_bit_str(), "01000001");
563 output.clear();
564 decoder.decode(bits, output);
565 EXPECT_EQ(output, "A");
566 }
567
568 TEST(AdaptiveHuffman, CopiesOwnIndependentModelsAndPartialLiterals)
569 {
572 encoder.encode("abcde", prefix);
573 auto copy = encoder;
574 BitArray original_suffix, copied_suffix;
575 encoder.encode("aaaa", original_suffix);
576 copy.encode("bcde", copied_suffix);
577 EXPECT_EQ(encoder.frequency('a'), 5u);
578 EXPECT_EQ(copy.frequency('a'), 1u);
579 Adaptive_Huffman_Encoder reference;
581 reference.encode("abcdebcde", expected);
582 EXPECT_TRUE(copied_suffix == slice(expected, prefix.size(), expected.size()));
583
585 std::string ignored;
586 decoder.decode(bit_literal("010"), ignored);
587 auto decoder_copy = decoder;
588 std::string a, b;
589 decoder.decode(bit_literal("00001"), a);
590 decoder_copy.decode(bit_literal("00010"), b);
591 EXPECT_EQ(a, "A");
592 EXPECT_EQ(b, "B");
593 EXPECT_EQ(decoder.frequency('B'), 0u);
594 EXPECT_EQ(decoder_copy.frequency('A'), 0u);
595 EXPECT_NO_THROW(decoder.finish());
596 EXPECT_NO_THROW(decoder_copy.finish());
597 }
598
599 TEST(AdaptiveHuffman, BitArrayPersistencePreservesFraming)
600 {
601 const std::string input("\0\xff\0 binary\n\xff", 12);
604 encoder.encode(input, bits);
605 std::stringstream storage;
606 bits.save(storage);
607 BitArray loaded;
608 loaded.load(storage);
609 EXPECT_TRUE(loaded == bits);
611 std::string output;
612 decoder.decode(loaded, output);
613 EXPECT_NO_THROW(decoder.finish());
614 EXPECT_EQ(output, input);
615 }
616
617 TEST(AdaptiveHuffmanTree, ExhaustiveShortTernarySequencesKeepSiblingProperty)
618 {
619 Counts counts{};
620 Model model;
621 check_model(model, counts);
622 size_t combinations = 1;
623 for (size_t length = 1; length <= 7; ++length)
624 {
625 combinations *= 3;
626 for (size_t sequence = 0; sequence < combinations; ++sequence)
627 {
628 model.reset();
629 counts.fill(0);
630 size_t digits = sequence;
631 for (size_t i = 0; i < length; ++i)
632 {
633 const auto byte = static_cast<unsigned char>(digits % 3);
634 digits /= 3;
635 ++counts[byte];
636 model.update(byte);
637 ASSERT_NO_FATAL_FAILURE(check_model(model, counts));
638 }
639 ASSERT_EQ(tree_cost(model), optimal_cost(counts));
640 }
641 }
642 }
643
644 TEST(AdaptiveHuffmanTree, RandomUpdatesRemainOptimalForCurrentFrequencies)
645 {
646 Model model;
647 Counts counts{};
648 std::mt19937 rng(0xf6c123u);
649 // The first part exercises NYT siblings and many equal-weight swaps;
650 // later parts force large changes in the distribution and internal swaps.
651 for (size_t i = 0; i < 6000; ++i)
652 {
653 const unsigned int alphabet = i < 2000 ? 256 : (i < 4000 ? 3 : 64);
654 const auto byte = static_cast<unsigned char>(rng() % alphabet);
655 ++counts[byte];
656 model.update(byte);
657 ASSERT_NO_FATAL_FAILURE(check_model(model, counts));
658 ASSERT_EQ(tree_cost(model), optimal_cost(counts)) << "Update " << i;
659 }
660 }
661
662 TEST(AdaptiveHuffmanTree, CounterLimitDoesNotWrapAndResetRecovers)
663 {
664 Model model;
665 constexpr unsigned char a = 'A';
666 model.update(a);
667 constexpr auto limit = std::numeric_limits<std::uint64_t>::max();
668 model.nodes[model.leaves[a]].weight = limit - 1;
669 model.nodes[Model::root].weight = limit - 1;
670 ASSERT_NO_THROW(model.check_capacity());
671 model.update(a);
672 EXPECT_EQ(model.nodes[Model::root].weight, limit);
673 EXPECT_EQ(model.nodes[model.leaves[a]].weight, limit);
674 EXPECT_THROW(model.check_capacity(), std::overflow_error);
675 model.reset();
676 EXPECT_NO_THROW(model.check_capacity());
677 EXPECT_EQ(model.nodes[Model::root].weight, 0u);
678 }
679}
One-pass adaptive Huffman coding of bytes using FGK updates.
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.
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.
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.
bool decode_bit(const unsigned int bit, unsigned char &symbol)
Consume one bit and emit a byte if its codeword is complete.
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.
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.
Contiguous array of bits.
Definition bitArray.H:201
void set_bit_str(const std::string &str)
Definition bitArray.H:966
void load(std::istream &input)
Loads an array of bits saved with save().
Definition bitArray.H:661
void push(const unsigned int value)
Inserts the value at the end of the array.
Definition bitArray.H:506
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
Definition bitArray.H:350
Minimal std::expected-style result type for C++20.
#define TEST(name)
static mt19937 rng
Main namespace for Aleph-w library functions.
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
static void prefix(Node *root, DynList< Node * > &acc)
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
STL namespace.
ofstream output
Definition writeHeap.C:215