2 * Heirloom mailx - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
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
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
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 */
48 * lzw.c - File compression ala IEEE Computer, June 1984.
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
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)
95 FILE *zs_fp
; /* File stream for I/O */
96 char zs_mode
; /* r or w */
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
;
115 count_int zs_checkpoint
;
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];
125 code_int zs_hsize_reg
;
127 } w
; /* Write paramenters */
129 char_type
*zs_stackp
;
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 */
138 /* Definitions to retain old variable names */
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.
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.
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.
229 zwrite(void *cookie
, const char *wbp
, int num
)
234 const unsigned char *bp
;
244 bp
= (const unsigned char *)wbp
;
245 if (state
== ST_MIDDLE
)
249 maxmaxcode
= 1L << maxbits
;
250 if (fwrite(magic_header
,
251 sizeof(char), sizeof(magic_header
), fp
) != sizeof(magic_header
))
253 tmp
= (unsigned char)((maxbits
) | block_compress
);
254 if (fwrite(&tmp
, sizeof(char), sizeof(tmp
), fp
) != sizeof(tmp
))
258 bytes_out
= 3; /* Includes 3-byte header mojo. */
263 checkpoint
= CHECK_GAP
;
264 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
265 free_ent
= ((block_compress
) ? FIRST
: 256);
271 for (fcode
= (long)hsize
; fcode
< 65536L; fcode
*= 2L)
273 hshift
= 8 - hshift
; /* Set hash code range bound. */
276 cl_hash(zs
, (count_int
)hsize_reg
); /* Clear hash table. */
278 middle
: for (i
= 0; count
--;) {
281 fcode
= (long)(((long)c
<< maxbits
) + ent
);
282 i
= ((c
<< hshift
) ^ ent
); /* Xor hashing. */
284 if (htabof(i
) == fcode
) {
287 } else if ((long)htabof(i
) < 0) /* Empty slot. */
289 disp
= hsize_reg
- i
; /* Secondary hash (after G. Knott). */
292 probe
: if ((i
-= disp
) < 0)
295 if (htabof(i
) == fcode
) {
299 if ((long)htabof(i
) >= 0)
301 nomatch
: if (output(zs
, (code_int
) ent
) == -1)
305 if (free_ent
< maxmaxcode
) {
306 codetabof(i
) = free_ent
++; /* code -> hashtable */
308 } else if ((count_int
)in_count
>=
309 checkpoint
&& block_compress
) {
310 if (cl_block(zs
) == -1)
323 if (zmode
== 'w') { /* Put out the final code. */
324 if (output(zs
, (code_int
) ent
) == -1) {
329 if (output(zs
, (code_int
) - 1) == -1) {
339 * Output the given code.
341 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
342 * that n_bits =< (long)wordsize - 1.
344 * Outputs code to the file.
346 * Chars are 8 bits long.
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};
359 output(struct s_zstate
*zs
, code_int ocode
)
369 /* Get to the first byte. */
373 * Since ocode is always >= 8 bits, only need to mask the first
376 *bp
= (*bp
& rmask
[r_off
]) | ((ocode
<< r_off
) & lmask
[r_off
]);
380 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
390 if (offset
== (n_bits
<< 3)) {
394 if (fwrite(bp
, sizeof(char), bits
, fp
) != bits
)
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.
410 if (fwrite(buf
, 1, n_bits
, fp
) != n_bits
)
417 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
421 if (n_bits
== maxbits
)
422 maxcode
= maxmaxcode
;
424 maxcode
= MAXCODE(n_bits
);
428 /* At EOF, write the rest of the buffer. */
430 offset
= (offset
+ 7) / 8;
431 if (fwrite(buf
, 1, offset
, fp
) != offset
)
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.
447 zread(void *cookie
, char *rbp
, int num
)
451 unsigned char *bp
, header
[3];
458 bp
= (unsigned char *)rbp
;
469 /* Check the magic number */
471 sizeof(char), sizeof(header
), fp
) != sizeof(header
) ||
472 memcmp(header
, magic_header
, sizeof(magic_header
)) != 0) {
475 maxbits
= header
[2]; /* Set -b from file. */
476 block_compress
= maxbits
& BLOCK_MASK
;
478 maxmaxcode
= 1L << maxbits
;
479 if (maxbits
> BITS
) {
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
;
499 while ((code
= getcode(zs
)) > -1) {
501 if ((code
== CLEAR
) && block_compress
) {
502 for (code
= 255; code
>= 0; code
--)
503 tab_prefixof(code
) = 0;
505 free_ent
= FIRST
- 1;
506 if ((code
= getcode(zs
)) == -1) /* O, untimely death! */
511 /* Special case for KwKwK string. */
512 if (code
>= free_ent
) {
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. */
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
;
538 /* Remember previous code. */
542 eof
: return (num
- count
);
546 * Read one code from the standard input. If EOF, return -1.
550 * code or -1 is returned.
553 getcode(struct s_zstate
*zs
)
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
) {
568 if (n_bits
== maxbits
) /* Won't get any bigger now. */
569 maxcode
= maxmaxcode
;
571 maxcode
= MAXCODE(n_bits
);
574 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
577 size
= fread(gbuf
, 1, n_bits
, fp
);
578 if (size
<= 0) /* End of file. */
581 /* Round size down to integral number of codes. */
582 size
= (size
<< 3) - (n_bits
- 1);
587 /* Get to the first byte. */
591 /* Get first part (low order bits). */
592 gcode
= (*bp
++ >> 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). */
598 gcode
|= *bp
++ << r_off
;
603 /* High order bits. */
604 gcode
|= (*bp
& rmask
[bits
]) << r_off
;
611 cl_block ( /* Table clear for block compress. */
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. */
624 rat
= in_count
/ rat
;
626 rat
= (in_count
<< 8) / bytes_out
; /* 8 fractional bits. */
631 cl_hash(zs
, (count_int
) hsize
);
634 if (output(zs
, (code_int
) CLEAR
) == -1)
641 cl_hash ( /* Reset code table. */
650 htab_p
= htab
+ cl_hsize
;
652 do { /* Might use Sys V memset(3) here. */
670 } while ((i
-= 16) >= 0);
671 for (i
+= 16; i
> 0; i
--)
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
;
690 checkpoint
= CHECK_GAP
;
691 in_count
= 1; /* Length of input. */
692 out_count
= 0; /* # of codes output (for debugging). */