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/*
28 * We keep our own copy of this algorithm for 2 main reasons:
29 * 	1. If we didn't, anyone modifying common/os/compress.c would
30 *         directly break our on disk format
31 * 	2. Our version of lzjb does not have a number of checks that the
32 *         common/os version needs and uses
33 * In particular, we are adding the "feature" that compress() can
34 * take a destination buffer size and return -1 if the data will not
35 * compress to d_len or less.
36 */
37
38#define	MATCH_BITS	6
39#define	MATCH_MIN	3
40#define	MATCH_MAX	((1 << MATCH_BITS) + (MATCH_MIN - 1))
41#define	OFFSET_MASK	((1 << (16 - MATCH_BITS)) - 1)
42#define	LEMPEL_SIZE	256
43
44/*ARGSUSED*/
45static int
46lzjb_decompress(void *s_start, void *d_start, size_t s_len __unused,
47    size_t d_len, int n __unused)
48{
49	unsigned char *src = s_start;
50	unsigned char *dst = d_start;
51	unsigned char *d_end = (unsigned char *)d_start + d_len;
52	unsigned char *cpy, copymap = 0;
53	int copymask = 1 << (NBBY - 1);
54
55	while (dst < d_end) {
56		if ((copymask <<= 1) == (1 << NBBY)) {
57			copymask = 1;
58			copymap = *src++;
59		}
60		if (copymap & copymask) {
61			int mlen = (src[0] >> (NBBY - MATCH_BITS)) + MATCH_MIN;
62			int offset = ((src[0] << NBBY) | src[1]) & OFFSET_MASK;
63			src += 2;
64			if ((cpy = dst - offset) < (unsigned char *)d_start)
65				return (-1);
66			while (--mlen >= 0 && dst < d_end)
67				*dst++ = *cpy++;
68		} else {
69			*dst++ = *src++;
70		}
71	}
72	return (0);
73}
74