xref: /freebsd/sys/contrib/openzfs/module/zfs/zle.c (revision 02e9120893770924227138ba49df1edb3896112a)
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 https://opensource.org/licenses/CDDL-1.0.
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Zero-length encoding.  This is a fast and simple algorithm to eliminate
29  * runs of zeroes.  Each chunk of compressed data begins with a length byte, b.
30  * If b < n (where n is the compression parameter) then the next b + 1 bytes
31  * are literal values.  If b >= n then the next (256 - b + 1) bytes are zero.
32  */
33 #include <sys/types.h>
34 #include <sys/sysmacros.h>
35 #include <sys/zio_compress.h>
36 
37 size_t
38 zle_compress(void *s_start, void *d_start, size_t s_len, size_t d_len, int n)
39 {
40 	uchar_t *src = s_start;
41 	uchar_t *dst = d_start;
42 	uchar_t *s_end = src + s_len;
43 	uchar_t *d_end = dst + d_len;
44 
45 	while (src < s_end && dst < d_end - 1) {
46 		uchar_t *first = src;
47 		uchar_t *len = dst++;
48 		if (src[0] == 0) {
49 			uchar_t *last = src + (256 - n);
50 			while (src < MIN(last, s_end) && src[0] == 0)
51 				src++;
52 			*len = src - first - 1 + n;
53 		} else {
54 			uchar_t *last = src + n;
55 			if (d_end - dst < n)
56 				break;
57 			while (src < MIN(last, s_end) - 1 && (src[0] | src[1]))
58 				*dst++ = *src++;
59 			if (src[0])
60 				*dst++ = *src++;
61 			*len = src - first - 1;
62 		}
63 	}
64 	return (src == s_end ? dst - (uchar_t *)d_start : s_len);
65 }
66 
67 int
68 zle_decompress(void *s_start, void *d_start, size_t s_len, size_t d_len, int n)
69 {
70 	uchar_t *src = s_start;
71 	uchar_t *dst = d_start;
72 	uchar_t *s_end = src + s_len;
73 	uchar_t *d_end = dst + d_len;
74 
75 	while (src < s_end && dst < d_end) {
76 		int len = 1 + *src++;
77 		if (len <= n) {
78 			if (src + len > s_end || dst + len > d_end)
79 				return (-1);
80 			while (len-- != 0)
81 				*dst++ = *src++;
82 		} else {
83 			len -= n;
84 			if (dst + len > d_end)
85 				return (-1);
86 			while (len-- != 0)
87 				*dst++ = 0;
88 		}
89 	}
90 	return (dst == d_end ? 0 : -1);
91 }
92