2 * Copyright (c) 1985, 1986, 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Diomidis Spinellis and James A. Woods, derived from original
7 * work by Spencer Thomas and Joseph Orost.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)zopen.c 8.1 (Berkeley) 6/27/93";
40 #endif /* LIBC_SCCS and not lint */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD: src/usr.bin/compress/zopen.c,v 1.5.6.1 2002/07/16 00:52:08 tjr Exp $");
46 * fcompress.c - File compression ala IEEE Computer, June 1984.
49 * Spencer W. Thomas (decvax!utah-cs!thomas)
50 * Jim McKie (decvax!mcvax!jim)
51 * Steve Davies (decvax!vax135!petsd!peora!srd)
52 * Ken Turkowski (decvax!decwrl!turtlevax!ken)
53 * James A. Woods (decvax!ihnp4!ames!jaw)
54 * Joe Orost (decvax!vax135!petsd!joe)
56 * Cleaned up and converted to library returning I/O streams by
57 * Diomidis Spinellis <dds@doc.ic.ac.uk>.
59 * zopen(filename, mode, bits)
60 * Returns a FILE * that can be used for read or write. The modes
61 * supported are only "r" and "w". Seeking is not allowed. On
62 * reading the file is decompressed, on writing it is compressed.
63 * The output is compatible with compress(1) with 16 bit tables.
64 * Any file produced by compress(1) can be read.
67 #include <sys/param.h>
79 #define BITS 16 /* Default bits. */
80 #define HSIZE 69001 /* 95% occupancy */
82 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
83 typedef long code_int;
84 typedef long count_int;
86 typedef u_char char_type;
87 static char_type magic_header[] =
88 {'\037', '\235'}; /* 1F 9D */
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)
102 FILE *zs_fp; /* File stream for I/O */
103 char zs_mode; /* r or w */
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;
122 count_int zs_checkpoint;
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];
132 code_int zs_hsize_reg;
134 } w; /* Write paramenters */
136 char_type *zs_stackp;
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 */
145 /* Definitions to retain old variable names */
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);
208 static int zclose(void *);
209 static int zread(void *, char *, int);
210 static int zwrite(void *, const char *, int);
213 * Algorithm from "A Technique for High Performance Data Compression",
214 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
217 * Modified Lempel-Ziv method (LZW). Basically finds common
218 * substrings and replaces them with a variable size code. This is
219 * deterministic, and can be done on the fly. Thus, the decompression
220 * procedure needs no input table, but tracks the way the table was built.
226 * Algorithm: use open addressing double hashing (no chaining) on the
227 * prefix code / next character combination. We do a variant of Knuth's
228 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
229 * secondary probe. Here, the modular division first probe is gives way
230 * to a faster exclusive-or manipulation. Also do block compression with
231 * an adaptive reset, whereby the code table is cleared when the compression
232 * ratio decreases, but after the table fills. The variable-length output
233 * codes are re-sized at this point, and a special CLEAR code is generated
234 * for the decompressor. Late addition: construct the table according to
235 * file size for noticeable speed improvement on small files. Please direct
236 * questions about this implementation to ames!jaw.
239 zwrite(cookie, wbp, num)
257 if (state == S_MIDDLE)
261 maxmaxcode = 1L << maxbits;
262 if (fwrite(magic_header,
263 sizeof(char), sizeof(magic_header), fp) != sizeof(magic_header))
265 tmp = (u_char)((maxbits) | block_compress);
266 if (fwrite(&tmp, sizeof(char), sizeof(tmp), fp) != sizeof(tmp))
270 bytes_out = 3; /* Includes 3-byte header mojo. */
275 checkpoint = CHECK_GAP;
276 maxcode = MAXCODE(n_bits = INIT_BITS);
277 free_ent = ((block_compress) ? FIRST : 256);
283 for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L)
285 hshift = 8 - hshift; /* Set hash code range bound. */
288 cl_hash(zs, (count_int)hsize_reg); /* Clear hash table. */
290 middle: for (i = 0; count--;) {
293 fcode = (long)(((long)c << maxbits) + ent);
294 i = ((c << hshift) ^ ent); /* Xor hashing. */
296 if (htabof(i) == fcode) {
299 } else if ((long)htabof(i) < 0) /* Empty slot. */
301 disp = hsize_reg - i; /* Secondary hash (after G. Knott). */
304 probe: if ((i -= disp) < 0)
307 if (htabof(i) == fcode) {
311 if ((long)htabof(i) >= 0)
313 nomatch: if (output(zs, (code_int) ent) == -1)
317 if (free_ent < maxmaxcode) {
318 codetabof(i) = free_ent++; /* code -> hashtable */
320 } else if ((count_int)in_count >=
321 checkpoint && block_compress) {
322 if (cl_block(zs) == -1)
337 if (zmode == 'w') { /* Put out the final code. */
338 if (output(zs, (code_int) ent) == -1) {
344 if (output(zs, (code_int) - 1) == -1) {
350 rval = fclose(fp) == EOF ? -1 : 0;
356 * Output the given code.
358 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
359 * that n_bits =< (long)wordsize - 1.
361 * Outputs code to the file.
363 * Chars are 8 bits long.
365 * Maintain a BITS character long buffer (so that 8 codes will
366 * fit in it exactly). Use the VAX insv instruction to insert each
367 * code in turn. When the buffer fills up empty it and start over.
370 static char_type lmask[9] =
371 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
372 static char_type rmask[9] =
373 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
388 /* Get to the first byte. */
392 * Since ocode is always >= 8 bits, only need to mask the first
395 *bp = (*bp & rmask[r_off]) | ((ocode << r_off) & lmask[r_off]);
399 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
409 if (offset == (n_bits << 3)) {
413 if (fwrite(bp, sizeof(char), bits, fp) != bits)
420 * If the next entry is going to be too big for the ocode size,
421 * then increase it, if possible.
423 if (free_ent > maxcode || (clear_flg > 0)) {
425 * Write the whole buffer, because the input side won't
426 * discover the size increase until after it has read it.
429 if (fwrite(buf, 1, n_bits, fp) != n_bits)
436 maxcode = MAXCODE(n_bits = INIT_BITS);
440 if (n_bits == maxbits)
441 maxcode = maxmaxcode;
443 maxcode = MAXCODE(n_bits);
447 /* At EOF, write the rest of the buffer. */
449 offset = (offset + 7) / 8;
450 if (fwrite(buf, 1, offset, fp) != offset)
460 * Decompress read. This routine adapts to the codes in the file building
461 * the "string" table on-the-fly; requiring no table to be stored in the
462 * compressed file. The tables used herein are shared with those of the
463 * compress() routine. See the definitions above.
466 zread(cookie, rbp, num)
473 u_char *bp, header[3];
491 /* Check the magic number */
493 sizeof(char), sizeof(header), fp) != sizeof(header) ||
494 memcmp(header, magic_header, sizeof(magic_header)) != 0) {
498 maxbits = header[2]; /* Set -b from file. */
499 block_compress = maxbits & BLOCK_MASK;
501 maxmaxcode = 1L << maxbits;
502 if (maxbits > BITS) {
506 /* As above, initialize the first 256 entries in the table. */
507 maxcode = MAXCODE(n_bits = INIT_BITS);
508 for (code = 255; code >= 0; code--) {
509 tab_prefixof(code) = 0;
510 tab_suffixof(code) = (char_type) code;
512 free_ent = block_compress ? FIRST : 256;
514 finchar = oldcode = getcode(zs);
515 if (oldcode == -1) /* EOF already? */
516 return (0); /* Get out of here */
518 /* First code must be 8 bits = char. */
519 *bp++ = (u_char)finchar;
523 while ((code = getcode(zs)) > -1) {
525 if ((code == CLEAR) && block_compress) {
526 for (code = 255; code >= 0; code--)
527 tab_prefixof(code) = 0;
529 free_ent = FIRST - 1;
530 if ((code = getcode(zs)) == -1) /* O, untimely death! */
535 /* Special case for KwKwK string. */
536 if (code >= free_ent) {
541 /* Generate output characters in reverse order. */
542 while (code >= 256) {
543 *stackp++ = tab_suffixof(code);
544 code = tab_prefixof(code);
546 *stackp++ = finchar = tab_suffixof(code);
548 /* And put them out in forward order. */
553 } while (stackp > de_stack);
555 /* Generate the new entry. */
556 if ((code = free_ent) < maxmaxcode) {
557 tab_prefixof(code) = (u_short) oldcode;
558 tab_suffixof(code) = finchar;
562 /* Remember previous code. */
566 eof: return (num - count);
570 * Read one code from the standard input. If EOF, return -1.
574 * code or -1 is returned.
585 if (clear_flg > 0 || roffset >= size || free_ent > maxcode) {
587 * If the next entry will be too big for the current gcode
588 * size, then we must increase the size. This implies reading
589 * a new buffer full, too.
591 if (free_ent > maxcode) {
593 if (n_bits == maxbits) /* Won't get any bigger now. */
594 maxcode = maxmaxcode;
596 maxcode = MAXCODE(n_bits);
599 maxcode = MAXCODE(n_bits = INIT_BITS);
602 size = fread(gbuf, 1, n_bits, fp);
603 if (size <= 0) /* End of file. */
606 /* Round size down to integral number of codes. */
607 size = (size << 3) - (n_bits - 1);
612 /* Get to the first byte. */
616 /* Get first part (low order bits). */
617 gcode = (*bp++ >> r_off);
619 r_off = 8 - r_off; /* Now, roffset into gcode word. */
621 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
623 gcode |= *bp++ << r_off;
628 /* High order bits. */
629 gcode |= (*bp & rmask[bits]) << r_off;
636 cl_block(zs) /* Table clear for block compress. */
641 checkpoint = in_count + CHECK_GAP;
643 if (in_count > 0x007fffff) { /* Shift will overflow. */
644 rat = bytes_out >> 8;
645 if (rat == 0) /* Don't divide by zero. */
648 rat = in_count / rat;
650 rat = (in_count << 8) / bytes_out; /* 8 fractional bits. */
655 cl_hash(zs, (count_int) hsize);
658 if (output(zs, (code_int) CLEAR) == -1)
665 cl_hash(zs, cl_hsize) /* Reset code table. */
673 htab_p = htab + cl_hsize;
675 do { /* Might use Sys V memset(3) here. */
693 } while ((i -= 16) >= 0);
694 for (i += 16; i > 0; i--)
699 zopen(fname, mode, bits)
700 const char *fname, *mode;
705 if ((mode[0] != 'r' && mode[0] != 'w') || mode[1] != '\0' ||
706 bits < 0 || bits > BITS) {
711 if ((zs = calloc(1, sizeof(struct s_zstate))) == NULL)
714 maxbits = bits ? bits : BITS; /* User settable max # bits/code. */
715 maxmaxcode = 1L << maxbits; /* Should NEVER generate this code. */
716 hsize = HSIZE; /* For dynamic table sizing. */
717 free_ent = 0; /* First unused entry. */
718 block_compress = BLOCK_MASK;
721 checkpoint = CHECK_GAP;
722 in_count = 1; /* Length of input. */
723 out_count = 0; /* # of codes output (for debugging). */
729 * Layering compress on top of stdio in order to provide buffering,
730 * and ensure that reads and write work with the data specified.
732 if ((fp = fopen(fname, mode)) == NULL) {
739 return (funopen(zs, zread, NULL, NULL, zclose));
742 return (funopen(zs, NULL, zwrite, NULL, zclose));