summaryrefslogtreecommitdiffstats
path: root/src/compression.c
blob: 4c7db813ee9c7c428133ac7d9ee21e5307092d8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * Copyright (C) 2013  Patrick "P. J." McDermott
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <config.h>
#include "compression.h"
#include "logging.h"

static void
zlib_err(int status)
{
	switch (status) {
		case Z_OK:
		case Z_STREAM_END:
			break;
		case Z_MEM_ERROR:
			err(1, "zlib error: out of memory");
			break;
		case Z_VERSION_ERROR:
			err(1, "zlib error: incompatible library version");
			break;
		case Z_STREAM_ERROR:
			err(1, "zlib error: invalid stream");
			break;
		case Z_NEED_DICT:
			err(1, "zlib error: need dictionary");
			break;
		case Z_DATA_ERROR:
			err(1, "zlib error: corrupted data");
			break;
		case Z_BUF_ERROR:
			err(1, "zlib error: buffer error");
			break;
		default:
			err(1, "zlib error: unknown");
			break;
	}
}

void
decompress(char *src, size_t src_len, char *dest, size_t dest_len)
{
	z_stream d_stream;

	d_stream.zalloc = Z_NULL;
	d_stream.zfree = Z_NULL;
	d_stream.opaque = Z_NULL;
	d_stream.next_in = (Bytef *) src;
	d_stream.avail_in = src_len;
	d_stream.next_out = (Bytef *) dest;
	d_stream.avail_out = dest_len;

#ifdef DEBUG_COMPRESSION
	debug("Initializing inflation stream...");
#endif
	zlib_err(inflateInit2(&d_stream, 15 + 32));

#ifdef DEBUG_COMPRESSION
	debug("Inflating %d bytes into up to %d bytes...", src_len, dest_len);
#endif
	zlib_err(inflate(&d_stream, Z_NO_FLUSH));

#ifdef DEBUG_COMPRESSION
	debug("Ending inflation stream...");
#endif
	zlib_err(inflateEnd(&d_stream));
}