nail.h: use MAXPATHLEN as fallback for struct cw
[s-mailx.git] / lzw.c
blob757fe25391375f9ceb70171a9fb62b972910ade0
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ LZW file compression.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2013 Steffen "Daode" Nurpmeso <sdaoden@users.sf.net>.
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) */
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.
64 #include "config.h"
66 #ifndef HAVE_IMAP
67 typedef int avoid_empty_file_compiler_warning;
68 #else
69 #include "nail.h"
71 /* Minimize differences to FreeBSDs usr.bin/compress/zopen.c */
72 #undef u_int
73 #define u_int unsigned int
74 #undef u_short
75 #define u_short unsigned short
76 #undef u_char
77 #define u_char unsigned char
78 #define count cnt
80 #define BITS 16 /* Default bits. */
81 #define HSIZE 69001 /* 95% occupancy */
83 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
84 typedef long code_int;
85 typedef long count_int;
87 typedef u_char char_type;
88 static char_type magic_header[] = {0x1F, 0x9D}; /* \037, \235 */
90 #define BIT_MASK 0x1f /* Defines for third byte of header. */
91 #define BLOCK_MASK 0x80
94 * Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is
95 * a fourth header byte (for expansion).
97 #define INIT_BITS 9 /* Initial number of bits/code. */
99 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
101 struct s_zstate {
102 FILE *zs_fp; /* File stream for I/O */
103 char zs_mode; /* r or w */
104 enum {
105 S_START, S_MIDDLE, S_EOF
106 } zs_state; /* State of computation */
107 u_int zs_n_bits; /* Number of bits/code. */
108 u_int zs_maxbits; /* User settable max # bits/code. */
109 code_int zs_maxcode; /* Maximum code, given n_bits. */
110 code_int zs_maxmaxcode; /* Should NEVER generate this code. */
111 count_int zs_htab [HSIZE];
112 u_short zs_codetab [HSIZE];
113 code_int zs_hsize; /* For dynamic table sizing. */
114 code_int zs_free_ent; /* First unused entry. */
116 * Block compression parameters -- after all codes are used up,
117 * and compression rate changes, start over.
119 int zs_block_compress;
120 int zs_clear_flg;
121 long zs_ratio;
122 count_int zs_checkpoint;
123 u_int zs_offset;
124 long zs_in_count; /* Length of input. */
125 long zs_bytes_out; /* Length of compressed output. */
126 long zs_out_count; /* # of codes output (for debugging). */
127 char_type zs_buf[BITS];
128 union {
129 struct {
130 long zs_fcode;
131 code_int zs_ent;
132 code_int zs_hsize_reg;
133 int zs_hshift;
134 } w; /* Write parameters */
135 struct {
136 char_type *zs_stackp;
137 int zs_finchar;
138 code_int zs_code, zs_oldcode, zs_incode;
139 int zs_roffset, zs_size;
140 char_type zs_gbuf[BITS];
141 } r; /* Read parameters */
142 } u;
145 /* Definitions to retain old variable names */
146 #define fp zs->zs_fp
147 #define zmode zs->zs_mode
148 #define state zs->zs_state
149 #define n_bits zs->zs_n_bits
150 #define maxbits zs->zs_maxbits
151 #define maxcode zs->zs_maxcode
152 #define maxmaxcode zs->zs_maxmaxcode
153 #define htab zs->zs_htab
154 #define codetab zs->zs_codetab
155 #define hsize zs->zs_hsize
156 #define free_ent zs->zs_free_ent
157 #define block_compress zs->zs_block_compress
158 #define clear_flg zs->zs_clear_flg
159 #define ratio zs->zs_ratio
160 #define checkpoint zs->zs_checkpoint
161 #define offset zs->zs_offset
162 #define in_count zs->zs_in_count
163 #define bytes_out zs->zs_bytes_out
164 #define out_count zs->zs_out_count
165 #define buf zs->zs_buf
166 #define fcode zs->u.w.zs_fcode
167 #define hsize_reg zs->u.w.zs_hsize_reg
168 #define ent zs->u.w.zs_ent
169 #define hshift zs->u.w.zs_hshift
170 #define stackp zs->u.r.zs_stackp
171 #define finchar zs->u.r.zs_finchar
172 #define code zs->u.r.zs_code
173 #define oldcode zs->u.r.zs_oldcode
174 #define incode zs->u.r.zs_incode
175 #define roffset zs->u.r.zs_roffset
176 #define size zs->u.r.zs_size
177 #define gbuf zs->u.r.zs_gbuf
180 * To save much memory, we overlay the table used by compress() with those
181 * used by decompress(). The tab_prefix table is the same size and type as
182 * the codetab. The tab_suffix table needs 2**BITS characters. We get this
183 * from the beginning of htab. The output stack uses the rest of htab, and
184 * contains characters. There is plenty of room for any possible stack
185 * (stack used to be 8000 characters).
188 #define htabof(i) htab[i]
189 #define codetabof(i) codetab[i]
191 #define tab_prefixof(i) codetabof(i)
192 #define tab_suffixof(i) ((char_type *)(htab))[i]
193 #define de_stack ((char_type *)&tab_suffixof(1 << BITS))
195 #define CHECK_GAP 10000 /* Ratio check interval. */
198 * the next two codes should not be changed lightly, as they must not
199 * lie within the contiguous general code space.
201 #define FIRST 257 /* First free entry. */
202 #define CLEAR 256 /* Table clear output code. */
204 static int cl_block(struct s_zstate *);
205 static void cl_hash(struct s_zstate *, count_int);
206 static code_int getcode(struct s_zstate *);
207 static int output(struct s_zstate *, code_int);
210 * Algorithm from "A Technique for High Performance Data Compression",
211 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
213 * Algorithm:
214 * Modified Lempel-Ziv method (LZW). Basically finds common
215 * substrings and replaces them with a variable size code. This is
216 * deterministic, and can be done on the fly. Thus, the decompression
217 * procedure needs no input table, but tracks the way the table was built.
221 * compress write
223 * Algorithm: use open addressing double hashing (no chaining) on the
224 * prefix code / next character combination. We do a variant of Knuth's
225 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
226 * secondary probe. Here, the modular division first probe is gives way
227 * to a faster exclusive-or manipulation. Also do block compression with
228 * an adaptive reset, whereby the code table is cleared when the compression
229 * ratio decreases, but after the table fills. The variable-length output
230 * codes are re-sized at this point, and a special CLEAR code is generated
231 * for the decompressor. Late addition: construct the table according to
232 * file size for noticeable speed improvement on small files. Please direct
233 * questions about this implementation to ames!jaw.
236 zwrite(void *cookie, const char *wbp, int num)
238 code_int i;
239 int c, disp;
240 struct s_zstate *zs;
241 const u_char *bp;
242 u_char tmp;
243 int count;
245 if (num == 0)
246 return (0);
248 zs = cookie;
249 zmode = 'w';
250 count = num;
251 bp = (const u_char *)wbp;
252 if (state == S_MIDDLE)
253 goto middle;
254 state = S_MIDDLE;
256 maxmaxcode = 1L << maxbits;
257 if (fwrite(magic_header,
258 sizeof(char), sizeof(magic_header), fp) != sizeof(magic_header))
259 return (-1);
260 tmp = (u_char)((maxbits) | block_compress);
261 if (fwrite(&tmp, sizeof(char), sizeof(tmp), fp) != sizeof(tmp))
262 return (-1);
264 offset = 0;
265 bytes_out = 3; /* Includes 3-byte header mojo. */
266 out_count = 0;
267 clear_flg = 0;
268 ratio = 0;
269 in_count = 1;
270 checkpoint = CHECK_GAP;
271 maxcode = MAXCODE(n_bits = INIT_BITS);
272 free_ent = ((block_compress) ? FIRST : 256);
274 ent = *bp++;
275 --count;
277 hshift = 0;
278 for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L)
279 hshift++;
280 hshift = 8 - hshift; /* Set hash code range bound. */
282 hsize_reg = hsize;
283 cl_hash(zs, (count_int)hsize_reg); /* Clear hash table. */
285 middle: for (i = 0; count--;) {
286 c = *bp++;
287 in_count++;
288 fcode = (long)(((long)c << maxbits) + ent);
289 i = ((c << hshift) ^ ent); /* Xor hashing. */
291 if (htabof(i) == fcode) {
292 ent = codetabof(i);
293 continue;
294 } else if ((long)htabof(i) < 0) /* Empty slot. */
295 goto nomatch;
296 disp = hsize_reg - i; /* Secondary hash (after G. Knott). */
297 if (i == 0)
298 disp = 1;
299 probe: if ((i -= disp) < 0)
300 i += hsize_reg;
302 if (htabof(i) == fcode) {
303 ent = codetabof(i);
304 continue;
306 if ((long)htabof(i) >= 0)
307 goto probe;
308 nomatch: if (output(zs, (code_int) ent) == -1)
309 return (-1);
310 out_count++;
311 ent = c;
312 if (free_ent < maxmaxcode) {
313 codetabof(i) = free_ent++; /* code -> hashtable */
314 htabof(i) = fcode;
315 } else if ((count_int)in_count >=
316 checkpoint && block_compress) {
317 if (cl_block(zs) == -1)
318 return (-1);
321 return (num);
325 zfree(void *cookie)
327 struct s_zstate *zs;
329 zs = cookie;
330 if (zmode == 'w') { /* Put out the final code. */
331 if (output(zs, (code_int) ent) == -1) {
332 free(zs);
333 return (-1);
335 out_count++;
336 if (output(zs, (code_int) - 1) == -1) {
337 free(zs);
338 return (-1);
341 free(zs);
342 return (0);
346 * Output the given code.
347 * Inputs:
348 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
349 * that n_bits =< (long)wordsize - 1.
350 * Outputs:
351 * Outputs code to the file.
352 * Assumptions:
353 * Chars are 8 bits long.
354 * Algorithm:
355 * Maintain a BITS character long buffer (so that 8 codes will
356 * fit in it exactly). Use the VAX insv instruction to insert each
357 * code in turn. When the buffer fills up empty it and start over.
360 static char_type lmask[9] =
361 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
362 static char_type rmask[9] =
363 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
365 static int
366 output(struct s_zstate *zs, code_int ocode)
368 int r_off;
369 u_int bits;
370 char_type *bp;
372 r_off = offset;
373 bits = n_bits;
374 bp = buf;
375 if (ocode >= 0) {
376 /* Get to the first byte. */
377 bp += (r_off >> 3);
378 r_off &= 7;
380 * Since ocode is always >= 8 bits, only need to mask the first
381 * hunk on the left.
383 *bp = (*bp & rmask[r_off]) | ((ocode << r_off) & lmask[r_off]);
384 bp++;
385 bits -= (8 - r_off);
386 ocode >>= 8 - r_off;
387 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
388 if (bits >= 8) {
389 *bp++ = ocode;
390 ocode >>= 8;
391 bits -= 8;
393 /* Last bits. */
394 if (bits)
395 *bp = ocode;
396 offset += n_bits;
397 if (offset == (n_bits << 3)) {
398 bp = buf;
399 bits = n_bits;
400 bytes_out += bits;
401 if (fwrite(bp, sizeof(char), bits, fp) != bits)
402 return (-1);
403 bp += bits;
404 bits = 0;
405 offset = 0;
408 * If the next entry is going to be too big for the ocode size,
409 * then increase it, if possible.
411 if (free_ent > maxcode || (clear_flg > 0)) {
413 * Write the whole buffer, because the input side won't
414 * discover the size increase until after it has read it.
416 if (offset > 0) {
417 if (fwrite(buf, 1, n_bits, fp) != n_bits)
418 return (-1);
419 bytes_out += n_bits;
421 offset = 0;
423 if (clear_flg) {
424 maxcode = MAXCODE(n_bits = INIT_BITS);
425 clear_flg = 0;
426 } else {
427 n_bits++;
428 if (n_bits == maxbits)
429 maxcode = maxmaxcode;
430 else
431 maxcode = MAXCODE(n_bits);
434 } else {
435 /* At EOF, write the rest of the buffer. */
436 if (offset > 0) {
437 offset = (offset + 7) / 8;
438 if (fwrite(buf, 1, offset, fp) != offset)
439 return (-1);
440 bytes_out += offset;
442 offset = 0;
444 return (0);
448 * Decompress read. This routine adapts to the codes in the file building
449 * the "string" table on-the-fly; requiring no table to be stored in the
450 * compressed file. The tables used herein are shared with those of the
451 * compress() routine. See the definitions above.
454 zread(void *cookie, char *rbp, int num)
456 u_int count;
457 struct s_zstate *zs;
458 u_char *bp, header[3];
460 if (num == 0)
461 return (0);
463 zs = cookie;
464 count = num;
465 bp = (u_char *)rbp;
466 switch (state) {
467 case S_START:
468 state = S_MIDDLE;
469 break;
470 case S_MIDDLE:
471 goto middle;
472 case S_EOF:
473 goto eof;
476 /* Check the magic number */
477 if (fread(header,
478 sizeof(char), sizeof(header), fp) != sizeof(header) ||
479 memcmp(header, magic_header, sizeof(magic_header)) != 0) {
480 return (-1);
482 maxbits = header[2]; /* Set -b from file. */
483 block_compress = maxbits & BLOCK_MASK;
484 maxbits &= BIT_MASK;
485 maxmaxcode = 1L << maxbits;
486 if (maxbits > BITS || maxbits < 12) {
487 return (-1);
489 /* As above, initialize the first 256 entries in the table. */
490 maxcode = MAXCODE(n_bits = INIT_BITS);
491 for (code = 255; code >= 0; code--) {
492 tab_prefixof(code) = 0;
493 tab_suffixof(code) = (char_type) code;
495 free_ent = block_compress ? FIRST : 256;
497 finchar = oldcode = getcode(zs);
498 if (oldcode == -1) /* EOF already? */
499 return (0); /* Get out of here */
501 /* First code must be 8 bits = char. */
502 *bp++ = (u_char)finchar;
503 count--;
504 stackp = de_stack;
506 while ((code = getcode(zs)) > -1) {
508 if ((code == CLEAR) && block_compress) {
509 for (code = 255; code >= 0; code--)
510 tab_prefixof(code) = 0;
511 clear_flg = 1;
512 free_ent = FIRST;
513 oldcode = -1;
514 continue;
516 incode = code;
518 /* Special case for kWkWk string. */
519 if (code >= free_ent) {
520 if (code > free_ent || oldcode == -1) {
521 return (-1);
523 *stackp++ = finchar;
524 code = oldcode;
527 * The above condition ensures that code < free_ent.
528 * The construction of tab_prefixof in turn guarantees that
529 * each iteration decreases code and therefore stack usage is
530 * bound by 1 << BITS - 256.
533 /* Generate output characters in reverse order. */
534 while (code >= 256) {
535 *stackp++ = tab_suffixof(code);
536 code = tab_prefixof(code);
538 *stackp++ = finchar = tab_suffixof(code);
540 /* And put them out in forward order. */
541 middle: do {
542 if (count-- == 0)
543 return (num);
544 *bp++ = *--stackp;
545 } while (stackp > de_stack);
547 /* Generate the new entry. */
548 if ((code = free_ent) < maxmaxcode && oldcode != -1) {
549 tab_prefixof(code) = (u_short) oldcode;
550 tab_suffixof(code) = finchar;
551 free_ent = code + 1;
554 /* Remember previous code. */
555 oldcode = incode;
557 state = S_EOF;
558 eof: return (num - count);
562 * Read one code from the standard input. If EOF, return -1.
563 * Inputs:
564 * stdin
565 * Outputs:
566 * code or -1 is returned.
568 static code_int
569 getcode(struct s_zstate *zs)
571 code_int gcode;
572 int r_off, bits;
573 char_type *bp;
575 bp = gbuf;
576 if (clear_flg > 0 || roffset >= size || free_ent > maxcode) {
578 * If the next entry will be too big for the current gcode
579 * size, then we must increase the size. This implies reading
580 * a new buffer full, too.
582 if (free_ent > maxcode) {
583 n_bits++;
584 if (n_bits == maxbits) /* Won't get any bigger now. */
585 maxcode = maxmaxcode;
586 else
587 maxcode = MAXCODE(n_bits);
589 if (clear_flg > 0) {
590 maxcode = MAXCODE(n_bits = INIT_BITS);
591 clear_flg = 0;
593 size = fread(gbuf, 1, n_bits, fp);
594 if (size <= 0) /* End of file. */
595 return (-1);
596 roffset = 0;
597 /* Round size down to integral number of codes. */
598 size = (size << 3) - (n_bits - 1);
600 r_off = roffset;
601 bits = n_bits;
603 /* Get to the first byte. */
604 bp += (r_off >> 3);
605 r_off &= 7;
607 /* Get first part (low order bits). */
608 gcode = (*bp++ >> r_off);
609 bits -= (8 - r_off);
610 r_off = 8 - r_off; /* Now, roffset into gcode word. */
612 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
613 if (bits >= 8) {
614 gcode |= *bp++ << r_off;
615 r_off += 8;
616 bits -= 8;
619 /* High order bits. */
620 gcode |= (*bp & rmask[bits]) << r_off;
621 roffset += n_bits;
623 return (gcode);
626 static int
627 cl_block(struct s_zstate *zs) /* Table clear for block compress. */
629 long rat;
631 checkpoint = in_count + CHECK_GAP;
633 if (in_count > 0x007fffff) { /* Shift will overflow. */
634 rat = bytes_out >> 8;
635 if (rat == 0) /* Don't divide by zero. */
636 rat = 0x7fffffff;
637 else
638 rat = in_count / rat;
639 } else
640 rat = (in_count << 8) / bytes_out; /* 8 fractional bits. */
641 if (rat > ratio)
642 ratio = rat;
643 else {
644 ratio = 0;
645 cl_hash(zs, (count_int) hsize);
646 free_ent = FIRST;
647 clear_flg = 1;
648 if (output(zs, (code_int) CLEAR) == -1)
649 return (-1);
651 return (0);
654 static void
655 cl_hash(struct s_zstate *zs, count_int cl_hsize) /* Reset code table. */
657 count_int *htab_p;
658 long i, m1;
660 m1 = -1;
661 htab_p = htab + cl_hsize;
662 i = cl_hsize - 16;
663 do { /* Might use Sys V memset(3) here. */
664 *(htab_p - 16) = m1;
665 *(htab_p - 15) = m1;
666 *(htab_p - 14) = m1;
667 *(htab_p - 13) = m1;
668 *(htab_p - 12) = m1;
669 *(htab_p - 11) = m1;
670 *(htab_p - 10) = m1;
671 *(htab_p - 9) = m1;
672 *(htab_p - 8) = m1;
673 *(htab_p - 7) = m1;
674 *(htab_p - 6) = m1;
675 *(htab_p - 5) = m1;
676 *(htab_p - 4) = m1;
677 *(htab_p - 3) = m1;
678 *(htab_p - 2) = m1;
679 *(htab_p - 1) = m1;
680 htab_p -= 16;
681 } while ((i -= 16) >= 0);
682 for (i += 16; i > 0; i--)
683 *--htab_p = m1;
686 #undef fp
687 void *
688 zalloc(FILE *fp)
690 #define bits BITS
691 struct s_zstate *zs;
693 zs = scalloc(1, sizeof *zs);
694 maxbits = bits ? bits : BITS; /* User settable max # bits/code. */
695 maxmaxcode = 1L << maxbits; /* Should NEVER generate this code. */
696 hsize = HSIZE; /* For dynamic table sizing. */
697 free_ent = 0; /* First unused entry. */
698 block_compress = BLOCK_MASK;
699 clear_flg = 0;
700 ratio = 0;
701 checkpoint = CHECK_GAP;
702 in_count = 1; /* Length of input. */
703 out_count = 0; /* # of codes output (for debugging). */
704 state = S_START;
705 roffset = 0;
706 size = 0;
707 zs->zs_fp = fp;
708 return zs;
710 #endif /* ndef HAVE_IMAP */