added config
[nao-ulib.git] / src / deflate.c
blob11d293f5bbd7a8d80503ce856b336292692e24d8
1 /*
2 * nao-ulib
3 * Copyright 2009 Daniel Borkmann <dborkma@tik.ee.ethz.ch>
4 * Subject to the GPL.
5 * Nao-Team HTWK,
6 * Faculty of Computer Science, Mathematics and Natural Sciences,
7 * Leipzig University of Applied Sciences (HTWK Leipzig)
8 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <errno.h>
14 #include "deflate.h"
15 #include "xmalloc.h"
16 #include "zlib.h"
17 #include "die.h"
19 /* Not thread safe! */
20 static z_stream inf, def;
22 /* Maximum of a jumbo frame and some overhead */
23 static unsigned char *z_buf = NULL;
24 static int z_buf_size = 9200;
26 int z_alloc_or_maybe_die(int z_level)
28 int ret;
30 /* Usually can be Z_DEFAULT_COMPRESSION */
31 if (z_level < -1 || z_level > 9)
32 return -EINVAL;
34 def.zalloc = Z_NULL;
35 def.zfree = Z_NULL;
36 def.opaque = Z_NULL;
38 inf.zalloc = Z_NULL;
39 inf.zfree = Z_NULL;
40 inf.opaque = Z_NULL;
42 ret = deflateInit(&def, z_level);
43 if (ret != Z_OK)
44 panic("Can't initialize zLibs compressor!\n");
46 ret = inflateInit(&inf);
47 if (ret != Z_OK)
48 panic("Can't initialize zLibs decompressor!\n");
50 z_buf = xmalloc(z_buf_size);
52 return 0;
55 void z_free(void)
57 deflateEnd(&def);
58 inflateEnd(&inf);
60 xfree(z_buf);
63 char *z_get_version(void)
65 return ZLIB_VERSION;
68 static void z_buf_expansion_or_die(z_stream *stream, size_t size)
70 z_buf = xrealloc(z_buf, 1, z_buf_size + size);
72 stream->next_out = z_buf + z_buf_size;
73 stream->avail_out = size;
75 z_buf_size += size;
78 ssize_t z_deflate(char *src, size_t size, char **dst)
80 int ret;
81 size_t todo, done = 0;
83 def.next_in = (void *) src;
84 def.avail_in = size;
85 def.next_out = (void *) z_buf;
86 def.avail_out = z_buf_size;
88 for (;;) {
89 todo = def.avail_out;
91 ret = deflate(&def, Z_SYNC_FLUSH);
92 if (ret != Z_OK) {
93 whine("Deflate error %d!\n", ret);
94 return -EIO;
97 done += (todo - def.avail_out);
98 if (def.avail_in == 0)
99 break;
101 z_buf_expansion_or_die(&def, 100);
104 *dst = (void *) z_buf;
105 return done;
108 ssize_t z_inflate(char *src, size_t size, char **dst)
110 int ret;
111 int todo, done = 0;
113 inf.next_in = (void *) src;
114 inf.avail_in = size;
115 inf.next_out = (void *) z_buf;
116 inf.avail_out = z_buf_size;
118 for (;;) {
119 todo = inf.avail_out;
121 ret = inflate(&inf, Z_SYNC_FLUSH);
122 if (ret != Z_OK) {
123 whine("Inflate error %d!\n", ret);
124 return -EIO;
127 done += (todo - inf.avail_out);
128 if (inf.avail_in == 0)
129 break;
131 z_buf_expansion_or_die(&inf, 100);
134 *dst = (void *) z_buf;
135 return done;