29#include <gtest/gtest.h>
51 using Counts = std::array<std::uint64_t, 256>;
62 for (
size_t i = begin; i < end; ++i)
71 BitArray bit_literal(
const std::string &text)
86 void check_model(
const Model &model,
const Counts &counts)
88 std::uint64_t total = 0;
90 for (
size_t symbol = 0; symbol < counts.size(); ++symbol)
92 total += counts[symbol];
93 if (counts[symbol] == 0)
94 ASSERT_EQ(model.leaves[symbol], -1);
98 const int leaf = model.leaves[symbol];
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]);
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);
116 const int first = Model::max_nodes - model.used;
117 for (
int order = first; order < Model::max_nodes; ++order)
119 const int id = model.by_order[order];
121 ASSERT_LT(
id, model.used);
122 const auto &node = model.nodes[id];
123 ASSERT_EQ(node.order, order);
125 ASSERT_LE(model.nodes[model.by_order[order - 1]].weight, node.weight);
126 if (
id != Model::root)
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);
132 ASSERT_TRUE(parent.left ==
id or parent.right ==
id);
134 if (not node.is_leaf())
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);
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);
158 std::uint64_t optimal_cost(
const Counts &counts)
160 std::priority_queue<std::uint64_t, std::vector<std::uint64_t>,
161 std::greater<std::uint64_t>> heap;
163 for (
const auto count : counts)
166 std::uint64_t cost = 0;
167 while (heap.size() > 1)
169 const auto a = heap.top();
171 const auto b = heap.top();
183 std::uint64_t tree_cost(
const Model &model)
185 std::uint64_t cost = 0;
186 for (
const int leaf : model.leaves)
188 for (int node = leaf; model.nodes[node].parent != -1;
189 node = model.nodes[node].parent)
190 cost += model.nodes[leaf].weight;
197 void check_round_trip(
const std::string_view input)
206 EXPECT_NO_THROW(decoder.
finish());
211 for (
const unsigned char byte : input)
213 for (
size_t symbol = 0; symbol < counts.size(); ++symbol)
215 EXPECT_EQ(encoder.
frequency(
static_cast<unsigned char>(symbol)), counts[symbol]);
216 EXPECT_EQ(decoder.
frequency(
static_cast<unsigned char>(symbol)), counts[symbol]);
220 TEST(AdaptiveHuffman, EmptyInputAndExistingOutputPrefixes)
225 EXPECT_EQ(encoder.
encode(std::string_view{},
bits), 0u);
226 EXPECT_EQ(
bits.get_bit_str(),
"101");
227 std::string
output =
"prefix";
229 EXPECT_EQ(
output,
"prefix");
230 EXPECT_NO_THROW(decoder.
finish());
240 EXPECT_EQ(
bits.get_bit_str(),
"10101000001");
242 EXPECT_EQ(
output,
"prefixA");
243 EXPECT_NO_THROW(decoder.
finish());
246 TEST(AdaptiveHuffman, GoldenBitSequences)
249 const std::pair<std::string, std::string> cases[] = {
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"}
257 for (
const auto &[input,
expected] : cases)
269 EXPECT_NO_THROW(decoder.
finish());
274 TEST(AdaptiveHuffman, RepeatedSymbolNeedsOneBitAfterItsFirstOccurrence)
278 const std::string input(4096,
'\0');
280 EXPECT_EQ(
bits.size(), 8 + input.size() - 1);
282 check_round_trip(input);
285 TEST(AdaptiveHuffman, AllByteValuesAndChangingDistributions)
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);
297 TEST(AdaptiveHuffman, EmitsEachByteOnItsLastBit)
301 const std::string input =
"abcdefghiaaf abracadabra\n\t";
302 for (
const unsigned char byte : input)
306 unsigned char output =
static_cast<unsigned char>(~byte);
307 for (
size_t i = 0; i <
bits.size(); ++i)
310 EXPECT_EQ(
output, i + 1 ==
bits.size() ?
byte : static_cast<unsigned char>(~byte));
315 EXPECT_NO_THROW(decoder.
finish());
319 TEST(AdaptiveHuffman, ArbitraryChunksMatchWholeMessage)
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)
326 SCOPED_TRACE(alphabet);
328 const size_t length =
rng() % 1025;
330 for (
size_t i = 0; i < length; ++i)
331 input.push_back(
static_cast<char>(
rng() % alphabet));
335 whole_encoder.
encode(input, whole_bits);
336 for (
size_t i = 0; i < input.size();)
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);
342 ASSERT_TRUE(chunk_bits == whole_bits);
346 for (
size_t i = 0; i < chunk_bits.
size();)
348 const size_t end = std::min<size_t>(i + 1 +
rng() % 37, chunk_bits.
size());
352 EXPECT_NO_THROW(decoder.
finish());
357 TEST(AdaptiveHuffman, EveryPartialCodewordCanBeResumed)
361 const std::string input =
"abcdefghiaaf abracadabra";
362 for (
const unsigned char byte : input)
366 for (
size_t cut = 1; cut <
bits.size(); ++cut)
368 auto partial = decoder;
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)));
382 TEST(AdaptiveHuffman, RejectsNonBinaryBitsWithoutChangingState)
385 unsigned char output = 99;
386 for (
const unsigned int bit : {0u, 1u, 0u})
392 decoder.
decode(bit_literal(
"00001"), text);
393 EXPECT_NO_THROW(decoder.
finish());
394 EXPECT_EQ(text,
"A");
397 TEST(AdaptiveHuffman, RejectsKnownByteIntroducedThroughNYT)
402 EXPECT_THROW(decoder.
decode(bit_literal(
"0" "01000001"),
output), std::invalid_argument);
407 unsigned char byte = 99;
408 EXPECT_THROW(decoder.
decode_bit(1,
byte), std::domain_error);
409 EXPECT_THROW(decoder.
finish(), std::domain_error);
416 EXPECT_NO_THROW(decoder.
finish());
419 TEST(AdaptiveHuffman, RejectsNYTAfterTheWholeAlphabetWasSeen)
425 for (
int symbol = 0; symbol < 256; ++symbol)
427 encoder.
encode(
static_cast<unsigned char>(symbol),
bits);
428 model.update(
static_cast<unsigned char>(symbol));
434 for (
int node = model.nyt; model.nodes[node].parent != -1;)
436 const int parent = model.nodes[node].parent;
437 path.push_back(model.nodes[parent].left == node ?
'0' :
'1');
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);
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);
454 EXPECT_NO_THROW(decoder.
finish());
459 TEST(AdaptiveHuffman, MalformedChunkKeepsTheBytesBeforeTheBadCodeword)
463 encoder.
encode(
"AB", chunk);
464 for (
const char c :
std::string(
"00" "01000001"))
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");
471 EXPECT_THROW(decoder.
finish(), std::domain_error);
477 TEST(AdaptiveHuffman, EncodeByteReturnsTheBitsItAppended)
482 size_t unseen_deep = 0;
483 for (
const unsigned char byte :
std::string_view(
"abracadabra: every byte reports its own bits"))
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);
491 EXPECT_GE(returned, 8u);
492 unseen_deep += returned > 8;
496 EXPECT_GE(returned, 1u);
500 EXPECT_GT(known, 0u);
501 EXPECT_GT(unseen_deep, 0u);
507 TEST(AdaptiveHuffman, FibonacciFrequenciesGiveCodewordsAsDeepAsTheAlphabet)
509 constexpr int distinct = 20;
513 for (
int symbol = 0; symbol < distinct; ++symbol)
515 input.append(a,
static_cast<char>(200 + symbol));
516 const auto next = a + b;
524 for (
int symbol = 0; symbol < distinct; ++symbol)
526 auto probe = encoder;
528 longest = std::max(longest, probe.encode(
static_cast<unsigned char>(200 + symbol),
code));
530 EXPECT_EQ(longest,
static_cast<size_t>(distinct));
534 EXPECT_NO_THROW(decoder.
finish());
538 TEST(AdaptiveHuffman, ResetRestoresInitialWireFormatAndPendingState)
547 encoder.
encode(
'\0', next_bits);
559 EXPECT_NO_THROW(decoder.
finish());
562 EXPECT_EQ(
bits.get_bit_str(),
"01000001");
568 TEST(AdaptiveHuffman, CopiesOwnIndependentModelsAndPartialLiterals)
574 BitArray original_suffix, copied_suffix;
575 encoder.
encode(
"aaaa", original_suffix);
576 copy.encode(
"bcde", copied_suffix);
578 EXPECT_EQ(
copy.frequency(
'a'), 1u);
586 decoder.
decode(bit_literal(
"010"), ignored);
587 auto decoder_copy = decoder;
589 decoder.
decode(bit_literal(
"00001"), a);
590 decoder_copy.decode(bit_literal(
"00010"), b);
594 EXPECT_EQ(decoder_copy.frequency(
'A'), 0u);
595 EXPECT_NO_THROW(decoder.
finish());
596 EXPECT_NO_THROW(decoder_copy.finish());
599 TEST(AdaptiveHuffman, BitArrayPersistencePreservesFraming)
601 const std::string input(
"\0\xff\0 binary\n\xff", 12);
605 std::stringstream storage;
608 loaded.
load(storage);
609 EXPECT_TRUE(loaded ==
bits);
613 EXPECT_NO_THROW(decoder.
finish());
617 TEST(AdaptiveHuffmanTree, ExhaustiveShortTernarySequencesKeepSiblingProperty)
621 check_model(model, counts);
622 size_t combinations = 1;
623 for (
size_t length = 1; length <= 7; ++length)
626 for (
size_t sequence = 0; sequence < combinations; ++sequence)
630 size_t digits = sequence;
631 for (
size_t i = 0; i < length; ++i)
633 const auto byte =
static_cast<unsigned char>(digits % 3);
637 ASSERT_NO_FATAL_FAILURE(check_model(model, counts));
639 ASSERT_EQ(tree_cost(model), optimal_cost(counts));
644 TEST(AdaptiveHuffmanTree, RandomUpdatesRemainOptimalForCurrentFrequencies)
648 std::mt19937
rng(0xf6c123u);
651 for (
size_t i = 0; i < 6000; ++i)
653 const unsigned int alphabet = i < 2000 ? 256 : (i < 4000 ? 3 : 64);
654 const auto byte =
static_cast<unsigned char>(
rng() % alphabet);
657 ASSERT_NO_FATAL_FAILURE(check_model(model, counts));
658 ASSERT_EQ(tree_cost(model), optimal_cost(counts)) <<
"Update " << i;
662 TEST(AdaptiveHuffmanTree, CounterLimitDoesNotWrapAndResetRecovers)
665 constexpr unsigned char a =
'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());
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);
676 EXPECT_NO_THROW(model.check_capacity());
677 EXPECT_EQ(model.nodes[Model::root].weight, 0u);
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.
void set_bit_str(const std::string &str)
void load(std::istream &input)
Loads an array of bits saved with save().
void push(const unsigned int value)
Inserts the value at the end of the array.
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
Minimal std::expected-style result type for C++20.
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.
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).
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.