Tweak *rfc822-show-all* manual text
[s-mailx.git] / lzw.c
blob4fa880f7dd62a6110a7c6a443f3f478d20a66cde
1 /*
2 * S-nail - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 Steffen "Daode" Nurpmeso.
6 */
7 /*-
8 * Copyright (c) 1985, 1986, 1992, 1993
9 * The Regents of the University of California. All rights reserved.
11 * This code is derived from software contributed to Berkeley by
12 * Diomidis Spinellis and James A. Woods, derived from original
13 * work by Spencer Thomas and Joseph Orost.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
40 /* from zopen.c 8.1 (Berkeley) 6/27/93 */
41 /* from FreeBSD: /repoman/r/ncvs/src/usr.bin/compress/zopen.c,v
42 * 1.5.6.1 2002/07/16 00:52:08 tjr Exp */
43 /* from FreeBSD: git://git.freebsd.org/freebsd,
44 * master:usr.bin/compress/zopen.c,
45 * (Fix handling of corrupt compress(1)ed data. [11:04], 2011-09-28),
46 * 2902cb5e28a1e38bce859ef1ae14e9d22fe50214. */
48 /*-
49 * lzw.c - File compression ala IEEE Computer, June 1984.
51 * Compress authors:
52 * Spencer W. Thomas (decvax!utah-cs!thomas)
53 * Jim McKie (decvax!mcvax!jim)
54 * Steve Davies (decvax!vax135!petsd!peora!srd)
55 * Ken Turkowski (decvax!decwrl!turtlevax!ken)
56 * James A. Woods (decvax!ihnp4!ames!jaw)
57 * Joe Orost (decvax!vax135!petsd!joe)
59 * Cleaned up and converted to library returning I/O streams by
60 * Diomidis Spinellis <dds@doc.ic.ac.uk>.
62 * Adopted for Heirloom mailx by Gunnar Ritter.
65 #include "config.h"
67 #if ! defined USE_IMAP && ! defined USE_JUNK
68 typedef int avoid_empty_file_compiler_warning;
69 #else
71 #include "rcv.h"
72 #include "extern.h"
74 #include <stdio.h>
76 /* Minimize differences to FreeBSDs usr.bin/compress/zopen.c */
77 #undef u_int
78 #define u_int unsigned int
79 #undef u_short
80 #define u_short unsigned short
81 #undef u_char
82 #define u_char unsigned char
84 #define BITS 16 /* Default bits. */
85 #define HSIZE 69001 /* 95% occupancy */
87 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
88 typedef long code_int;
89 typedef long count_int;
91 typedef u_char char_type;
92 static char_type magic_header[] =
93 {'\037', '\235'}; /* 1F 9D */
95 #define BIT_MASK 0x1f /* Defines for third byte of header. */
96 #define BLOCK_MASK 0x80
99 * Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is
100 * a fourth header byte (for expansion).
102 #define INIT_BITS 9 /* Initial number of bits/code. */
104 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
106 struct s_zstate {
107 FILE *zs_fp; /* File stream for I/O */
108 char zs_mode; /* r or w */
109 enum {
110 S_START, S_MIDDLE, S_EOF
111 } zs_state; /* State of computation */
112 u_int zs_n_bits; /* Number of bits/code. */
113 u_int zs_maxbits; /* User settable max # bits/code. */
114 code_int zs_maxcode; /* Maximum code, given n_bits. */
115 code_int zs_maxmaxcode; /* Should NEVER generate this code. */
116 count_int zs_htab [HSIZE];
117 u_short zs_codetab [HSIZE];
118 code_int zs_hsize; /* For dynamic table sizing. */
119 code_int zs_free_ent; /* First unused entry. */
121 * Block compression parameters -- after all codes are used up,
122 * and compression rate changes, start over.
124 int zs_block_compress;
125 int zs_clear_flg;
126 long zs_ratio;
127 count_int zs_checkpoint;
128 u_int zs_offset;
129 long zs_in_count; /* Length of input. */
130 long zs_bytes_out; /* Length of compressed output. */
131 long zs_out_count; /* # of codes output (for debugging). */
132 char_type zs_buf[BITS];
133 union {
134 struct {
135 long zs_fcode;
136 code_int zs_ent;
137 code_int zs_hsize_reg;
138 int zs_hshift;
139 } w; /* Write parameters */
140 struct {
141 char_type *zs_stackp;
142 int zs_finchar;
143 code_int zs_code, zs_oldcode, zs_incode;
144 int zs_roffset, zs_size;
145 char_type zs_gbuf[BITS];
146 } r; /* Read parameters */
147 } u;
150 /* Definitions to retain old variable names */
151 #define fp zs->zs_fp
152 #define zmode zs->zs_mode
153 #define state zs->zs_state
154 #define n_bits zs->zs_n_bits
155 #define maxbits zs->zs_maxbits
156 #define maxcode zs->zs_maxcode
157 #define maxmaxcode zs->zs_maxmaxcode
158 #define htab zs->zs_htab
159 #define codetab zs->zs_codetab
160 #define hsize zs->zs_hsize
161 #define free_ent zs->zs_free_ent
162 #define block_compress zs->zs_block_compress
163 #define clear_flg zs->zs_clear_flg
164 #define ratio zs->zs_ratio
165 #define checkpoint zs->zs_checkpoint
166 #define offset zs->zs_offset
167 #define in_count zs->zs_in_count
168 #define bytes_out zs->zs_bytes_out
169 #define out_count zs->zs_out_count
170 #define buf zs->zs_buf
171 #define fcode zs->u.w.zs_fcode
172 #define hsize_reg zs->u.w.zs_hsize_reg
173 #define ent zs->u.w.zs_ent
174 #define hshift zs->u.w.zs_hshift
175 #define stackp zs->u.r.zs_stackp
176 #define finchar zs->u.r.zs_finchar
177 #define code zs->u.r.zs_code
178 #define oldcode zs->u.r.zs_oldcode
179 #define incode zs->u.r.zs_incode
180 #define roffset zs->u.r.zs_roffset
181 #define size zs->u.r.zs_size
182 #define gbuf zs->u.r.zs_gbuf
185 * To save much memory, we overlay the table used by compress() with those
186 * used by decompress(). The tab_prefix table is the same size and type as
187 * the codetab. The tab_suffix table needs 2**BITS characters. We get this
188 * from the beginning of htab. The output stack uses the rest of htab, and
189 * contains characters. There is plenty of room for any possible stack
190 * (stack used to be 8000 characters).
193 #define htabof(i) htab[i]
194 #define codetabof(i) codetab[i]
196 #define tab_prefixof(i) codetabof(i)
197 #define tab_suffixof(i) ((char_type *)(htab))[i]
198 #define de_stack ((char_type *)&tab_suffixof(1 << BITS))
200 #define CHECK_GAP 10000 /* Ratio check interval. */
203 * the next two codes should not be changed lightly, as they must not
204 * lie within the contiguous general code space.
206 #define FIRST 257 /* First free entry. */
207 #define CLEAR 256 /* Table clear output code. */
209 static int cl_block(struct s_zstate *);
210 static void cl_hash(struct s_zstate *, count_int);
211 static code_int getcode(struct s_zstate *);
212 static int output(struct s_zstate *, code_int);
215 * Algorithm from "A Technique for High Performance Data Compression",
216 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
218 * Algorithm:
219 * Modified Lempel-Ziv method (LZW). Basically finds common
220 * substrings and replaces them with a variable size code. This is
221 * deterministic, and can be done on the fly. Thus, the decompression
222 * procedure needs no input table, but tracks the way the table was built.
226 * compress write
228 * Algorithm: use open addressing double hashing (no chaining) on the
229 * prefix code / next character combination. We do a variant of Knuth's
230 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
231 * secondary probe. Here, the modular division first probe is gives way
232 * to a faster exclusive-or manipulation. Also do block compression with
233 * an adaptive reset, whereby the code table is cleared when the compression
234 * ratio decreases, but after the table fills. The variable-length output
235 * codes are re-sized at this point, and a special CLEAR code is generated
236 * for the decompressor. Late addition: construct the table according to
237 * file size for noticeable speed improvement on small files. Please direct
238 * questions about this implementation to ames!jaw.
241 zwrite(void *cookie, const char *wbp, int num)
243 code_int i;
244 int c, disp;
245 struct s_zstate *zs;
246 const u_char *bp;
247 u_char tmp;
248 int count;
250 if (num == 0)
251 return (0);
253 zs = cookie;
254 zmode = 'w';
255 count = num;
256 bp = (const u_char *)wbp;
257 if (state == S_MIDDLE)
258 goto middle;
259 state = S_MIDDLE;
261 maxmaxcode = 1L << maxbits;
262 if (fwrite(magic_header,
263 sizeof(char), sizeof(magic_header), fp) != sizeof(magic_header))
264 return (-1);
265 tmp = (u_char)((maxbits) | block_compress);
266 if (fwrite(&tmp, sizeof(char), sizeof(tmp), fp) != sizeof(tmp))
267 return (-1);
269 offset = 0;
270 bytes_out = 3; /* Includes 3-byte header mojo. */
271 out_count = 0;
272 clear_flg = 0;
273 ratio = 0;
274 in_count = 1;
275 checkpoint = CHECK_GAP;
276 maxcode = MAXCODE(n_bits = INIT_BITS);
277 free_ent = ((block_compress) ? FIRST : 256);
279 ent = *bp++;
280 --count;
282 hshift = 0;
283 for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L)
284 hshift++;
285 hshift = 8 - hshift; /* Set hash code range bound. */
287 hsize_reg = hsize;
288 cl_hash(zs, (count_int)hsize_reg); /* Clear hash table. */
290 middle: for (i = 0; count--;) {
291 c = *bp++;
292 in_count++;
293 fcode = (long)(((long)c << maxbits) + ent);
294 i = ((c << hshift) ^ ent); /* Xor hashing. */
296 if (htabof(i) == fcode) {
297 ent = codetabof(i);
298 continue;
299 } else if ((long)htabof(i) < 0) /* Empty slot. */
300 goto nomatch;
301 disp = hsize_reg - i; /* Secondary hash (after G. Knott). */
302 if (i == 0)
303 disp = 1;
304 probe: if ((i -= disp) < 0)
305 i += hsize_reg;
307 if (htabof(i) == fcode) {
308 ent = codetabof(i);
309 continue;
311 if ((long)htabof(i) >= 0)
312 goto probe;
313 nomatch: if (output(zs, (code_int) ent) == -1)
314 return (-1);
315 out_count++;
316 ent = c;
317 if (free_ent < maxmaxcode) {
318 codetabof(i) = free_ent++; /* code -> hashtable */
319 htabof(i) = fcode;
320 } else if ((count_int)in_count >=
321 checkpoint && block_compress) {
322 if (cl_block(zs) == -1)
323 return (-1);
326 return (num);
330 zfree(void *cookie)
332 struct s_zstate *zs;
334 zs = cookie;
335 if (zmode == 'w') { /* Put out the final code. */
336 if (output(zs, (code_int) ent) == -1) {
337 free(zs);
338 return (-1);
340 out_count++;
341 if (output(zs, (code_int) - 1) == -1) {
342 free(zs);
343 return (-1);
346 free(zs);
347 return (0);
351 * Output the given code.
352 * Inputs:
353 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
354 * that n_bits =< (long)wordsize - 1.
355 * Outputs:
356 * Outputs code to the file.
357 * Assumptions:
358 * Chars are 8 bits long.
359 * Algorithm:
360 * Maintain a BITS character long buffer (so that 8 codes will
361 * fit in it exactly). Use the VAX insv instruction to insert each
362 * code in turn. When the buffer fills up empty it and start over.
365 static char_type lmask[9] =
366 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
367 static char_type rmask[9] =
368 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
370 static int
371 output(struct s_zstate *zs, code_int ocode)
373 int r_off;
374 u_int bits;
375 char_type *bp;
377 r_off = offset;
378 bits = n_bits;
379 bp = buf;
380 if (ocode >= 0) {
381 /* Get to the first byte. */
382 bp += (r_off >> 3);
383 r_off &= 7;
385 * Since ocode is always >= 8 bits, only need to mask the first
386 * hunk on the left.
388 *bp = (*bp & rmask[r_off]) | ((ocode << r_off) & lmask[r_off]);
389 bp++;
390 bits -= (8 - r_off);
391 ocode >>= 8 - r_off;
392 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
393 if (bits >= 8) {
394 *bp++ = ocode;
395 ocode >>= 8;
396 bits -= 8;
398 /* Last bits. */
399 if (bits)
400 *bp = ocode;
401 offset += n_bits;
402 if (offset == (n_bits << 3)) {
403 bp = buf;
404 bits = n_bits;
405 bytes_out += bits;
406 if (fwrite(bp, sizeof(char), bits, fp) != bits)
407 return (-1);
408 bp += bits;
409 bits = 0;
410 offset = 0;
413 * If the next entry is going to be too big for the ocode size,
414 * then increase it, if possible.
416 if (free_ent > maxcode || (clear_flg > 0)) {
418 * Write the whole buffer, because the input side won't
419 * discover the size increase until after it has read it.
421 if (offset > 0) {
422 if (fwrite(buf, 1, n_bits, fp) != n_bits)
423 return (-1);
424 bytes_out += n_bits;
426 offset = 0;
428 if (clear_flg) {
429 maxcode = MAXCODE(n_bits = INIT_BITS);
430 clear_flg = 0;
431 } else {
432 n_bits++;
433 if (n_bits == maxbits)
434 maxcode = maxmaxcode;
435 else
436 maxcode = MAXCODE(n_bits);
439 } else {
440 /* At EOF, write the rest of the buffer. */
441 if (offset > 0) {
442 offset = (offset + 7) / 8;
443 if (fwrite(buf, 1, offset, fp) != offset)
444 return (-1);
445 bytes_out += offset;
447 offset = 0;
449 return (0);
453 * Decompress read. This routine adapts to the codes in the file building
454 * the "string" table on-the-fly; requiring no table to be stored in the
455 * compressed file. The tables used herein are shared with those of the
456 * compress() routine. See the definitions above.
459 zread(void *cookie, char *rbp, int num)
461 u_int count;
462 struct s_zstate *zs;
463 u_char *bp, header[3];
465 if (num == 0)
466 return (0);
468 zs = cookie;
469 count = num;
470 bp = (u_char *)rbp;
471 switch (state) {
472 case S_START:
473 state = S_MIDDLE;
474 break;
475 case S_MIDDLE:
476 goto middle;
477 case S_EOF:
478 goto eof;
481 /* Check the magic number */
482 if (fread(header,
483 sizeof(char), sizeof(header), fp) != sizeof(header) ||
484 memcmp(header, magic_header, sizeof(magic_header)) != 0) {
485 return (-1);
487 maxbits = header[2]; /* Set -b from file. */
488 block_compress = maxbits & BLOCK_MASK;
489 maxbits &= BIT_MASK;
490 maxmaxcode = 1L << maxbits;
491 if (maxbits > BITS || maxbits < 12) {
492 return (-1);
494 /* As above, initialize the first 256 entries in the table. */
495 maxcode = MAXCODE(n_bits = INIT_BITS);
496 for (code = 255; code >= 0; code--) {
497 tab_prefixof(code) = 0;
498 tab_suffixof(code) = (char_type) code;
500 free_ent = block_compress ? FIRST : 256;
502 finchar = oldcode = getcode(zs);
503 if (oldcode == -1) /* EOF already? */
504 return (0); /* Get out of here */
506 /* First code must be 8 bits = char. */
507 *bp++ = (u_char)finchar;
508 count--;
509 stackp = de_stack;
511 while ((code = getcode(zs)) > -1) {
513 if ((code == CLEAR) && block_compress) {
514 for (code = 255; code >= 0; code--)
515 tab_prefixof(code) = 0;
516 clear_flg = 1;
517 free_ent = FIRST;
518 oldcode = -1;
519 continue;
521 incode = code;
523 /* Special case for kWkWk string. */
524 if (code >= free_ent) {
525 if (code > free_ent || oldcode == -1) {
526 return (-1);
528 *stackp++ = finchar;
529 code = oldcode;
532 * The above condition ensures that code < free_ent.
533 * The construction of tab_prefixof in turn guarantees that
534 * each iteration decreases code and therefore stack usage is
535 * bound by 1 << BITS - 256.
538 /* Generate output characters in reverse order. */
539 while (code >= 256) {
540 *stackp++ = tab_suffixof(code);
541 code = tab_prefixof(code);
543 *stackp++ = finchar = tab_suffixof(code);
545 /* And put them out in forward order. */
546 middle: do {
547 if (count-- == 0)
548 return (num);
549 *bp++ = *--stackp;
550 } while (stackp > de_stack);
552 /* Generate the new entry. */
553 if ((code = free_ent) < maxmaxcode && oldcode != -1) {
554 tab_prefixof(code) = (u_short) oldcode;
555 tab_suffixof(code) = finchar;
556 free_ent = code + 1;
559 /* Remember previous code. */
560 oldcode = incode;
562 state = S_EOF;
563 eof: return (num - count);
567 * Read one code from the standard input. If EOF, return -1.
568 * Inputs:
569 * stdin
570 * Outputs:
571 * code or -1 is returned.
573 static code_int
574 getcode(struct s_zstate *zs)
576 code_int gcode;
577 int r_off, bits;
578 char_type *bp;
580 bp = gbuf;
581 if (clear_flg > 0 || roffset >= size || free_ent > maxcode) {
583 * If the next entry will be too big for the current gcode
584 * size, then we must increase the size. This implies reading
585 * a new buffer full, too.
587 if (free_ent > maxcode) {
588 n_bits++;
589 if (n_bits == maxbits) /* Won't get any bigger now. */
590 maxcode = maxmaxcode;
591 else
592 maxcode = MAXCODE(n_bits);
594 if (clear_flg > 0) {
595 maxcode = MAXCODE(n_bits = INIT_BITS);
596 clear_flg = 0;
598 size = fread(gbuf, 1, n_bits, fp);
599 if (size <= 0) /* End of file. */
600 return (-1);
601 roffset = 0;
602 /* Round size down to integral number of codes. */
603 size = (size << 3) - (n_bits - 1);
605 r_off = roffset;
606 bits = n_bits;
608 /* Get to the first byte. */
609 bp += (r_off >> 3);
610 r_off &= 7;
612 /* Get first part (low order bits). */
613 gcode = (*bp++ >> r_off);
614 bits -= (8 - r_off);
615 r_off = 8 - r_off; /* Now, roffset into gcode word. */
617 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
618 if (bits >= 8) {
619 gcode |= *bp++ << r_off;
620 r_off += 8;
621 bits -= 8;
624 /* High order bits. */
625 gcode |= (*bp & rmask[bits]) << r_off;
626 roffset += n_bits;
628 return (gcode);
631 static int
632 cl_block(struct s_zstate *zs) /* Table clear for block compress. */
634 long rat;
636 checkpoint = in_count + CHECK_GAP;
638 if (in_count > 0x007fffff) { /* Shift will overflow. */
639 rat = bytes_out >> 8;
640 if (rat == 0) /* Don't divide by zero. */
641 rat = 0x7fffffff;
642 else
643 rat = in_count / rat;
644 } else
645 rat = (in_count << 8) / bytes_out; /* 8 fractional bits. */
646 if (rat > ratio)
647 ratio = rat;
648 else {
649 ratio = 0;
650 cl_hash(zs, (count_int) hsize);
651 free_ent = FIRST;
652 clear_flg = 1;
653 if (output(zs, (code_int) CLEAR) == -1)
654 return (-1);
656 return (0);
659 static void
660 cl_hash(struct s_zstate *zs, count_int cl_hsize) /* Reset code table. */
662 count_int *htab_p;
663 long i, m1;
665 m1 = -1;
666 htab_p = htab + cl_hsize;
667 i = cl_hsize - 16;
668 do { /* Might use Sys V memset(3) here. */
669 *(htab_p - 16) = m1;
670 *(htab_p - 15) = m1;
671 *(htab_p - 14) = m1;
672 *(htab_p - 13) = m1;
673 *(htab_p - 12) = m1;
674 *(htab_p - 11) = m1;
675 *(htab_p - 10) = m1;
676 *(htab_p - 9) = m1;
677 *(htab_p - 8) = m1;
678 *(htab_p - 7) = m1;
679 *(htab_p - 6) = m1;
680 *(htab_p - 5) = m1;
681 *(htab_p - 4) = m1;
682 *(htab_p - 3) = m1;
683 *(htab_p - 2) = m1;
684 *(htab_p - 1) = m1;
685 htab_p -= 16;
686 } while ((i -= 16) >= 0);
687 for (i += 16; i > 0; i--)
688 *--htab_p = m1;
691 #undef fp
692 void *
693 zalloc(FILE *fp)
695 #define bits BITS
696 struct s_zstate *zs;
698 zs = scalloc(1, sizeof *zs);
699 maxbits = bits ? bits : BITS; /* User settable max # bits/code. */
700 maxmaxcode = 1L << maxbits; /* Should NEVER generate this code. */
701 hsize = HSIZE; /* For dynamic table sizing. */
702 free_ent = 0; /* First unused entry. */
703 block_compress = BLOCK_MASK;
704 clear_flg = 0;
705 ratio = 0;
706 checkpoint = CHECK_GAP;
707 in_count = 1; /* Length of input. */
708 out_count = 0; /* # of codes output (for debugging). */
709 state = S_START;
710 roffset = 0;
711 size = 0;
712 zs->zs_fp = fp;
713 return zs;
715 #endif /* ! defined USE_IMAP && ! defined USE_JUNK */