base64.c: fix compiler warnings
[s-mailx.git] / lzw.c
blob4a9f032c3d8c047729e00d6af162afbdb0502e7d
1 /*
2 * Heirloom mailx - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 */
6 /*-
7 * Copyright (c) 1985, 1986, 1992, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * Diomidis Spinellis and James A. Woods, derived from original
12 * work by Spencer Thomas and Joseph Orost.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the University of
25 * California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * SUCH DAMAGE.
43 /* from zopen.c 8.1 (Berkeley) 6/27/93 */
44 /* from FreeBSD: /repoman/r/ncvs/src/usr.bin/compress/zopen.c,v
45 * 1.5.6.1 2002/07/16 00:52:08 tjr Exp */
47 /*-
48 * lzw.c - File compression ala IEEE Computer, June 1984.
50 * Compress authors:
51 * Spencer W. Thomas (decvax!utah-cs!thomas)
52 * Jim McKie (decvax!mcvax!jim)
53 * Steve Davies (decvax!vax135!petsd!peora!srd)
54 * Ken Turkowski (decvax!decwrl!turtlevax!ken)
55 * James A. Woods (decvax!ihnp4!ames!jaw)
56 * Joe Orost (decvax!vax135!petsd!joe)
58 * Cleaned up and converted to library returning I/O streams by
59 * Diomidis Spinellis <dds@doc.ic.ac.uk>.
61 * Adopted for Heirloom mailx by Gunnar Ritter.
63 * Sccsid @(#)lzw.c 1.11 (gritter) 3/4/06
66 #include "config.h"
68 #include "rcv.h"
69 #include "extern.h"
70 #include <stdio.h>
72 #define BITS 16 /* Default bits. */
73 #define HSIZE 69001 /* 95% occupancy */
75 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
76 typedef long code_int;
77 typedef long count_int;
79 typedef unsigned char char_type;
80 static char_type magic_header[] =
81 {037, 0235}; /* 1F 9D */
83 #define BIT_MASK 0x1f /* Defines for third byte of header. */
84 #define BLOCK_MASK 0x80
87 * Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is
88 * a fourth header byte (for expansion).
90 #define INIT_BITS 9 /* Initial number of bits/code. */
92 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
94 struct s_zstate {
95 FILE *zs_fp; /* File stream for I/O */
96 char zs_mode; /* r or w */
97 enum {
98 ST_START, ST_MIDDLE, ST_EOF
99 } zs_state; /* State of computation */
100 unsigned zs_n_bits; /* Number of bits/code. */
101 unsigned zs_maxbits; /* User settable max # bits/code. */
102 code_int zs_maxcode; /* Maximum code, given n_bits. */
103 code_int zs_maxmaxcode; /* Should NEVER generate this code. */
104 count_int zs_htab[HSIZE];
105 unsigned short zs_codetab[HSIZE];
106 code_int zs_hsize; /* For dynamic table sizing. */
107 code_int zs_free_ent; /* First unused entry. */
109 * Block compression parameters -- after all codes are used up,
110 * and compression rate changes, start over.
112 int zs_block_compress;
113 int zs_clear_flg;
114 long zs_ratio;
115 count_int zs_checkpoint;
116 unsigned zs_offset;
117 long zs_in_count; /* Length of input. */
118 long zs_bytes_out; /* Length of compressed output. */
119 long zs_out_count; /* # of codes output (for debugging). */
120 char_type zs_buf[BITS+1];
121 union {
122 struct {
123 long zs_fcode;
124 code_int zs_ent;
125 code_int zs_hsize_reg;
126 int zs_hshift;
127 } w; /* Write paramenters */
128 struct {
129 char_type *zs_stackp;
130 int zs_finchar;
131 code_int zs_code, zs_oldcode, zs_incode;
132 int zs_roffset, zs_size;
133 char_type zs_gbuf[BITS+1];
134 } r; /* Read parameters */
135 } u;
138 /* Definitions to retain old variable names */
139 #define fp zs->zs_fp
140 #define zmode zs->zs_mode
141 #define state zs->zs_state
142 #define n_bits zs->zs_n_bits
143 #define maxbits zs->zs_maxbits
144 #define maxcode zs->zs_maxcode
145 #define maxmaxcode zs->zs_maxmaxcode
146 #define htab zs->zs_htab
147 #define codetab zs->zs_codetab
148 #define hsize zs->zs_hsize
149 #define free_ent zs->zs_free_ent
150 #define block_compress zs->zs_block_compress
151 #define clear_flg zs->zs_clear_flg
152 #define ratio zs->zs_ratio
153 #define checkpoint zs->zs_checkpoint
154 #define offset zs->zs_offset
155 #define in_count zs->zs_in_count
156 #define bytes_out zs->zs_bytes_out
157 #define out_count zs->zs_out_count
158 #define buf zs->zs_buf
159 #define fcode zs->u.w.zs_fcode
160 #define hsize_reg zs->u.w.zs_hsize_reg
161 #define ent zs->u.w.zs_ent
162 #define hshift zs->u.w.zs_hshift
163 #define stackp zs->u.r.zs_stackp
164 #define finchar zs->u.r.zs_finchar
165 #define code zs->u.r.zs_code
166 #define oldcode zs->u.r.zs_oldcode
167 #define incode zs->u.r.zs_incode
168 #define roffset zs->u.r.zs_roffset
169 #define size zs->u.r.zs_size
170 #define gbuf zs->u.r.zs_gbuf
173 * To save much memory, we overlay the table used by compress() with those
174 * used by decompress(). The tab_prefix table is the same size and type as
175 * the codetab. The tab_suffix table needs 2**BITS characters. We get this
176 * from the beginning of htab. The output stack uses the rest of htab, and
177 * contains characters. There is plenty of room for any possible stack
178 * (stack used to be 8000 characters).
181 #define htabof(i) htab[i]
182 #define codetabof(i) codetab[i]
184 #define tab_prefixof(i) codetabof(i)
185 #define tab_suffixof(i) ((char_type *)(htab))[i]
186 #define de_stack ((char_type *)&tab_suffixof(1 << BITS))
188 #define CHECK_GAP 10000 /* Ratio check interval. */
191 * the next two codes should not be changed lightly, as they must not
192 * lie within the contiguous general code space.
194 #define FIRST 257 /* First free entry. */
195 #define CLEAR 256 /* Table clear output code. */
197 static int output(struct s_zstate *zs, code_int ocode);
198 static code_int getcode(struct s_zstate *zs);
199 static int cl_block(struct s_zstate *zs);
200 static void cl_hash(struct s_zstate *zs, count_int cl_hsize);
203 * Algorithm from "A Technique for High Performance Data Compression",
204 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
206 * Algorithm:
207 * Modified Lempel-Ziv method (LZW). Basically finds common
208 * substrings and replaces them with a variable size code. This is
209 * deterministic, and can be done on the fly. Thus, the decompression
210 * procedure needs no input table, but tracks the way the table was built.
214 * compress write
216 * Algorithm: use open addressing double hashing (no chaining) on the
217 * prefix code / next character combination. We do a variant of Knuth's
218 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
219 * secondary probe. Here, the modular division first probe is gives way
220 * to a faster exclusive-or manipulation. Also do block compression with
221 * an adaptive reset, whereby the code table is cleared when the compression
222 * ratio decreases, but after the table fills. The variable-length output
223 * codes are re-sized at this point, and a special CLEAR code is generated
224 * for the decompressor. Late addition: construct the table according to
225 * file size for noticeable speed improvement on small files. Please direct
226 * questions about this implementation to ames!jaw.
228 int
229 zwrite(void *cookie, const char *wbp, int num)
231 code_int i;
232 int c, disp;
233 struct s_zstate *zs;
234 const unsigned char *bp;
235 unsigned char tmp;
236 int count;
238 if (num == 0)
239 return (0);
241 zs = cookie;
242 zmode = 'w';
243 count = num;
244 bp = (const unsigned char *)wbp;
245 if (state == ST_MIDDLE)
246 goto middle;
247 state = ST_MIDDLE;
249 maxmaxcode = 1L << maxbits;
250 if (fwrite(magic_header,
251 sizeof(char), sizeof(magic_header), fp) != sizeof(magic_header))
252 return (-1);
253 tmp = (unsigned char)((maxbits) | block_compress);
254 if (fwrite(&tmp, sizeof(char), sizeof(tmp), fp) != sizeof(tmp))
255 return (-1);
257 offset = 0;
258 bytes_out = 3; /* Includes 3-byte header mojo. */
259 out_count = 0;
260 clear_flg = 0;
261 ratio = 0;
262 in_count = 1;
263 checkpoint = CHECK_GAP;
264 maxcode = MAXCODE(n_bits = INIT_BITS);
265 free_ent = ((block_compress) ? FIRST : 256);
267 ent = *bp++;
268 --count;
270 hshift = 0;
271 for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L)
272 hshift++;
273 hshift = 8 - hshift; /* Set hash code range bound. */
275 hsize_reg = hsize;
276 cl_hash(zs, (count_int)hsize_reg); /* Clear hash table. */
278 middle: for (i = 0; count--;) {
279 c = *bp++;
280 in_count++;
281 fcode = (long)(((long)c << maxbits) + ent);
282 i = ((c << hshift) ^ ent); /* Xor hashing. */
284 if (htabof(i) == fcode) {
285 ent = codetabof(i);
286 continue;
287 } else if ((long)htabof(i) < 0) /* Empty slot. */
288 goto nomatch;
289 disp = hsize_reg - i; /* Secondary hash (after G. Knott). */
290 if (i == 0)
291 disp = 1;
292 probe: if ((i -= disp) < 0)
293 i += hsize_reg;
295 if (htabof(i) == fcode) {
296 ent = codetabof(i);
297 continue;
299 if ((long)htabof(i) >= 0)
300 goto probe;
301 nomatch: if (output(zs, (code_int) ent) == -1)
302 return (-1);
303 out_count++;
304 ent = c;
305 if (free_ent < maxmaxcode) {
306 codetabof(i) = free_ent++; /* code -> hashtable */
307 htabof(i) = fcode;
308 } else if ((count_int)in_count >=
309 checkpoint && block_compress) {
310 if (cl_block(zs) == -1)
311 return (-1);
314 return (num);
317 int
318 zfree(void *cookie)
320 struct s_zstate *zs;
322 zs = cookie;
323 if (zmode == 'w') { /* Put out the final code. */
324 if (output(zs, (code_int) ent) == -1) {
325 free(zs);
326 return (-1);
328 out_count++;
329 if (output(zs, (code_int) - 1) == -1) {
330 free(zs);
331 return (-1);
334 free(zs);
335 return (0);
339 * Output the given code.
340 * Inputs:
341 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
342 * that n_bits =< (long)wordsize - 1.
343 * Outputs:
344 * Outputs code to the file.
345 * Assumptions:
346 * Chars are 8 bits long.
347 * Algorithm:
348 * Maintain a BITS character long buffer (so that 8 codes will
349 * fit in it exactly). Use the VAX insv instruction to insert each
350 * code in turn. When the buffer fills up empty it and start over.
353 static char_type lmask[9] =
354 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
355 static char_type rmask[9] =
356 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
358 static int
359 output(struct s_zstate *zs, code_int ocode)
361 int r_off;
362 unsigned bits;
363 char_type *bp;
365 r_off = offset;
366 bits = n_bits;
367 bp = buf;
368 if (ocode >= 0) {
369 /* Get to the first byte. */
370 bp += (r_off >> 3);
371 r_off &= 7;
373 * Since ocode is always >= 8 bits, only need to mask the first
374 * hunk on the left.
376 *bp = (*bp & rmask[r_off]) | ((ocode << r_off) & lmask[r_off]);
377 bp++;
378 bits -= (8 - r_off);
379 ocode >>= 8 - r_off;
380 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
381 if (bits >= 8) {
382 *bp++ = ocode;
383 ocode >>= 8;
384 bits -= 8;
386 /* Last bits. */
387 if (bits)
388 *bp = ocode;
389 offset += n_bits;
390 if (offset == (n_bits << 3)) {
391 bp = buf;
392 bits = n_bits;
393 bytes_out += bits;
394 if (fwrite(bp, sizeof(char), bits, fp) != bits)
395 return (-1);
396 bp += bits;
397 bits = 0;
398 offset = 0;
401 * If the next entry is going to be too big for the ocode size,
402 * then increase it, if possible.
404 if (free_ent > maxcode || (clear_flg > 0)) {
406 * Write the whole buffer, because the input side won't
407 * discover the size increase until after it has read it.
409 if (offset > 0) {
410 if (fwrite(buf, 1, n_bits, fp) != n_bits)
411 return (-1);
412 bytes_out += n_bits;
414 offset = 0;
416 if (clear_flg) {
417 maxcode = MAXCODE(n_bits = INIT_BITS);
418 clear_flg = 0;
419 } else {
420 n_bits++;
421 if (n_bits == maxbits)
422 maxcode = maxmaxcode;
423 else
424 maxcode = MAXCODE(n_bits);
427 } else {
428 /* At EOF, write the rest of the buffer. */
429 if (offset > 0) {
430 offset = (offset + 7) / 8;
431 if (fwrite(buf, 1, offset, fp) != offset)
432 return (-1);
433 bytes_out += offset;
435 offset = 0;
437 return (0);
441 * Decompress read. This routine adapts to the codes in the file building
442 * the "string" table on-the-fly; requiring no table to be stored in the
443 * compressed file. The tables used herein are shared with those of the
444 * compress() routine. See the definitions above.
446 int
447 zread(void *cookie, char *rbp, int num)
449 unsigned count;
450 struct s_zstate *zs;
451 unsigned char *bp, header[3];
453 if (num == 0)
454 return (0);
456 zs = cookie;
457 count = num;
458 bp = (unsigned char *)rbp;
459 switch (state) {
460 case ST_START:
461 state = ST_MIDDLE;
462 break;
463 case ST_MIDDLE:
464 goto middle;
465 case ST_EOF:
466 goto eof;
469 /* Check the magic number */
470 if (fread(header,
471 sizeof(char), sizeof(header), fp) != sizeof(header) ||
472 memcmp(header, magic_header, sizeof(magic_header)) != 0) {
473 return (-1);
475 maxbits = header[2]; /* Set -b from file. */
476 block_compress = maxbits & BLOCK_MASK;
477 maxbits &= BIT_MASK;
478 maxmaxcode = 1L << maxbits;
479 if (maxbits > BITS) {
480 return (-1);
482 /* As above, initialize the first 256 entries in the table. */
483 maxcode = MAXCODE(n_bits = INIT_BITS);
484 for (code = 255; code >= 0; code--) {
485 tab_prefixof(code) = 0;
486 tab_suffixof(code) = (char_type) code;
488 free_ent = block_compress ? FIRST : 256;
490 finchar = oldcode = getcode(zs);
491 if (oldcode == -1) /* EOF already? */
492 return (0); /* Get out of here */
494 /* First code must be 8 bits = char. */
495 *bp++ = (unsigned char)finchar;
496 count--;
497 stackp = de_stack;
499 while ((code = getcode(zs)) > -1) {
501 if ((code == CLEAR) && block_compress) {
502 for (code = 255; code >= 0; code--)
503 tab_prefixof(code) = 0;
504 clear_flg = 1;
505 free_ent = FIRST - 1;
506 if ((code = getcode(zs)) == -1) /* O, untimely death! */
507 break;
509 incode = code;
511 /* Special case for KwKwK string. */
512 if (code >= free_ent) {
513 *stackp++ = finchar;
514 code = oldcode;
517 /* Generate output characters in reverse order. */
518 while (code >= 256) {
519 *stackp++ = tab_suffixof(code);
520 code = tab_prefixof(code);
522 *stackp++ = finchar = tab_suffixof(code);
524 /* And put them out in forward order. */
525 middle: do {
526 if (count-- == 0)
527 return (num);
528 *bp++ = *--stackp;
529 } while (stackp > de_stack);
531 /* Generate the new entry. */
532 if ((code = free_ent) < maxmaxcode) {
533 tab_prefixof(code) = (unsigned short) oldcode;
534 tab_suffixof(code) = finchar;
535 free_ent = code + 1;
538 /* Remember previous code. */
539 oldcode = incode;
541 state = ST_EOF;
542 eof: return (num - count);
546 * Read one code from the standard input. If EOF, return -1.
547 * Inputs:
548 * stdin
549 * Outputs:
550 * code or -1 is returned.
552 static code_int
553 getcode(struct s_zstate *zs)
555 code_int gcode;
556 int r_off, bits;
557 char_type *bp;
559 bp = gbuf;
560 if (clear_flg > 0 || roffset >= size || free_ent > maxcode) {
562 * If the next entry will be too big for the current gcode
563 * size, then we must increase the size. This implies reading
564 * a new buffer full, too.
566 if (free_ent > maxcode) {
567 n_bits++;
568 if (n_bits == maxbits) /* Won't get any bigger now. */
569 maxcode = maxmaxcode;
570 else
571 maxcode = MAXCODE(n_bits);
573 if (clear_flg > 0) {
574 maxcode = MAXCODE(n_bits = INIT_BITS);
575 clear_flg = 0;
577 size = fread(gbuf, 1, n_bits, fp);
578 if (size <= 0) /* End of file. */
579 return (-1);
580 roffset = 0;
581 /* Round size down to integral number of codes. */
582 size = (size << 3) - (n_bits - 1);
584 r_off = roffset;
585 bits = n_bits;
587 /* Get to the first byte. */
588 bp += (r_off >> 3);
589 r_off &= 7;
591 /* Get first part (low order bits). */
592 gcode = (*bp++ >> r_off);
593 bits -= (8 - r_off);
594 r_off = 8 - r_off; /* Now, roffset into gcode word. */
596 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
597 if (bits >= 8) {
598 gcode |= *bp++ << r_off;
599 r_off += 8;
600 bits -= 8;
603 /* High order bits. */
604 gcode |= (*bp & rmask[bits]) << r_off;
605 roffset += n_bits;
607 return (gcode);
610 static int
611 cl_block ( /* Table clear for block compress. */
612 struct s_zstate *zs
615 long rat;
617 checkpoint = in_count + CHECK_GAP;
619 if (in_count > 0x007fffff) { /* Shift will overflow. */
620 rat = bytes_out >> 8;
621 if (rat == 0) /* Don't divide by zero. */
622 rat = 0x7fffffff;
623 else
624 rat = in_count / rat;
625 } else
626 rat = (in_count << 8) / bytes_out; /* 8 fractional bits. */
627 if (rat > ratio)
628 ratio = rat;
629 else {
630 ratio = 0;
631 cl_hash(zs, (count_int) hsize);
632 free_ent = FIRST;
633 clear_flg = 1;
634 if (output(zs, (code_int) CLEAR) == -1)
635 return (-1);
637 return (0);
640 static void
641 cl_hash ( /* Reset code table. */
642 struct s_zstate *zs,
643 count_int cl_hsize
646 count_int *htab_p;
647 long i, m1;
649 m1 = -1;
650 htab_p = htab + cl_hsize;
651 i = cl_hsize - 16;
652 do { /* Might use Sys V memset(3) here. */
653 *(htab_p - 16) = m1;
654 *(htab_p - 15) = m1;
655 *(htab_p - 14) = m1;
656 *(htab_p - 13) = m1;
657 *(htab_p - 12) = m1;
658 *(htab_p - 11) = m1;
659 *(htab_p - 10) = m1;
660 *(htab_p - 9) = m1;
661 *(htab_p - 8) = m1;
662 *(htab_p - 7) = m1;
663 *(htab_p - 6) = m1;
664 *(htab_p - 5) = m1;
665 *(htab_p - 4) = m1;
666 *(htab_p - 3) = m1;
667 *(htab_p - 2) = m1;
668 *(htab_p - 1) = m1;
669 htab_p -= 16;
670 } while ((i -= 16) >= 0);
671 for (i += 16; i > 0; i--)
672 *--htab_p = m1;
675 #undef fp
676 void *
677 zalloc(FILE *fp)
679 #define bits BITS
680 struct s_zstate *zs;
682 zs = scalloc(1, sizeof *zs);
683 maxbits = bits ? bits : BITS; /* User settable max # bits/code. */
684 maxmaxcode = 1L << maxbits; /* Should NEVER generate this code. */
685 hsize = HSIZE; /* For dynamic table sizing. */
686 free_ent = 0; /* First unused entry. */
687 block_compress = BLOCK_MASK;
688 clear_flg = 0;
689 ratio = 0;
690 checkpoint = CHECK_GAP;
691 in_count = 1; /* Length of input. */
692 out_count = 0; /* # of codes output (for debugging). */
693 state = ST_START;
694 roffset = 0;
695 size = 0;
696 zs->zs_fp = fp;
697 return zs;