summaryrefslogtreecommitdiff
path: root/huffman.c
blob: 596de6ce1eea383ba059281c9bf02b47b32c640a (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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <time.h>

#include "cleanbench.h"
#include "randnum.h"


/************************
** HUFFMAN COMPRESSION **
************************/

/*
** This constant specifies the maximum number of Huffman
** compression loops the system will try for.  This keeps
** the test from going off into the weeds.  This is not
** a critical constant, and can be increased if your
** system is a real barn-burner.
*/
/*#define LOOP_MAX 50000L*/
#define LOOP_MAX 500000L

/*
** Following constant sets the size of the arrays to
** be compressed/uncompressed.
*/
#define ARRAY_SIZE 5000

#define EXCLUDED 32000L          /* Big positive value */

typedef struct {
	unsigned char c;                /* Byte value */
	float freq;             /* Frequency */
	int parent;             /* Parent node */
	int left;               /* Left pointer = 0 */
	int right;              /* Right pointer = 1 */
} huff_node;

static huff_node *hufftree;             /* The huffman tree */

static void create_text_line(char *dt,long nchars);
static void create_text_block(char *tb, unsigned long tblen,
		unsigned short maxlinlen);
static clock_t DoHuffIteration(char *plaintext, char *comparray, char *decomparray,
	unsigned long nloops, huff_node *hufftree);
static void SetCompBit(uint8_t *comparray, uint32_t bitoffset, char bitchar);
static int GetCompBit(uint8_t *comparray, uint32_t bitoffset);

/**************
** DoHuffman **
***************
** Execute a huffman compression on a block of plaintext.
** Note that (as with IDEA encryption) an iteration of the
** Huffman test includes a compression AND a decompression.
** Also, the compression cycle includes building the
** Huffman tree.
*/
double
DoHuffman(void)
{
        char*           comparray = NULL;
        char*           decomparray = NULL;
        char*           plaintext = NULL;
        clock_t         total_time = 0;
        int             iterations = 0;
        static bool     is_adjusted = false;
        static int      loops = 90; /* 90 since we want it to be 100 for the first iteration and add 10 before the first iteration */

        /*
        ** Allocate memory for the plaintext and the compressed text.
        ** We'll be really pessimistic here, and allocate equal amounts
        ** for both (though we know...well, we PRESUME) the compressed
        ** stuff will take less than the plain stuff.
        ** Also note that we'll build a 3rd buffer to decompress
        ** into, and we preallocate space for the huffman tree.
        ** (We presume that the Huffman tree will grow no larger
        ** than 512 bytes.  This is actually a super-conservative
        ** estimate...but, who cares?)
        */
        plaintext = malloc(ARRAY_SIZE * sizeof(char));

        comparray = malloc(ARRAY_SIZE * sizeof(char));

        decomparray = malloc(ARRAY_SIZE * sizeof(char));

        hufftree = malloc(sizeof(huff_node) * 512);

        /*
        ** Build the plaintext buffer.  Since we want this to
        ** actually be able to compress, we'll use the
        ** wordcatalog to build the plaintext stuff.
        */
        /*
        ** Reset random number generator so things repeat.
        ** added by Uwe F. Mayer
        */
        randnum((int32_t)13);
        create_text_block(plaintext,ARRAY_SIZE-1,(unsigned short)500);
        plaintext[ARRAY_SIZE-1L]='\0';

        /*
        ** See if we need to perform self adjustment loop.
        */
        if (is_adjusted == false) {
                is_adjusted = true;
                /*
                ** Do self-adjustment.  This involves initializing the
                ** # of loops and increasing the loop count until we
                ** get a number of loops that we can use.
                */
                do {
                        loops += 10;
                } while ((DoHuffIteration(plaintext, comparray, decomparray, loops, hufftree) <= MINIMUM_TICKS) && (loops < LOOP_MAX));
        }

        do {
                total_time += DoHuffIteration(plaintext, comparray, decomparray, loops, hufftree);
                iterations += loops;
        } while (total_time < MINIMUM_SECONDS * CLOCKS_PER_SEC);

        free(plaintext);
        free(comparray);
        free(decomparray);
        free(hufftree);

        return (double)(iterations * CLOCKS_PER_SEC) / (double)total_time;
}

/*********************
** create_text_line **
**********************
** Create a random line of text, stored at *dt.  The line may be
** no more than nchars long.
*/
static void create_text_line(char *dt,
			long nchars)
{
long charssofar = 0;        /* # of characters so far */
long tomove;            /* # of characters to move */
char myword[40];        /* Local buffer for words */
char *wordptr;       /* Pointer to word from catalog */

/*
** Word catalog
*/
#define WORDCATSIZE 50

char * wordcatarray[WORDCATSIZE] = {
        "Hello", "He", "Him", "the", "this", "that", "though", "rough", "cough", "obviously", "But",
	"but", "bye", "begin", "beginning", "beginnings", "of", "our", "ourselves", "yourselves",
	"to", "together", "togetherness", "from", "either", "I", "A", "return", "However", "that",
	"example", "yet", "quickly", "all", "if", "were", "includes", "always", "never", "not",	"small",
	"returns", "set", "basic", "Entered", "with", "used", "shown", "you", "know"
};

do {
/*
** Grab a random word from the wordcatalog
*/
wordptr=wordcatarray[abs_randwc((int32_t)WORDCATSIZE)];
memmove(myword, wordptr, strlen(wordptr) + 1);

/*
** Append a blank.
*/
tomove=strlen(myword)+1;
myword[tomove-1]=' ';

/*
** See how long it is.  If its length+charssofar > nchars, we have
** to trim it.
*/
if((tomove+charssofar)>nchars)
	tomove=nchars-charssofar;
/*
** Attach the word to the current line.  Increment counter.
*/
memmove(dt, myword, tomove);
charssofar+=tomove;
dt+=tomove;

/*
** If we're done, bail out.  Otherwise, go get another word.
*/
} while(charssofar<nchars);

return;
}

/**********************
** create_text_block **
***********************
** Build a block of text randomly loaded with words.  The words
** come from the wordcatalog (which must be loaded before you
** call this).
** *tb points to the memory where the text is to be built.
** tblen is the # of bytes to put into the text block
** maxlinlen is the maximum length of any line (line end indicated
**  by a carriage return).
*/
static void create_text_block(char *tb,
			unsigned long tblen,
			unsigned short maxlinlen)
{
unsigned long bytessofar;       /* # of bytes so far */
unsigned long linelen;          /* Line length */

bytessofar=0L;
do {

/*
** Pick a random length for a line and fill the line.
** Make sure the line can fit (haven't exceeded tablen) and also
** make sure you leave room to append a carriage return.
*/
linelen=abs_randwc(maxlinlen-6)+6;
if((linelen+bytessofar)>tblen)
	linelen=tblen-bytessofar;

if(linelen>1)
{
	create_text_line(tb,linelen);
}
tb+=linelen-1;          /* Add the carriage return */
*tb++='\n';

bytessofar+=linelen;

} while(bytessofar<tblen);

}

/********************
** DoHuffIteration **
*********************
** Perform the huffman benchmark.  This routine
**  (a) Builds the huffman tree
**  (b) Compresses the text
**  (c) Decompresses the text and verifies correct decompression
*/
static clock_t
DoHuffIteration(char *plaintext, char *comparray, char *decomparray, unsigned long nloops, huff_node *hufftree)
{
        clock_t start, stop;
int i;                          /* Index */
long j;                         /* Bigger index */
int root;                       /* Pointer to huffman tree root */
float lowfreq1, lowfreq2;       /* Low frequency counters */
int lowidx1, lowidx2;           /* Indexes of low freq. elements */
long bitoffset;                 /* Bit offset into text */
long textoffset;                /* Char offset into text */
long maxbitoffset;              /* Holds limit of bit offset */
long bitstringlen;              /* Length of bitstring */
int c;                          /* Character from plaintext */
char bitstring[30];             /* Holds bitstring */

        start = clock();

while(nloops--)
{

/*
** Calculate the frequency of each byte value. Store the
** results in what will become the "leaves" of the
** Huffman tree.  Interior nodes will be built in those
** nodes greater than node #255.
*/
for(i=0;i<256;i++)
{
	hufftree[i].freq=(float)0.0;
	hufftree[i].c=(unsigned char)i;
}

for(j=0;j<ARRAY_SIZE;j++)
	hufftree[(int)plaintext[j]].freq+=(float)1.0;

for(i=0;i<256;i++)
	if(hufftree[i].freq != 0.0)
		hufftree[i].freq/=(float)ARRAY_SIZE;

/* Reset the second half of the tree. Otherwise the loop below that
** compares the frequencies up to index 512 makes no sense. Some
** systems automatically zero out memory upon allocation, others (like
** for example DEC Unix) do not. Depending on this the loop below gets
** different data and different run times. On our alpha the data that
** was arbitrarily assigned led to an underflow error at runtime. We
** use that zeroed-out bits are in fact 0 as a float.
** Uwe F. Mayer */
memset(&(hufftree[256]), 0, sizeof(huff_node) * 256);
/*
** Build the huffman tree.  First clear all the parent
** pointers and left/right pointers.  Also, discard all
** nodes that have a frequency of true 0.  */
for(i=0;i<512;i++)
{       if(hufftree[i].freq == 0.0)
		hufftree[i].parent=EXCLUDED;
	else {
		hufftree[i].right = -1;
		hufftree[i].left = -1;
		hufftree[i].parent = -1;
	}
}

/*
** Go through the tree. Finding nodes of really low
** frequency.
*/
root=255;                       /* Starting root node-1 */
while(1)
{
	lowfreq1=(float)2.0; lowfreq2=(float)2.0;
	lowidx1=-1; lowidx2=-1;
	/*
	** Find first lowest frequency.
	*/
	for(i=0;i<=root;i++)
		if(hufftree[i].parent<0)
			if(hufftree[i].freq<lowfreq1)
			{       lowfreq1=hufftree[i].freq;
				lowidx1=i;
			}

	/*
	** Did we find a lowest value?  If not, the
	** tree is done.
	*/
	if(lowidx1==-1) break;

	/*
	** Find next lowest frequency
	*/
	for(i=0;i<=root;i++)
		if((hufftree[i].parent<0) && (i!=lowidx1))
			if(hufftree[i].freq<lowfreq2)
			{       lowfreq2=hufftree[i].freq;
				lowidx2=i;
			}

	/*
	** If we could only find one item, then that
	** item is surely the root, and (as above) the
	** tree is done.
	*/
	if(lowidx2==-1) break;

	/*
	** Attach the two new nodes to the current root, and
	** advance the current root.
	*/
	root++;                 /* New root */
	hufftree[lowidx1].parent=root;
	hufftree[lowidx2].parent=root;
	hufftree[root].freq=lowfreq1+lowfreq2;
	hufftree[root].left=lowidx1;
	hufftree[root].right=lowidx2;
	hufftree[root].parent=-2;       /* Show root */
}

/*
** Huffman tree built...compress the plaintext
*/
bitoffset=0L;                           /* Initialize bit offset */
for(i=0;i<ARRAY_SIZE;i++)
{
	c=(int)plaintext[i];                 /* Fetch character */
	/*
	** Build a bit string for byte c
	*/
	bitstringlen=0;
	while(hufftree[c].parent!=-2)
	{       if(hufftree[hufftree[c].parent].left==c)
			bitstring[bitstringlen]='0';
		else
			bitstring[bitstringlen]='1';
		c=hufftree[c].parent;
		bitstringlen++;
	}

	/*
	** Step backwards through the bit string, setting
	** bits in the compressed array as you go.
	*/
	while(bitstringlen--)
	{       SetCompBit((uint8_t *)comparray,(uint32_t)bitoffset,bitstring[bitstringlen]);
		bitoffset++;
	}
}

/*
** Compression done.  Perform de-compression.
*/
maxbitoffset=bitoffset;
bitoffset=0;
textoffset=0;
do {
	i=root;
	while(hufftree[i].left!=-1)
	{       if(GetCompBit((uint8_t *)comparray,(uint32_t)bitoffset)==0)
			i=hufftree[i].left;
		else
			i=hufftree[i].right;
		bitoffset++;
	}
	decomparray[textoffset]=hufftree[i].c;

	textoffset++;
} while(bitoffset<maxbitoffset);

}       /* End the big while(nloops--) from above */

        stop = clock();

        return stop - start;
}

/***************
** SetCompBit **
****************
** Set a bit in the compression array.  The value of the
** bit is set according to char bitchar.
*/
static void SetCompBit(uint8_t *comparray,
		uint32_t bitoffset,
		char bitchar)
{
uint32_t byteoffset;
int bitnumb;

/*
** First calculate which element in the comparray to
** alter. and the bitnumber.
*/
byteoffset=bitoffset>>3;
bitnumb=bitoffset % 8;

/*
** Set or clear
*/
if(bitchar=='1')
	comparray[byteoffset]|=(1<<bitnumb);
else
	comparray[byteoffset]&=~(1<<bitnumb);

return;
}

/***************
** GetCompBit **
****************
** Return the bit value of a bit in the comparession array.
** Returns 0 if the bit is clear, nonzero otherwise.
*/
static int GetCompBit(uint8_t *comparray,
		uint32_t bitoffset)
{
uint32_t byteoffset;
int bitnumb;

/*
** Calculate byte offset and bit number.
*/
byteoffset=bitoffset>>3;
bitnumb=bitoffset % 8;

/*
** Fetch
*/
return((1<<bitnumb) & comparray[byteoffset] );
}