summaryrefslogtreecommitdiff
path: root/huffman/huffman.c
blob: eb388c5406eb33c17fc174da4b3a66e28c7e9df6 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// ================================================================================================
// Huffman encoding demo
//
// ref: https://en.wikipedia.org/wiki/Huffman_coding#Basic_technique
//
// Changelog:
//     9/29/2026: Initial release
//     10/1/2026: Added decode + round-trip check
//
// License:
//     Copyright (c) 2026 Hunter Kvalevog
//
//     Permission to use, copy, modify, and/or distribute this software for any
//     purpose with or without fee is hereby granted.
//
//     THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
//     WITH REGARD TO THIS SOFTWARE.
// ================================================================================================

#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#define DEBUG

#ifdef __GNUC__
#  define ATTR_NORETURN       __attribute__((noreturn))
#  define ATTR_PRINTF(A1, A2) __attribute__((format(printf, A1, A2)))
#else
#  define ATTR_NORETURN
#  define ATTR_PRINTF(A1, A2)
#endif

ATTR_NORETURN
ATTR_PRINTF(1, 2)
static void die(const char *fmt, ...)
{
    va_list va; va_start(va, fmt);
    vprintf(fmt, va);
    va_end(va);

    exit(1);
}

// bit writer
typedef struct BitW BitW;
struct BitW
{
    uint8_t *bbuf;
    size_t   blen;
    size_t   cbyte;
    size_t   cbit;
};

static void write_bit(BitW *bw, uint8_t val)
{
    assert(!(val & ~1));
    assert(bw->cbyte < bw->blen);
    bw->bbuf[bw->cbyte] |= (val << (7 - bw->cbit));
    bw->cbit += 1;
    if (bw->cbit >= 8)
    {
        bw->cbyte += 1;
        bw->cbit = 0;
    }
}

static void write_bits(BitW *bw, uint64_t val, uint8_t len)
{
    for (uint8_t i = 0; i < len; ++i)
        write_bit(bw, (val >> (len - i - 1)) & 1);
}

// bit reader
typedef struct BitR BitR;
struct BitR
{
    const uint8_t *bbuf;
    size_t         blen;
    size_t         cbyte;
    size_t         cbit;
};

static uint8_t read_bit(BitR *br)
{
    assert(br->cbyte < br->blen);
    uint8_t bit = (br->bbuf[br->cbyte] >> (7 - br->cbit)) & 1;
    br->cbit += 1;
    if (br->cbit >= 8)
    {
        br->cbyte += 1;
        br->cbit = 0;
    }
    return bit;
}

static uint64_t read_bits(BitR *br, uint8_t len)
{
    uint64_t r = 0;
    for (size_t i = 0; i < len; ++i)
    {
        r <<= 1;
        r |= read_bit(br);
    }
    return r;
}

// This demo encodes raw bytes (domain [0, 255])
#define MAX_SYMBOLS 256

// In a Huffman tree, the number of internal nodes is always one less than the number of symbols.
// ...according to Wikipedia. I don't know how to prove this.
#define MAX_INTERNAL_NODES (MAX_SYMBOLS - 1)

#define MAX_NODES (MAX_SYMBOLS + MAX_INTERNAL_NODES)

typedef struct Node Node;
struct Node
{
    uint8_t sym;
    int32_t weight;

    Node *tl; // tree left
    Node *tr; // tree right

    Node *ln; // linked list next
};

static int sort_node_freq(const void *p1, const void *p2)
{
    const Node *n1 = p1;
    const Node *n2 = p2;
    return (n1->weight > n2->weight) - (n1->weight < n2->weight);
}

// arena allocator for internal nodes
static Node *new_node(void)
{
    static Node   buf[MAX_NODES * 2];
    static size_t idx = 0;
    assert(idx < MAX_NODES * 2);
    return &buf[idx++];
}

typedef struct Code Code;
struct Code
{
    uint64_t bits;
    uint8_t  len;
};

static void build_dictionary(Node *node, uint64_t bits, uint8_t len, Code *dictionary)
{
    // Huffman tree nodes always have 0 or 2 children
    if (!node->tl)
    {
        // leaf
        dictionary[node->sym].bits = bits;
        dictionary[node->sym].len  = len;
        return;
    }

    // internal
    build_dictionary(node->tl, (bits << 1) | 0, len + 1, dictionary); // left  = 0
    build_dictionary(node->tr, (bits << 1) | 1, len + 1, dictionary); // right = 1
}

static void write_tree(BitW *bw, Node *n)
{
    if (!n->tl)
    {
        // leaf
        write_bit(bw, 1);
        write_bits(bw, n->sym, 8);
        return;
    }

    // internal
    write_bit(bw, 0);
    write_tree(bw, n->tl);
    write_tree(bw, n->tr);
}

uint8_t *decompress(const uint8_t *bbuf, size_t blen, size_t *olen);

int main(int argc, char **argv)
{
    if (argc < 2)
        die("supply a file\n");

    FILE *f = fopen(argv[1], "rb");
    if (!f)
        die("failed to open file\n");

    fseek(f, 0, SEEK_END);
    const size_t ilen = ftell(f);
    fseek(f, 0, SEEK_SET);

    uint8_t *ibuf = malloc(ilen);
    fread(ibuf, 1, ilen, f);

    // Set of all possible symbols
    Node syms[MAX_SYMBOLS] = { 0 };
    for (size_t i = 0; i < MAX_SYMBOLS; ++i)
        syms[i].sym = i & 0xFF;

    // Count frequencies of symbols in input data
    for (size_t i = 0; i < ilen; ++i)
        syms[ibuf[i]].weight += 1;

    // Sort by frequency
    qsort(syms, MAX_SYMBOLS, sizeof(Node), sort_node_freq);
#ifdef DEBUG
    for (size_t i = 0; i < MAX_SYMBOLS; ++i)
        if (syms[i].weight)
            printf("'%c': %d\n", (char)syms[i].sym, syms[i].weight);
#endif

    // Linked list-ify
    Node *queue = 0;
    for (size_t i = 1; i <= MAX_SYMBOLS; ++i)
    {
        Node *n = &syms[MAX_SYMBOLS - i];
        if (n->weight)
        {
            n->ln = queue;
            queue = n;
        }
    }
#ifdef DEBUG
    for (Node *n = queue; n; n = n->ln)
        printf("'%c':%d->", (char)n->sym, n->weight);
    printf("0\n");
#endif
    assert(queue);

    // Single-node trees do not generate valid Huffman codes. Add a dummy leaf.
    if (!queue->ln)
    {
        Node *n = new_node();
        n->sym = queue->sym ^ 1; // some value other than the existing one
        n->ln = queue;
        queue = n;
    }

    // Combine the two lightest nodes
    while (queue->ln)
    {
        Node *n1 = queue;
        Node *n2 = queue->ln;
        Node *n3 = new_node();
        // n3 adopts n1 and n2
        n3->tl = n1;
        n3->tr = n2;
        n3->weight = n1->weight + n2->weight;
        // n1 and n2 are removed from the list
        queue = queue->ln->ln;
        n1->ln = 0;
        n2->ln = 0;
        // n3 is inserted back into the sorted queue
        Node **p = &queue;
        while (*p && (*p)->weight <= n3->weight)
            p = &(*p)->ln;
        n3->ln= *p;
        *p = n3;
    }

    // Traverse tree to build dictionary
    Code dictionary[MAX_SYMBOLS] = { 0 };
    build_dictionary(queue, 0, 0, dictionary);
#ifdef DEBUG
    for (size_t i = 0; i < MAX_SYMBOLS; ++i)
    {
        Code *c = &dictionary[i];
        if (!c->len)
            continue;
        printf("%c: ", (char)i);
        for (size_t j = 0; j < c->len; ++j)
        {
            uint8_t bit = (c->bits >> (c->len - j - 1)) & 1;
            printf(bit ? "1" : "0");
        }
        printf("\n");
    }
#endif
    // Calculate maximum possible tree payload len
    uint64_t max_tree_bits = 10 * MAX_SYMBOLS;

    // Calculate data payload len
    uint64_t data_bits = 0;
    for (size_t i = 0; i < ilen; ++i)
        data_bits += dictionary[ibuf[i]].len;

    BitW bw = { 0 };
    bw.blen = (32 + data_bits + max_tree_bits + 7) / 8; // in bytes, rounded up
    bw.bbuf = calloc(1, bw.blen); assert(bw.bbuf);

    write_bits(&bw, ilen, 32);
    write_tree(&bw, queue);
    for (size_t i = 0; i < ilen; ++i)
    {
        Code *c = &dictionary[ibuf[i]];
        write_bits(&bw, c->bits, c->len);
    }


    size_t   olen = 0;
    uint8_t *obuf = decompress(bw.bbuf, bw.blen, &olen);

    printf("input size:      %zu bits\n", ilen * 8);
    printf("compressed size: %zu bits\n", bw.cbyte * 8 + bw.cbit);
    printf("output size:     %zu bits\n", olen * 8);

    if (olen != ilen || memcmp(obuf, ibuf, ilen))
        die("round trip mismatch");

    printf("round-trip success\n");
}

static Node *read_tree(BitR *br)
{
    Node *n = new_node();

    if (read_bit(br))
    {
        // leaf
        n->sym = read_bits(br, 8);
        return n;
    }

    // internal
    n->tl = read_tree(br);
    n->tr = read_tree(br);
    return n;
}

static Node *traverse(BitR *br, Node *n)
{
    Node *p = read_bit(br) ? n->tr : n->tl;
    if (!p->tl)
        return p;
    return traverse(br, p);
}

uint8_t *decompress(const uint8_t *bbuf, size_t blen, size_t *olen)
{
    BitR br = { bbuf, blen, 0, 0 };

    *olen = read_bits(&br, 32);
    uint8_t *obuf = malloc(*olen);

    Node *root = read_tree(&br);

    for (size_t i = 0; i < *olen; ++i)
    {
        obuf[i] = traverse(&br, root)->sym;
    }

#ifdef DEBUG
    printf("%.*s\n", (int)*olen, (const char *)obuf);
#endif
    return obuf;
}