2 * @file test_huff_code.c Test Huffman coding
3 * @author David Huggins-Daines <dhuggins@cs.cmu.edu>
7 #include "test_macros.h"
13 int32 const ivalues[10] = {
14 1, 2, 3, 5, 7, 11, 13, 17, 19, 23
16 int32 const frequencies[10] = {
17 42, 4, 5, 6, 225, 15001, 3, 2, 87, 1003
19 char * const svalues[10] = {
20 "foo", "bar", "baz", "quux", "argh",
21 "hurf", "burf", "blatz", "unf", "woof"
23 char * const svalues2[10] = {
24 "1","2","3","4","5","6","7","8","9","10"
26 char const cdata[7] = { 0x08, 0x30, 0x40, 0x4c, 0x00, 0x04, 0x50 };
29 test_intcode(huff_code_t *hc)
37 fh = fopen("hufftest.out", "wb");
38 huff_code_attach(hc, fh, "wb");
39 for (i = 0; i < 10; ++i) {
40 huff_code_encode_int(hc, ivalues[i], NULL);
44 fh = fopen("hufftest.out", "rb");
45 huff_code_attach(hc, fh, "rb");
46 for (i = 0; i < 10; ++i) {
48 huff_code_decode_int(hc, &val, NULL, NULL, 0);
50 TEST_EQUAL(val, ivalues[i]);
59 for (i = 0; i < 10; ++i) {
60 huff_code_decode_int(hc, &val, &dptr, &dlen, &offset);
62 TEST_EQUAL(val, ivalues[i]);
65 TEST_EQUAL(offset, 4);
72 while (huff_code_decode_int(hc, &val, &dptr, &dlen, &offset) != -1) {
74 TEST_EQUAL(val, ivalues[i++]);
77 TEST_EQUAL(offset, 4);
82 test_strcode(huff_code_t *hc, char * const *svalues)
89 fh = fopen("hufftest.out", "wb");
90 huff_code_attach(hc, fh, "wb");
91 for (i = 9; i >= 0; --i) {
92 huff_code_encode_str(hc, svalues[i], NULL);
96 fh = fopen("hufftest.out", "rb");
97 huff_code_attach(hc, fh, "rb");
98 for (i = 9; i >= 0; --i) {
99 char const *val = huff_code_decode_str(hc, NULL, NULL, 0);
101 TEST_EQUAL(0, strcmp(val, svalues[i]));
104 huff_code_detach(hc);
110 for (i = 0; i < 10; ++i) {
111 char const *val = huff_code_decode_str(hc, &dptr, &dlen, &offset);
113 TEST_EQUAL(0, strcmp(val, svalues[i]));
116 TEST_EQUAL(offset, 4);
121 main(int argc, char *argv[])
126 hc = huff_code_build_int(ivalues, frequencies, 10);
127 huff_code_dump(hc, stdout);
129 fh = fopen("huffcode.out", "wb");
130 huff_code_write(hc, fh);
134 fh = fopen("huffcode.out", "rb");
135 hc = huff_code_read(fh);
140 hc = huff_code_build_str(svalues, frequencies, 10);
141 huff_code_dump(hc, stdout);
142 test_strcode(hc, svalues);
143 fh = fopen("huffcode.out", "wb");
144 huff_code_write(hc, fh);
148 fh = fopen("huffcode.out", "rb");
149 hc = huff_code_read(fh);
151 test_strcode(hc, svalues);
154 hc = huff_code_build_str(svalues2, frequencies, 10);
155 huff_code_dump(hc, stdout);
156 test_strcode(hc, svalues2);