1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24 * Use is subject to license terms.
25 */
26
27/*#pragma ident	"%Z%%M%	%I%	%E% SMI"*/
28
29/*
30 * We keep our own copy of this algorithm for 2 main reasons:
31 * 	1. If we didn't, anyone modifying common/os/compress.c would
32 *         directly break our on disk format
33 * 	2. Our version of lzjb does not have a number of checks that the
34 *         common/os version needs and uses
35 * In particular, we are adding the "feature" that compress() can
36 * take a destination buffer size and return -1 if the data will not
37 * compress to d_len or less.
38 */
39
40#define	MATCH_BITS	6
41#define	MATCH_MIN	3
42#define	MATCH_MAX	((1 << MATCH_BITS) + (MATCH_MIN - 1))
43#define	OFFSET_MASK	((1 << (16 - MATCH_BITS)) - 1)
44#define	LEMPEL_SIZE	256
45
46/*ARGSUSED*/
47static int
48lzjb_decompress(void *s_start, void *d_start, size_t s_len, size_t d_len, int n)
49{
50	unsigned char *src = s_start;
51	unsigned char *dst = d_start;
52	unsigned char *d_end = (unsigned char *)d_start + d_len;
53	unsigned char *cpy, copymap = 0;
54	int copymask = 1 << (NBBY - 1);
55
56	while (dst < d_end) {
57		if ((copymask <<= 1) == (1 << NBBY)) {
58			copymask = 1;
59			copymap = *src++;
60		}
61		if (copymap & copymask) {
62			int mlen = (src[0] >> (NBBY - MATCH_BITS)) + MATCH_MIN;
63			int offset = ((src[0] << NBBY) | src[1]) & OFFSET_MASK;
64			src += 2;
65			if ((cpy = dst - offset) < (unsigned char *)d_start)
66				return (-1);
67			while (--mlen >= 0 && dst < d_end)
68				*dst++ = *cpy++;
69		} else {
70			*dst++ = *src++;
71		}
72	}
73	return (0);
74}
75