1 #pragma prototyped
2 
3 /*
4  * compress encoder/decoder
5  *
6  * compress/zcat discipline snarfed from BSD zopen by
7  * Glenn Fowler
8  * AT&T Research
9  * 1999-06-23
10  */
11 
12 /*-
13  * Copyright (c) 1985, 1986, 1992, 1993
14  *	The Regents of the University of California.  All rights reserved.
15  *
16  * This code is derived from software contributed to Berkeley by
17  * Diomidis Spinellis and James A. Woods, derived from original
18  * work by Spencer Thomas and Joseph Orost.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  * 3. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  */
44 
45 /*-
46  * fcompress.c - File compression ala IEEE Computer, June 1984.
47  *
48  * Compress authors:
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)
55  *
56  * Cleaned up and converted to library returning I/O streams by
57  * Diomidis Spinellis <dds@doc.ic.ac.uk>.
58  */
59 
60 #include <codex.h>
61 
62 #define MAGIC1		0x1f
63 #define MAGIC2		0x9d
64 #define HEADER		3
65 
66 #define MINBITS		9
67 #define MAXBITS		16
68 
69 #define	BITS		MAXBITS		/* Default bits. */
70 #define	HSIZE		69001		/* 95% occupancy */
71 
72 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
73 typedef int32_t code_int;
74 typedef int32_t count_int;
75 
76 typedef u_char char_type;
77 
78 #define	BIT_MASK	0x1f		/* Defines for third byte of header. */
79 #define	BLOCK_MASK	0x80
80 
81 /*
82  * Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
83  * a fourth header byte (for expansion).
84  */
85 #define	INIT_BITS 9			/* Initial number of bits/code. */
86 
87 #define	MAXCODE(n_bits)	((1 << (n_bits)) - 1)
88 
89 typedef struct s_zstate {
90 	Codex_t* codex;
91 	enum {
92 		S_START, S_MIDDLE, S_EOF
93 	} zs_state;			/* State of computation */
94 	int zs_n_bits;			/* Number of bits/code. */
95 	int zs_maxbits;			/* User settable max # bits/code. */
96 	code_int zs_maxcode;		/* Maximum code, given n_bits. */
97 	code_int zs_maxmaxcode;		/* Should NEVER generate this code. */
98 	count_int zs_htab [HSIZE];
99 	u_short zs_codetab [HSIZE];
100 	code_int zs_hsize;		/* For dynamic table sizing. */
101 	code_int zs_free_ent;		/* First unused entry. */
102 	/*
103 	 * Block compression parameters -- after all codes are used up,
104 	 * and compression rate changes, start over.
105 	 */
106 	int zs_block_compress;
107 	int zs_clear_flg;
108 	long zs_ratio;
109 	count_int zs_checkpoint;
110 	int zs_offset;
111 	long zs_in_count;		/* Length of input. */
112 	long zs_bytes_out;		/* Length of compressed output. */
113 	long zs_sync_out;		/* bytes_out at last sync */
114 	long zs_out_count;		/* # of codes output (for debugging). */
115 	char_type zs_buf[BITS];
116 	union {
117 		struct {
118 			long zs_fcode;
119 			code_int zs_ent;
120 			code_int zs_hsize_reg;
121 			int zs_hshift;
122 		} w;			/* Write paramenters */
123 		struct {
124 			char_type *zs_stackp;
125 			int zs_finchar;
126 			code_int zs_code, zs_oldcode, zs_incode;
127 			int zs_roffset, zs_size;
128 			char_type zs_gbuf[BITS];
129 		} r;			/* Read parameters */
130 	} u;
131 } State_t;
132 
133 /* Definitions to retain old variable names */
134 #define	state		zs->zs_state
135 #define	n_bits		zs->zs_n_bits
136 #define	maxbits		zs->zs_maxbits
137 #define	maxcode		zs->zs_maxcode
138 #define	maxmaxcode	zs->zs_maxmaxcode
139 #define	htab		zs->zs_htab
140 #define	codetab		zs->zs_codetab
141 #define	hsize		zs->zs_hsize
142 #define	free_ent	zs->zs_free_ent
143 #define	block_compress	zs->zs_block_compress
144 #define	clear_flg	zs->zs_clear_flg
145 #define	ratio		zs->zs_ratio
146 #define	checkpoint	zs->zs_checkpoint
147 #define	offset		zs->zs_offset
148 #define	in_count	zs->zs_in_count
149 #define	bytes_out	zs->zs_bytes_out
150 #define	sync_out	zs->zs_sync_out
151 #define	out_count	zs->zs_out_count
152 #define	buf		zs->zs_buf
153 #define	fcode		zs->u.w.zs_fcode
154 #define	hsize_reg	zs->u.w.zs_hsize_reg
155 #define	ent		zs->u.w.zs_ent
156 #define	hshift		zs->u.w.zs_hshift
157 #define	stackp		zs->u.r.zs_stackp
158 #define	finchar		zs->u.r.zs_finchar
159 #define	code		zs->u.r.zs_code
160 #define	oldcode		zs->u.r.zs_oldcode
161 #define	incode		zs->u.r.zs_incode
162 #define	roffset		zs->u.r.zs_roffset
163 #define	size		zs->u.r.zs_size
164 #define	gbuf		zs->u.r.zs_gbuf
165 
166 /*
167  * To save much memory, we overlay the table used by compress() with those
168  * used by decompress().  The tab_prefix table is the same size and type as
169  * the codetab.  The tab_suffix table needs 2**BITS characters.  We get this
170  * from the beginning of htab.  The output stack uses the rest of htab, and
171  * contains characters.  There is plenty of room for any possible stack
172  * (stack used to be 8000 characters).
173  */
174 
175 #define	htabof(i)	htab[i]
176 #define	codetabof(i)	codetab[i]
177 
178 #define	tab_prefixof(i)	codetabof(i)
179 #define	tab_suffixof(i)	((char_type *)(htab))[i]
180 #define	de_stack	((char_type *)&tab_suffixof(1 << BITS))
181 
182 #define	CHECK_GAP 10000		/* Ratio check interval. */
183 
184 /*
185  * the next two codes should not be changed lightly, as they must not
186  * lie within the contiguous general code space.
187  */
188 #define	FIRST	257		/* First free entry. */
189 #define	CLEAR	256		/* Table clear output code. */
190 
191 /*-
192  * Algorithm from "A Technique for High Performance Data Compression",
193  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
194  *
195  * Algorithm:
196  * 	Modified Lempel-Ziv method (LZW).  Basically finds common
197  * substrings and replaces them with a variable size code.  This is
198  * deterministic, and can be done on the fly.  Thus, the decompression
199  * procedure needs no input table, but tracks the way the table was built.
200  */
201 
202 /*-
203  * Output the given code.
204  * Inputs:
205  * 	code:	A n_bits-bit integer.  If == -1, then EOF.  This assumes
206  *		that n_bits =< (long)wordsize - 1.
207  * Outputs:
208  * 	Outputs code to the file.
209  * Assumptions:
210  *	Chars are 8 bits long.
211  * Algorithm:
212  * 	Maintain a BITS character long buffer (so that 8 codes will
213  * fit in it exactly).  Use the VAX insv instruction to insert each
214  * code in turn.  When the buffer fills up empty it and start over.
215  */
216 
217 static char_type lmask[9] =
218 	{0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
219 static char_type rmask[9] =
220 	{0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
221 
222 static int
output(State_t * zs,Sfio_t * f,code_int ocode,Sfdisc_t * dp)223 output(State_t* zs, Sfio_t* f, code_int ocode, Sfdisc_t* dp)
224 {
225 	register int bits, r_off;
226 	register char_type *bp;
227 
228 	r_off = offset;
229 	bits = n_bits;
230 	bp = buf;
231 	if (ocode >= 0) {
232 		/* Get to the first byte. */
233 		bp += (r_off >> 3);
234 		r_off &= 7;
235 		/*
236 		 * Since ocode is always >= 8 bits, only need to mask the first
237 		 * hunk on the left.
238 		 */
239 		*bp = (*bp & rmask[r_off]) | ((ocode << r_off) & lmask[r_off]);
240 		bp++;
241 		bits -= (8 - r_off);
242 		ocode >>= 8 - r_off;
243 		/* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
244 		if (bits >= 8) {
245 			*bp++ = ocode;
246 			ocode >>= 8;
247 			bits -= 8;
248 		}
249 		/* Last bits. */
250 		if (bits)
251 			*bp = ocode;
252 		offset += n_bits;
253 		if (offset == (n_bits << 3)) {
254 			bp = buf;
255 			bits = n_bits;
256 			bytes_out += bits;
257 			if (sfwr(f, bp, bits, dp) != bits)
258 				return (-1);
259 			bp += bits;
260 			bits = 0;
261 			offset = 0;
262 		}
263 		/*
264 		 * If the next entry is going to be too big for the ocode size,
265 		 * then increase it, if possible.
266 		 */
267 		if (free_ent > maxcode || (clear_flg > 0)) {
268 		       /*
269 			* Write the whole buffer, because the input side won't
270 			* discover the size increase until after it has read it.
271 			*/
272 			if (offset > 0) {
273 				if (sfwr(f, buf, n_bits, dp) != n_bits)
274 					return (-1);
275 				bytes_out += n_bits;
276 			}
277 			offset = 0;
278 
279 			if (clear_flg) {
280 				maxcode = MAXCODE(n_bits = INIT_BITS);
281 				clear_flg = 0;
282 			} else {
283 				n_bits++;
284 				if (n_bits == maxbits)
285 					maxcode = maxmaxcode;
286 				else
287 					maxcode = MAXCODE(n_bits);
288 			}
289 		}
290 	} else {
291 		/* At EOF, write the rest of the buffer. */
292 		if (offset > 0) {
293 			offset = (offset + 7) / 8;
294 			if (sfwr(f, buf, offset, dp) != offset)
295 				return (-1);
296 			bytes_out += offset;
297 		}
298 		offset = 0;
299 	}
300 	return (0);
301 }
302 
303 /*-
304  * Read one code from the standard input.  If EOF, return -1.
305  * Inputs:
306  * 	stdin
307  * Outputs:
308  * 	code or -1 is returned.
309  */
310 static code_int
getcode(State_t * zs,Sfio_t * f,Sfdisc_t * dp)311 getcode(State_t* zs, Sfio_t* f, Sfdisc_t* dp)
312 {
313 	register code_int gcode;
314 	register int r_off, bits;
315 	register char_type *bp;
316 
317 	bp = gbuf;
318 	if (clear_flg > 0 || roffset >= size || free_ent > maxcode) {
319 		/*
320 		 * If the next entry will be too big for the current gcode
321 		 * size, then we must increase the size.  This implies reading
322 		 * a new buffer full, too.
323 		 */
324 		if (free_ent > maxcode) {
325 			n_bits++;
326 			if (n_bits == maxbits)	/* Won't get any bigger now. */
327 				maxcode = maxmaxcode;
328 			else
329 				maxcode = MAXCODE(n_bits);
330 		}
331 		if (clear_flg > 0) {
332 			maxcode = MAXCODE(n_bits = INIT_BITS);
333 			clear_flg = 0;
334 		}
335 		size = sfrd(f, gbuf, n_bits, dp);
336 		if (size <= 0)			/* End of file. */
337 			return (-1);
338 		roffset = 0;
339 		/* Round size down to integral number of codes. */
340 		size = (size << 3) - (n_bits - 1);
341 	}
342 	r_off = roffset;
343 	bits = n_bits;
344 
345 	/* Get to the first byte. */
346 	bp += (r_off >> 3);
347 	r_off &= 7;
348 
349 	/* Get first part (low order bits). */
350 	gcode = (*bp++ >> r_off);
351 	bits -= (8 - r_off);
352 	r_off = 8 - r_off;	/* Now, roffset into gcode word. */
353 
354 	/* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
355 	if (bits >= 8) {
356 		gcode |= *bp++ << r_off;
357 		r_off += 8;
358 		bits -= 8;
359 	}
360 
361 	/* High order bits. */
362 	gcode |= (*bp & rmask[bits]) << r_off;
363 	roffset += n_bits;
364 
365 	return (gcode);
366 }
367 
368 static void
cl_hash(State_t * zs,register count_int cl_hsize)369 cl_hash(State_t* zs, register count_int cl_hsize)		/* Reset code table. */
370 {
371 	register count_int *htab_p;
372 	register long i, m1;
373 
374 	m1 = -1;
375 	htab_p = htab + cl_hsize;
376 	i = cl_hsize - 16;
377 	do {			/* Might use Sys V memset(3) here. */
378 		*(htab_p - 16) = m1;
379 		*(htab_p - 15) = m1;
380 		*(htab_p - 14) = m1;
381 		*(htab_p - 13) = m1;
382 		*(htab_p - 12) = m1;
383 		*(htab_p - 11) = m1;
384 		*(htab_p - 10) = m1;
385 		*(htab_p - 9) = m1;
386 		*(htab_p - 8) = m1;
387 		*(htab_p - 7) = m1;
388 		*(htab_p - 6) = m1;
389 		*(htab_p - 5) = m1;
390 		*(htab_p - 4) = m1;
391 		*(htab_p - 3) = m1;
392 		*(htab_p - 2) = m1;
393 		*(htab_p - 1) = m1;
394 		htab_p -= 16;
395 	} while ((i -= 16) >= 0);
396 	for (i += 16; i > 0; i--)
397 		*--htab_p = m1;
398 }
399 
400 static int
cl_block(State_t * zs,Sfio_t * f,Sfdisc_t * dp)401 cl_block(State_t* zs, Sfio_t* f, Sfdisc_t* dp)/* Table clear for block compress. */
402 {
403 	register long rat;
404 
405 	checkpoint = in_count + CHECK_GAP;
406 
407 	if (sync_out == bytes_out)
408 		return(0);
409 	if (in_count > 0x007fffff) {	/* Shift will overflow. */
410 		rat = bytes_out >> 8;
411 		if (rat == 0)		/* Don't divide by zero. */
412 			rat = 0x7fffffff;
413 		else
414 			rat = in_count / rat;
415 	} else
416 		rat = (in_count << 8) / bytes_out;	/* 8 fractional bits. */
417 	if (rat > ratio)
418 		ratio = rat;
419 	else {
420 		ratio = 0;
421 		cl_hash(zs, (count_int) hsize);
422 		free_ent = FIRST;
423 		clear_flg = 1;
424 		if (output(zs, f, (code_int) CLEAR, dp) == -1)
425 			return (-1);
426 	}
427 	sync_out = bytes_out;
428 	return (0);
429 }
430 
431 static int
lzw_ident(Codexmeth_t * meth,const void * head,size_t headsize,char * name,size_t namesize)432 lzw_ident(Codexmeth_t* meth, const void* head, size_t headsize, char* name, size_t namesize)
433 {
434 	unsigned char*	h = (unsigned char*)head;
435 
436 	if (headsize >= 3 && h[0] == MAGIC1 && h[1] == MAGIC2)
437 	{
438 		strncopy(name, meth->name, namesize);
439 		return 1;
440 	}
441 	return 0;
442 }
443 
444 static int
lzw_open(Codex_t * p,char * const args[],Codexnum_t flags)445 lzw_open(Codex_t* p, char* const args[], Codexnum_t flags)
446 {
447 	register State_t*	zs;
448 	const char*		s;
449 	char*			e;
450 
451 	if (!(zs = newof(0, State_t, 1, 0)))
452 	{
453 		if (p->disc->errorf)
454 			(*p->disc->errorf)(NiL, p->disc, 2, "out of space");
455 		return -1;
456 	}
457 	if (!(s = args[2]))
458 		maxbits = BITS;
459 	else if ((maxbits = strton(s, &e, NiL, 0)) < MINBITS || maxbits > MAXBITS || *e)
460 	{
461 		if (p->disc->errorf)
462 			(*p->disc->errorf)(NiL, p->disc, 2, "%s: maximum bits per code must be in [%d..%d]", s, MINBITS, MAXBITS);
463 		return -1;
464 	}
465 	zs->codex = p;
466 	p->data = zs;
467 	return 0;
468 }
469 
470 static int
lzw_init(Codex_t * p)471 lzw_init(Codex_t* p)
472 {
473 	register State_t*	zs = (State_t*)p->data;
474 	u_char			header[HEADER];
475 
476 	hsize = HSIZE;			/* For dynamic table sizing. */
477 	block_compress = BLOCK_MASK;
478 	clear_flg = 0;
479 	ratio = 0;
480 	checkpoint = CHECK_GAP;
481 	in_count = 1;			/* Length of input. */
482 	roffset = 0;
483 	state = S_START;
484 	size = 0;
485 	if (p->flags & CODEX_ENCODE)
486 	{
487 		header[0] = MAGIC1;
488 		header[1] = MAGIC2;
489 		header[2] = ((maxbits) | block_compress) & 0xff;
490 		if (sfwr(p->sp, header, sizeof(header), &p->sfdisc) != sizeof(header))
491 			return -1;
492 		offset = 0;
493 		sync_out = 0;
494 		bytes_out = sizeof(header);
495 		out_count = 0;			/* # of codes output (for debugging). */
496 		hshift = 0;
497 		for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L)
498 			hshift++;
499 		hshift = 8 - hshift;	/* Set hash code range bound. */
500 		hsize_reg = hsize;
501 		cl_hash(zs, (count_int)hsize_reg);	/* Clear hash table. */
502 	}
503 	else
504 	{
505 		/* Check the magic number */
506 		if (sfrd(p->sp, header, sizeof(header), &p->sfdisc) != sizeof(header) ||
507 		    header[0] != MAGIC1 || header[1] != MAGIC2)
508 			return (-1);
509 		maxbits = header[2];	/* Set -b from file. */
510 		block_compress = maxbits & BLOCK_MASK;
511 		maxbits &= BIT_MASK;
512 		if (maxbits > BITS)
513 			return (-1);
514 		/* As above, initialize the first 256 entries in the table. */
515 		for (code = 255; code >= 0; code--) {
516 			tab_prefixof(code) = 0;
517 			tab_suffixof(code) = (char_type) code;
518 		}
519 	}
520 	maxcode = MAXCODE(n_bits = INIT_BITS);
521 	maxmaxcode = 1L << maxbits;
522 	free_ent = block_compress ? FIRST : 256;
523 	return 0;
524 }
525 
526 /*
527  * lzw sync (table flush)
528  */
529 
530 int
lzw_sync(Codex_t * p)531 lzw_sync(Codex_t* p)
532 {
533 	register State_t*	zs = (State_t*)p->data;
534 
535 	if ((zs->codex->flags & CODEX_ENCODE) && cl_block(zs, p->sp, &p->sfdisc))
536 		return -1;
537 	return 0;
538 }
539 
540 /*
541  * lzw done
542  */
543 
544 int
lzw_done(Codex_t * p)545 lzw_done(Codex_t* p)
546 {
547 	register State_t*	zs = (State_t*)p->data;
548 
549 	if (zs->codex->flags & CODEX_ENCODE)
550 	{
551 		if (output(zs, p->sp, (code_int)ent, &p->sfdisc))
552 			return -1;
553 		out_count++;
554 		if (output(zs, p->sp, (code_int)-1, &p->sfdisc))
555 			return -1;
556 	}
557 	return 0;
558 }
559 
560 /*
561  * Decompress read.  This routine adapts to the codes in the file building
562  * the "string" table on-the-fly; requiring no table to be stored in the
563  * compressed file.  The tables used herein are shared with those of the
564  * compress() routine.  See the definitions above.
565  */
566 static ssize_t
lzw_read(Sfio_t * f,Void_t * rbp,size_t num,Sfdisc_t * dp)567 lzw_read(Sfio_t* f, Void_t* rbp, size_t num, Sfdisc_t* dp)
568 {
569 	State_t *zs = (State_t*)CODEX(dp)->data;
570 	register u_int count;
571 	u_char *bp;
572 
573 	if (num == 0)
574 		return (0);
575 
576 	count = num;
577 	bp = (u_char *)rbp;
578 	switch (state) {
579 	case S_START:
580 		state = S_MIDDLE;
581 		break;
582 	case S_MIDDLE:
583 		goto middle;
584 	case S_EOF:
585 		goto eof;
586 	}
587 
588 
589 	finchar = oldcode = getcode(zs, f, dp);
590 	if (oldcode == -1)	/* EOF already? */
591 		return (0);	/* Get out of here */
592 
593 	/* First code must be 8 bits = char. */
594 	*bp++ = (u_char)finchar;
595 	count--;
596 	stackp = de_stack;
597 
598 	while ((code = getcode(zs, f, dp)) > -1) {
599 
600 		if ((code == CLEAR) && block_compress) {
601 			for (code = 255; code >= 0; code--)
602 				tab_prefixof(code) = 0;
603 			clear_flg = 1;
604 			free_ent = FIRST - 1;
605 			if ((code = getcode(zs, f, dp)) == -1)	/* O, untimely death! */
606 				break;
607 		}
608 		incode = code;
609 
610 		/* Special case for KwKwK string. */
611 		if (code >= free_ent) {
612 			*stackp++ = finchar;
613 			code = oldcode;
614 		}
615 
616 		/* Generate output characters in reverse order. */
617 		while (code >= 256) {
618 			*stackp++ = tab_suffixof(code);
619 			code = tab_prefixof(code);
620 		}
621 		*stackp++ = finchar = tab_suffixof(code);
622 
623 		/* And put them out in forward order.  */
624 middle:		do {
625 			if (count-- == 0)
626 				return (num);
627 			*bp++ = *--stackp;
628 		} while (stackp > de_stack);
629 
630 		/* Generate the new entry. */
631 		if ((code = free_ent) < maxmaxcode) {
632 			tab_prefixof(code) = (u_short) oldcode;
633 			tab_suffixof(code) = finchar;
634 			free_ent = code + 1;
635 		}
636 
637 		/* Remember previous code. */
638 		oldcode = incode;
639 	}
640 	state = S_EOF;
641 eof:	return (num - count);
642 }
643 
644 /*-
645  * compress write
646  *
647  * Algorithm:  use open addressing double hashing (no chaining) on the
648  * prefix code / next character combination.  We do a variant of Knuth's
649  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
650  * secondary probe.  Here, the modular division first probe is gives way
651  * to a faster exclusive-or manipulation.  Also do block compression with
652  * an adaptive reset, whereby the code table is cleared when the compression
653  * ratio decreases, but after the table fills.  The variable-length output
654  * codes are re-sized at this point, and a special CLEAR code is generated
655  * for the decompressor.  Late addition:  construct the table according to
656  * file size for noticeable speed improvement on small files.  Please direct
657  * questions about this implementation to ames!jaw.
658  */
659 
660 static ssize_t
lzw_write(Sfio_t * f,const Void_t * wbp,size_t num,Sfdisc_t * dp)661 lzw_write(Sfio_t* f, const Void_t* wbp, size_t num, Sfdisc_t* dp)
662 {
663 	State_t *zs = (State_t*)CODEX(dp)->data;
664 	register code_int i;
665 	register int c, disp;
666 	const u_char *bp;
667 	int count;
668 
669 	if (num == 0)
670 		return (0);
671 
672 	count = num;
673 	bp = (u_char *)wbp;
674 	if (state == S_START)
675 	{
676 		state = S_MIDDLE;
677 		ent = *bp++;
678 		count--;
679 	}
680 	for (i = 0; count--;) {
681 		c = *bp++;
682 		in_count++;
683 		fcode = (long)(((long)c << maxbits) + ent);
684 		i = ((c << hshift) ^ ent);	/* Xor hashing. */
685 
686 		if (htabof(i) == fcode) {
687 			ent = codetabof(i);
688 			continue;
689 		} else if ((long)htabof(i) < 0)	/* Empty slot. */
690 			goto nomatch;
691 		disp = hsize_reg - i;	/* Secondary hash (after G. Knott). */
692 		if (i == 0)
693 			disp = 1;
694 probe:		if ((i -= disp) < 0)
695 			i += hsize_reg;
696 
697 		if (htabof(i) == fcode) {
698 			ent = codetabof(i);
699 			continue;
700 		}
701 		if ((long)htabof(i) >= 0)
702 			goto probe;
703 nomatch:	if (output(zs, f, (code_int) ent, dp) == -1)
704 			return (-1);
705 		out_count++;
706 		ent = c;
707 		if (free_ent < maxmaxcode) {
708 			codetabof(i) = free_ent++;	/* code -> hashtable */
709 			htabof(i) = fcode;
710 		} else if ((count_int)in_count >=
711 		    checkpoint && block_compress) {
712 			if (cl_block(zs, f, dp) == -1)
713 				return (-1);
714 		}
715 	}
716 	return (num);
717 }
718 
719 Codexmeth_t	codex_compress =
720 {
721 	"compress",
722 	"compress LZW compression. The first parameter is the maximum number"
723 	" of bits per code { 9 - 16 }. The default is 16.",
724 	0,
725 	CODEX_DECODE|CODEX_ENCODE|CODEX_COMPRESS,
726 	0,
727 	lzw_ident,
728 	lzw_open,
729 	0,
730 	lzw_init,
731 	lzw_done,
732 	lzw_read,
733 	lzw_write,
734 	lzw_sync,
735 	0,
736 	0,
737 	0,
738 	0,
739 	CODEXNEXT(compress)
740 };
741 
742 CODEXLIB(compress)
743