Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
huffman.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
32
38#include <gtest/gtest.h>
39
40#include <Huffman.H>
41
42#include <tpl_binNodeUtils.H>
43
44#include <random>
45#include <sstream>
46#include <string>
47#include <vector>
48
49using namespace Aleph;
50using namespace std;
51
52namespace {
53
54vector<char> to_c_buffer(const string &s)
55{
56 vector<char> buf;
57 buf.reserve(s.size() + 1);
58 buf.insert(buf.end(), s.begin(), s.end());
59 buf.push_back('\0');
60 return buf;
61}
62
63string decode_bits(BinNode<string> *root, const string &end_symbol, BitArray &bits)
64{
65 Huffman_Decoder_Engine decoder(root, end_symbol);
66 ostringstream out;
67 decoder.decode(bits, out);
68 return out.str();
69}
70
71TEST(HuffmanCharAPI, roundtrip_with_whitespace_and_freq_tree)
72{
73 const string input = "hello world\nthis\tis a test\n";
74 auto buf = to_c_buffer(input);
75
78
79 encoder.read_input(buf.data(), true);
80 encoder.encode(buf.data(), bits);
81
82 EXPECT_EQ(encoder.get_end_of_stream(), string(""));
83 EXPECT_GT(bits.size(), 0u);
84
85 EXPECT_EQ(decode_bits(encoder.get_root(), encoder.get_end_of_stream(), bits), input);
86
87 destroyRec(encoder.get_root());
88 destroyRec(encoder.get_freq_root());
89}
90
91TEST(HuffmanStreamAPI, no_eof_off_by_one_on_read_and_encode)
92{
93 const string input = "A";
94 istringstream in1(input);
95
97 encoder.read_input(in1, false);
98
99 istringstream in2(input);
101 encoder.encode(in2, bits);
102
103 EXPECT_EQ(decode_bits(encoder.get_root(), encoder.get_end_of_stream(), bits), input);
104
105 destroyRec(encoder.get_root());
106}
107
108// load_tree() drops the symbols that the encoder was counting. Once the
109// tree that it loaded is freed, the encoder counts and generates again: it
110// must not keep the nodes of the symbols that it dropped.
111TEST(HuffmanPersistence, an_encoder_that_loaded_a_tree_counts_symbols_again)
112{
113 ostringstream out;
114 {
116 source.set_freq("a", 5);
117 source.set_freq("b", 2);
118 source.generate_huffman_tree();
119 source.save_tree(out);
120 destroyRec(source.get_root());
121 }
122
124 encoder.set_freq("x", 3);
125 encoder.set_freq("y", 4);
126 encoder.set_freq("z", 9);
127 istringstream in(out.str());
128 encoder.load_tree(in); // x, y and z are dropped
129 EXPECT_FALSE(is_leaf(encoder.get_root()));
130 destroyRec(encoder.get_root());
131
132 encoder.set_freq("x", 1);
133 encoder.set_freq("w", 6);
135 ASSERT_FALSE(is_leaf(root));
136 EXPECT_TRUE(is_leaf(LLINK(root)));
137 EXPECT_TRUE(is_leaf(RLINK(root)));
138 const string left = LLINK(root)->get_key();
139 const string right = RLINK(root)->get_key();
140 EXPECT_TRUE((left == "x" and right == "w") or (left == "w" and right == "x"));
141 EXPECT_EQ(encoder.get_freq_root()->get_key().second, 7u);
142 destroyRec(encoder.get_root());
143 destroyRec(encoder.get_freq_root());
144}
145
146TEST(HuffmanPersistence, save_load_tree_and_encode_roundtrip)
147{
148 const string input = "a b\nc\tdd\n";
149 auto buf = to_c_buffer(input);
150
152 encoder.read_input(buf.data(), false);
153
154 BitArray bits1;
155 encoder.encode(buf.data(), bits1);
156
157 ostringstream out;
158 encoder.save_tree(out);
159
161 istringstream in(out.str());
162 loaded.load_tree(in);
163
164 EXPECT_TRUE(areEquivalents(encoder.get_root(), loaded.get_root()));
165 EXPECT_EQ(loaded.get_end_of_stream(), encoder.get_end_of_stream());
166
167 BitArray bits2;
168 loaded.encode(buf.data(), bits2);
169 EXPECT_TRUE(bits1 == bits2);
170 EXPECT_EQ(decode_bits(loaded.get_root(), loaded.get_end_of_stream(), bits2), input);
171
172 destroyRec(encoder.get_root());
173 destroyRec(loaded.get_root());
174}
175
176TEST(HuffmanDecoder, stops_at_end_symbol_and_ignores_trailing_bits)
177{
178 const string input = "aba";
179 auto buf = to_c_buffer(input);
180
182 encoder.read_input(buf.data(), false);
183
185 encoder.encode(buf.data(), bits);
186
187 BitArray extended = bits;
188 extended.push(1);
189 extended.push(0);
190 extended.push(1);
191
192 EXPECT_EQ(decode_bits(encoder.get_root(), encoder.get_end_of_stream(), extended), input);
193
194 destroyRec(encoder.get_root());
195}
196
197TEST(HuffmanRandomized, matches_reference_roundtrip)
198{
199 mt19937 rng(123456u);
200 uniform_int_distribution<int> len_dist(0, 200);
201 const string alphabet = "abcde fghij\n\t";
202 uniform_int_distribution<size_t> pick(0, alphabet.size() - 1);
203
204 for (int iter = 0; iter < 50; ++iter)
205 {
206 const int len = len_dist(rng);
207 string input;
208 input.reserve(static_cast<size_t>(len));
209 for (int i = 0; i < len; ++i)
210 input.push_back(alphabet[pick(rng)]);
211
212 auto buf = to_c_buffer(input);
213
215 encoder.read_input(buf.data(), false);
216
218 encoder.encode(buf.data(), bits);
219
220 EXPECT_EQ(decode_bits(encoder.get_root(), encoder.get_end_of_stream(), bits), input);
221
222 destroyRec(encoder.get_root());
223 }
224}
225
226TEST(HuffmanErrors, encode_without_tree_throws)
227{
230 char input[] = "x";
231 EXPECT_THROW(encoder.encode(input, bits), std::domain_error);
232}
233
234TEST(HuffmanErrors, set_end_of_stream_twice_throws)
235{
237 encoder.set_end_of_stream("END");
238 EXPECT_THROW(encoder.set_end_of_stream("OTHER"), std::domain_error);
239}
240
241TEST(HuffmanErrors, generate_without_symbols_throws)
242{
244 EXPECT_THROW((void) encoder.generate_huffman_tree(false), std::domain_error);
245}
246
247} // namespace
248
Huffman coding for data compression.
size_t size_t int32_t * out
Definition ca-c-api.h:120
Node for binary search tree.
Key & get_key() noexcept
Contiguous array of bits.
Definition bitArray.H:201
void push(const unsigned int value)
Inserts the value at the end of the array.
Definition bitArray.H:506
Freq_Node *& get_freq_root()
Returns the root of the frequency tree.
Definition Huffman.H:485
void save_tree(std::ostream &output) const
Save a Huffman tree into a stream.
Definition Huffman.H:350
size_t encode(char *input, BitArray &bit_stream)
Encode the input text.
Definition Huffman.H:694
void load_tree(std::istream &input)
Load and build a binary tree from a stream.
Definition Huffman.H:467
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
#define TEST(name)
static mt19937 rng
__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
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].
bool areEquivalents(Node *t1, Node *t2, Equal &op) noexcept
Return true if trees are equivalents.
and
Check uniqueness with explicit hash + equality functors.
static bool is_leaf(BinNode< std::string > *p) noexcept
Definition Huffman.H:109
STL namespace.
#define RLINK(i, n)
#define LLINK(i, n)
Utility functions for binary tree operations.