lzo_wrapper.c revision 2b5136104fc18d420bfbb5b2f9fe9cb4da952848
1/*
2 * Copyright (c) 2010 LG Electronics
3 * Chan Jeong <chan.jeong@lge.com>
4 *
5 * All modifications Copyright (c) 2010
6 * Phillip Lougher <phillip@lougher.demon.co.uk>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2,
11 * or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 *
22 * lzo_wrapper.c
23 */
24
25#include <stdlib.h>
26#include <string.h>
27
28#include <lzo/lzoconf.h>
29#include <lzo/lzo1x.h>
30
31#include "squashfs_fs.h"
32#include "compressor.h"
33
34/* worst-case expansion calculation during compression,
35   see LZO FAQ for more information */
36#define LZO_OUTPUT_BUFFER_SIZE(size)	(size + (size/16) + 64 + 3)
37
38struct lzo_stream {
39	lzo_voidp wrkmem;
40	lzo_bytep out;
41};
42
43static int lzo_compress(void **strm, void *d, void *s, int size, int block_size,
44		int *error)
45{
46	int res = 0;
47	lzo_uint outlen;
48	struct lzo_stream *stream = *strm;
49
50	if(stream == NULL) {
51		if((stream = *strm = malloc(sizeof(struct lzo_stream))) == NULL)
52			goto failed;
53		/* work memory for compression */
54		if((stream->wrkmem = malloc(LZO1X_999_MEM_COMPRESS)) == NULL)
55			goto failed;
56		/* temporal output buffer */
57		if((stream->out = malloc(LZO_OUTPUT_BUFFER_SIZE(block_size))) == NULL)
58			goto failed;
59	}
60
61	res = lzo1x_999_compress(s, size, stream->out, &outlen, stream->wrkmem);
62	if(res != LZO_E_OK)
63		goto failed;
64	if(outlen >= size)
65		/*
66		 * Output buffer overflow. Return out of buffer space
67		 */
68		return 0;
69
70	/*
71	 * Success, return the compressed size.
72	 */
73	memcpy(d, stream->out, outlen);
74	return outlen;
75
76failed:
77	/*
78	 * All other errors return failure, with the compressor
79	 * specific error code in *error
80	 */
81	*error = res;
82	return -1;
83}
84
85
86static int lzo_uncompress(void *d, void *s, int size, int block_size, int *error)
87{
88	int res;
89	lzo_uint bytes = block_size;
90
91	res = lzo1x_decompress_safe(s, size, d, &bytes, NULL);
92
93	*error = res;
94	return res == LZO_E_OK ? bytes : -1;
95}
96
97
98struct compressor lzo_comp_ops = {
99	.compress = lzo_compress,
100	.uncompress = lzo_uncompress,
101	.options = NULL,
102	.id = LZO_COMPRESSION,
103	.name = "lzo",
104	.supported = 1
105};
106
107