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