Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
adaptive_huffman_allocation_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
37#include <gtest/gtest.h>
38
39#include "allocation_failure.H"
40
41#include <cstddef>
42#include <new>
43#include <random>
44#include <stdexcept>
45#include <string>
46
47#include <Adaptive_Huffman.H>
48
49using namespace Aleph;
50
51namespace
52{
53 // The tests need the operator new of allocation_failure.H
54 struct AdaptiveHuffmanWithoutMemory : public ::testing::Test
55 {
56 void SetUp() override
57 {
59 GTEST_SKIP() << "ThreadSanitizer replaces the global operator new";
60 }
61 };
62
63 // A message of n bytes: a few frequent ones and the rest at random, so
64 // that the codewords have many lengths
65 std::string message(const size_t n)
66 {
67 std::mt19937 rng(213);
68 std::string text;
69 for (size_t i = 0; i < n; ++i)
70 text.push_back(static_cast<char>(rng() % 5 != 0 ? 'a' + rng() % 6 : rng() % 256));
71 return text;
72 }
73} // namespace
74
75// decode() counts a byte in its model before it appends it to the output.
76// When the output could not grow, the decoder was left one byte ahead of
77// it, and nothing said so: finish() accepted the state, going on gave the
78// message with that byte missing, and decoding the same chunk again
79// appended bytes that are not in the message. Now the decoder is left
80// failed, as after malformed input: every later call says so until reset().
81TEST_F(AdaptiveHuffmanWithoutMemory, ALostByteLeavesTheDecoderFailed)
82{
83 const std::string text = message(3000);
86 encoder.encode(text, bits);
87
88 const std::string prefix = "kept:";
89 size_t failures = 0;
90 for (size_t k = 1; ; ++k) // the growth of the output that fails
91 {
92 SCOPED_TRACE(testing::Message() << "growth " << k);
94 std::string output = prefix;
95 bool thrown = false;
96 {
97 Fail_At fail(k);
98 try
99 {
100 decoder.decode(bits, output);
101 }
102 catch (const std::bad_alloc &)
103 {
104 thrown = true;
105 }
106 }
107 if (not thrown)
108 {
109 EXPECT_EQ(output, prefix + text);
110 EXPECT_NO_THROW(decoder.finish());
111 break;
112 }
113 ++failures;
114
115 // The bytes before the lost one are in the output, and the decoder
116 // counted one more
117 const size_t kept = output.size() - prefix.size();
118 ASSERT_LT(kept, text.size());
119 EXPECT_EQ(output, prefix + text.substr(0, kept));
120 EXPECT_EQ(decoder.symbols_processed(), kept + 1);
121
122 EXPECT_THROW(decoder.finish(), std::domain_error);
123 unsigned char byte = 99;
124 EXPECT_THROW(decoder.decode_bit(0, byte), std::domain_error);
125 EXPECT_THROW(decoder.decode_bit(1, byte), std::domain_error);
126 EXPECT_EQ(byte, 99);
127 EXPECT_THROW(decoder.decode(bits, output), std::domain_error); // the same chunk again
128 EXPECT_EQ(output.size(), prefix.size() + kept);
129 EXPECT_EQ(decoder.symbols_processed(), kept + 1);
130
131 // After reset() the decoder starts the message again
132 decoder.reset();
133 output = prefix;
134 EXPECT_EQ(decoder.decode(bits, output), text.size());
135 EXPECT_EQ(output, prefix + text);
136 EXPECT_NO_THROW(decoder.finish());
137 }
138 EXPECT_GE(failures, 5u); // the output grew that many times
139}
140
141// decode_bit() allocates nothing, so a decoder that the caller feeds bit by
142// bit, appending to an output that it grows itself, can go on after its
143// output fails: the byte is in the caller's hands when it is decoded
144TEST_F(AdaptiveHuffmanWithoutMemory, DecodeBitLetsTheCallerGoOn)
145{
146 const std::string text = message(500);
149 encoder.encode(text, bits);
150
152 std::string output;
153 size_t refused = 0;
154 for (size_t i = 0; i < bits.size(); ++i)
155 {
156 unsigned char byte;
157 {
158 No_Memory none; // decode_bit() takes no memory
159 if (not decoder.decode_bit(static_cast<unsigned int>(bits[i]), byte))
160 continue;
161 }
162 // Each growth of the output fails once, and the caller tries again
163 for (bool refused_once = false; ;)
164 try
165 {
166 const bool grows = output.size() == output.capacity();
167 Fail_At fail(grows and not refused_once ? 1 : 0);
168 output.push_back(static_cast<char>(byte));
169 break;
170 }
171 catch (const std::bad_alloc &)
172 {
173 refused_once = true;
174 ++refused;
175 }
176 }
177 EXPECT_EQ(output, text);
178 EXPECT_NO_THROW(decoder.finish());
179 EXPECT_GE(refused, 4u); // the output grew that many times
180}
One-pass adaptive Huffman coding of bytes using FGK updates.
TEST_F(AdaptiveHuffmanWithoutMemory, ALostByteLeavesTheDecoderFailed)
A global operator new that a test can make fail.
#define ALEPH_ALLOCATION_FAILURE_UNDER_TSAN
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 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.
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.
Contiguous array of bits.
Definition bitArray.H:201
static mt19937 rng
Main namespace for Aleph-w library functions.
void message(const char *file, int line, const char *format,...)
Print an informational message with file and line info.
Definition ahDefs.C:95
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
static void prefix(Node *root, DynList< Node * > &acc)
and
Check uniqueness with explicit hash + equality functors.
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
static int * k
ofstream output
Definition writeHeap.C:215