-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_huffman.cc
79 lines (64 loc) · 1.91 KB
/
test_huffman.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Eriksen Liu
/*
* test_huffman: test the Huffman class
*/
#include "huffman.hh"
#include <iostream>
#include <cassert>
#include <climits>
//////////////////////////////////////////////////////////////////////////////
// Ensure the encoder actually modifies the coding' length as expected
void test_encode()
{
Huffman huff;
auto bits = huff.encode('a');
assert(bits.size() >= CHAR_BIT);
bits = huff.encode('b');
assert(bits.size() >= CHAR_BIT);
bits = huff.encode('a');
assert(bits.size() < CHAR_BIT);
bits = huff.encode('b');
assert(bits.size() < CHAR_BIT);
bits = huff.encode('b');
assert(bits.size() == huff.encode('a').size());
bits = huff.encode('b');
bits = huff.encode('b');
bits = huff.encode('b');
assert(bits.size() < huff.encode('a').size());
}
//////////////////////////////////////////////////////////////////////////////
// A utility function that takes a collection of bits and a Huffman tree, and
// figures out which symbol these bits encode.
int decode_symbol(Huffman& huff, const Huffman::bits_t& bits)
{
int symbol = -1;
for (auto b : bits) {
symbol = huff.decode(b);
}
assert(symbol >= 0);
return symbol;
}
//////////////////////////////////////////////////////////////////////////////
// Ensure decoding returns the same symbol that was encoded, in different
// scenarios.
void test_decode()
{
Huffman encoder, decoder;
auto bits = encoder.encode('a');
assert(decode_symbol(decoder, bits) == 'a');
bits = encoder.encode('a');
assert(decode_symbol(decoder, bits) == 'a');
bits = encoder.encode('b');
assert(decode_symbol(decoder, bits) == 'b');
bits = encoder.encode('a');
assert(decode_symbol(decoder, bits) == 'a');
bits = encoder.encode(Huffman::HEOF);
assert(decode_symbol(decoder, bits) == Huffman::HEOF);
}
//////////////////////////////////////////////////////////////////////////////
int main()
{
test_encode();
test_decode();
return 0;
}