Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
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
45#include <gtest/gtest.h>
46
47#include "allocation_failure.H"
48
49#include <algorithm>
50#include <iterator>
51#include <new>
52#include <string>
53#include <utility>
54#include <vector>
55
56#include <Huffman.H>
57
58using namespace Aleph;
59
60namespace
61{
62 // The tests need the operator new of allocation_failure.H
63 struct HuffmanWithoutMemory : public ::testing::Test
64 {
65 void SetUp() override
66 {
68 GTEST_SKIP() << "ThreadSanitizer replaces the global operator new";
69 }
70 };
71
72 // The leaves of the tree of root p
73 size_t leaves(BinNode<std::string> *p)
74 {
75 if (p == nullptr)
76 return 0;
77 if (LLINK(p) == nullptr and RLINK(p) == nullptr)
78 return 1;
79 return leaves(LLINK(p)) + leaves(RLINK(p));
80 }
81
82 // The allocation k of add fails, for each k until add needs no more.
83 // Then the encoder takes the symbol with memory, and its tree must have
84 // two leaves, x and the symbol: a freed leaf left in the heap is a third
85 template <class Add>
86 void expect_two_leaves(Add add)
87 {
88 for (size_t k = 1; ; ++k)
89 {
90 SCOPED_TRACE(testing::Message() << "allocation " << k);
92 encoder.set_freq("x", 3);
93
94 bool thrown = false;
95 {
96 Fail_At failing(k);
97 try
98 {
99 add(encoder);
100 }
101 catch (const std::bad_alloc &)
102 {
103 thrown = true;
104 }
105 }
106
107 if (thrown)
108 add(encoder);
110 EXPECT_EQ(leaves(root), 2u);
111 destroyRec(root); // the tree is of the caller
112 if (not thrown)
113 break;
114 }
115 }
116
117 // Longer than the buffer of a short string: copying it allocates
118 const std::string Symbol = "a symbol longer than a short string";
119}
120
121TEST_F(HuffmanWithoutMemory, SetFreqLeavesTheEncoderAsItWas)
122{
123 expect_two_leaves([](Huffman_Encoder_Engine & e) { e.set_freq(Symbol, 5); });
124}
125
126// The end symbol was copied after it entered the heap and the map: without
127// memory for the copy, the encoder had the symbol, but not as its end, and
128// it could not take it again
129TEST_F(HuffmanWithoutMemory, SetEndOfStreamLeavesTheEncoderAsItWas)
130{
131 expect_two_leaves([](Huffman_Encoder_Engine & e) { e.set_end_of_stream(Symbol); });
132}
133
134namespace
135{
136 // Symbols longer than the buffer of a short string, some of them with
137 // the same frequency
138 const std::pair<std::string, size_t> Symbols[] = {
139 {"the first symbol, longer than a short string", 5},
140 {"the second symbol, longer than a short string", 2},
141 {"the third symbol, longer than a short string", 2},
142 {"the fourth symbol, longer than a short string", 9},
143 {"the fifth symbol, longer than a short string", 1},
144 {"x", 1},
145 {"y", 7}
146 };
147
148 using One_More = std::pair<std::string, size_t>;
149
150 void fill(Huffman_Encoder_Engine & encoder)
151 {
152 for (const auto & [symbol, freq] : Symbols)
153 encoder.set_freq(symbol, freq);
154 }
155
156 // The bits that the tree of root p takes for the frequencies: the sum of
157 // the frequency of each symbol times the depth of its leaf. `seen` takes
158 // the symbol of each leaf
159 size_t cost(BinNode<std::string> *p, const size_t depth, std::vector<std::string> & seen,
160 const One_More & one_more = {})
161 {
162 if (LLINK(p) == nullptr and RLINK(p) == nullptr)
163 {
164 seen.push_back(p->get_key());
165 if (one_more.second != 0 and one_more.first == p->get_key())
166 return one_more.second * depth;
167 for (const auto & [symbol, freq] : Symbols)
168 if (symbol == p->get_key())
169 return freq * depth;
170 return 0; // not a symbol: the_symbols_once() says so
171 }
172 return cost(LLINK(p), depth + 1, seen, one_more) + cost(RLINK(p), depth + 1, seen, one_more);
173 }
174
175 // True if the leaves have each symbol once, and nothing else: a tree
176 // with a symbol twice and without another one of the same frequency
177 // would cost the same
178 testing::AssertionResult the_symbols_once(std::vector<std::string> seen, const One_More & one_more = {})
179 {
180 std::vector<std::string> expected;
181 for (const auto & [symbol, freq] : Symbols)
182 expected.push_back(symbol);
183 if (one_more.second != 0)
184 expected.push_back(one_more.first);
185 std::sort(expected.begin(), expected.end());
186 std::sort(seen.begin(), seen.end());
187 if (seen == expected)
188 return testing::AssertionSuccess();
189 auto failure = testing::AssertionFailure() << seen.size() << " leaves for " << expected.size()
190 << " symbols:";
191 for (const auto & symbol : seen)
192 failure << " [" << symbol << "]";
193 return failure;
194 }
195
196 // In a tree of frequencies, each node that is not a leaf has the sum of
197 // those of its two children. It gives the frequency of p
198 size_t frequency(Freq_Node *p)
199 {
200 if (LLINK(p) == nullptr and RLINK(p) == nullptr)
201 return p->get_key().second;
202 const size_t sum = frequency(LLINK(p)) + frequency(RLINK(p));
203 EXPECT_EQ(p->get_key().second, sum) << "at the node " << p->get_key().first;
204 return sum;
205 }
206}
207
208// generate_huffman_tree() took two nodes out of the heap before it made
209// the one that joins them, and built the map of the codes with the tree
210// already out of the heap. Without memory for any of that, the nodes and
211// the trees that were out were lost, and the map of the symbols kept nodes
212// that the generation had freed. It now undoes what it did: the encoder
213// has its symbols and their frequencies, and generates the tree again.
214TEST_F(HuffmanWithoutMemory, GenerateLeavesTheEncoderAsItWas)
215{
216 size_t optimal = 0;
217 size_t total = 0;
218 for (const auto & [symbol, freq] : Symbols)
219 total += freq;
220 {
222 fill(encoder);
223 encoder.generate_huffman_tree();
224 std::vector<std::string> seen;
225 optimal = cost(encoder.get_root(), 0, seen);
226 EXPECT_TRUE(the_symbols_once(seen));
227 destroyRec(encoder.get_root()); // the encoder does not free its tree
228 }
229
230 for (const bool with_freqs : {false, true})
231 {
232 size_t failed = 0;
233 for (size_t k = 1; ; ++k)
234 {
235 SCOPED_TRACE(testing::Message() << "allocation " << k << ", with_freqs " << with_freqs);
237 fill(encoder);
238
239 bool thrown = false;
240 {
241 Fail_At failing(k);
242 try
243 {
244 encoder.generate_huffman_tree(with_freqs);
245 }
246 catch (const std::bad_alloc &)
247 {
248 thrown = true;
249 }
250 }
251
252 if (thrown)
253 {
254 ++failed;
255 // its symbols are there, and their nodes alive
256 for (const auto & [symbol, freq] : Symbols)
257 EXPECT_THROW(encoder.set_freq(symbol, freq), std::domain_error);
258 EXPECT_THROW(encoder.get_root(), std::domain_error);
259 encoder.generate_huffman_tree(with_freqs);
260 }
261 std::vector<std::string> seen;
262 EXPECT_EQ(cost(encoder.get_root(), 0, seen), optimal);
263 EXPECT_TRUE(the_symbols_once(seen));
264 destroyRec(encoder.get_root());
265 if (with_freqs)
266 {
267 EXPECT_EQ(frequency(encoder.get_freq_root()), total);
268 destroyRec(encoder.get_freq_root());
269 }
270 if (not thrown)
271 break;
272 }
273 EXPECT_GT(failed, 2 * std::size(Symbols)); // the nodes of each step, and the codes
274 }
275}
276
277// After a generation that failed, the encoder takes one symbol more, of the
278// least frequency, and its tree is the best one for them all: nothing of
279// what the generation joined stays joined
280TEST_F(HuffmanWithoutMemory, AFailedGenerationTakesMoreSymbols)
281{
282 const One_More one_more = {"one more symbol, longer than a short string", 1};
283
284 size_t optimal = 0;
285 {
287 fill(encoder);
288 encoder.set_freq(one_more.first, one_more.second);
289 encoder.generate_huffman_tree();
290 std::vector<std::string> seen;
291 optimal = cost(encoder.get_root(), 0, seen, one_more);
292 EXPECT_TRUE(the_symbols_once(seen, one_more));
293 destroyRec(encoder.get_root());
294 }
295
296 size_t failed = 0;
297 for (size_t k = 1; ; ++k)
298 {
299 SCOPED_TRACE(testing::Message() << "allocation " << k);
301 fill(encoder);
302 bool thrown = false;
303 {
304 Fail_At failing(k);
305 try
306 {
307 encoder.generate_huffman_tree();
308 }
309 catch (const std::bad_alloc &)
310 {
311 thrown = true;
312 }
313 }
314 if (not thrown)
315 {
316 destroyRec(encoder.get_root());
317 break;
318 }
319 ++failed;
320 encoder.set_freq(one_more.first, one_more.second);
321 encoder.generate_huffman_tree();
322 std::vector<std::string> seen;
323 EXPECT_EQ(cost(encoder.get_root(), 0, seen, one_more), optimal);
324 EXPECT_TRUE(the_symbols_once(seen, one_more));
325 destroyRec(encoder.get_root());
326 }
327 EXPECT_GT(failed, 2 * std::size(Symbols));
328}
329
330// The tree of one symbol is its leaf: the node of the symbol is the last
331// one of the heap, and it is freed once. Its tree of frequencies is a leaf
332// too, which the encoder did not make: get_freq_root() threw
333TEST_F(HuffmanWithoutMemory, OneSymbolGeneratesItsLeaf)
334{
335 for (const bool with_freqs : {false, true})
336 {
337 size_t failed = 0;
338 for (size_t k = 1; ; ++k)
339 {
340 SCOPED_TRACE(testing::Message() << "allocation " << k << ", with_freqs " << with_freqs);
342 encoder.set_freq(Symbol, 3);
343 bool thrown = false;
344 {
345 Fail_At failing(k);
346 try
347 {
348 encoder.generate_huffman_tree(with_freqs);
349 }
350 catch (const std::bad_alloc &)
351 {
352 thrown = true;
353 }
354 }
355 if (thrown)
356 {
357 ++failed;
358 encoder.generate_huffman_tree(with_freqs);
359 }
361 EXPECT_EQ(leaves(root), 1u);
362 EXPECT_EQ(root->get_key(), Symbol);
363 destroyRec(encoder.get_root());
364 if (with_freqs)
365 {
366 Freq_Node *freq_root = encoder.get_freq_root();
367 EXPECT_EQ(LLINK(freq_root), nullptr);
368 EXPECT_EQ(RLINK(freq_root), nullptr);
369 EXPECT_EQ(freq_root->get_key().first, Symbol);
370 EXPECT_EQ(freq_root->get_key().second, 3u);
371 destroyRec(encoder.get_freq_root());
372 }
373 else
374 EXPECT_THROW(encoder.get_freq_root(), std::domain_error);
375 if (not thrown)
376 break;
377 }
378 EXPECT_GT(failed, 0u);
379 }
380}
381
382// A generation that fails leaves no node of frequencies in the symbols:
383// one would keep the frequency of that moment, and read_input() counts on
384char abc_input[] = "abracadabra, a cab";
385
386TEST_F(HuffmanWithoutMemory, AFailedGenerationKeepsNoFrequencyOfItsOwn)
387{
388 const size_t length = std::string(abc_input).size();
389 size_t failed = 0;
390 size_t counted_twice = 0;
391 for (size_t k = 1; ; ++k)
392 {
393 SCOPED_TRACE(testing::Message() << "allocation " << k);
395 bool thrown = false;
396 {
397 Fail_At failing(k);
398 try
399 {
400 encoder.read_input(abc_input, true);
401 }
402 catch (const std::bad_alloc &)
403 {
404 thrown = true;
405 }
406 }
407 // read_input() sets the end symbol once it has counted its input: a
408 // failure after that is of the generation, and the retry counts the
409 // whole input again
410 const bool counted = thrown and encoder.get_end_of_stream() != "NO-END";
411 if (thrown)
412 {
413 ++failed;
414 encoder.read_input(abc_input, true); // it counts on what it had
415 }
416 const size_t total = frequency(encoder.get_freq_root());
417 if (not thrown)
418 EXPECT_EQ(total, length);
419 else if (counted)
420 {
421 ++counted_twice;
422 EXPECT_EQ(total, 2 * length);
423 }
424 else // it failed while it counted, or when the end symbol entered
425 {
426 EXPECT_GE(total, length);
427 EXPECT_LE(total, 2 * length);
428 }
429 destroyRec(encoder.get_root());
430 destroyRec(encoder.get_freq_root());
431 if (not thrown)
432 break;
433 }
434 EXPECT_GT(failed, 10u);
435 EXPECT_GT(counted_twice, 10u); // failures of the generation itself
436}
Huffman coding for data compression.
A global operator new that a test can make fail.
#define ALEPH_ALLOCATION_FAILURE_UNDER_TSAN
Node for binary search tree.
Key & get_key() noexcept
Freq_Node *& get_freq_root()
Returns the root of the frequency tree.
Definition Huffman.H:485
BinNode< std::string > *& get_root()
Returns the root of the Huffman decoding tree.
Definition Huffman.H:390
void set_freq(const std::string &str, const size_t &freq)
Define the frequency of a symbol.
Definition Huffman.H:501
void read_input(char *input, const bool &with_freqs=false)
Read a NUL-terminated character std::string, count frequencies and build the prefix tree.
Definition Huffman.H:609
void set_end_of_stream(const std::string &str)
Defines the end-of-stream symbol.
Definition Huffman.H:664
const std::string & get_end_of_stream() const noexcept
Return the configured end-of-stream symbol.
Definition Huffman.H:679
BinNode< std::string > * generate_huffman_tree(const bool &with_freqs=false)
Generate the Huffman prefix tree.
Definition Huffman.H:414
Minimal std::expected-style result type for C++20.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
void destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
TEST_F(HuffmanWithoutMemory, SetFreqLeavesTheEncoderAsItWas)
char abc_input[]
Main namespace for Aleph-w library functions.
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
and
Check uniqueness with explicit hash + equality functors.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
static void set_freq(Huffman_Node *huffman_node, const size_t &freq) noexcept
Definition Huffman.H:103
double add(double a, double b)
#define RLINK(i, n)
#define LLINK(i, n)
static int * k