1 #include <cmajor/rt/ZlibInterface.h>
2 #include <cmajor/system/ext/zlib-1.2.11/zlib.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <stdlib.h>
6
7 #define COMPRESS 0
8 #define DECOMPRESS 1
9
10 int32_t zlib_init(int32_t mode, int32_t level, void** handle)
11 {
12 int32_t ret = Z_OK;
13 if (!handle)
14 {
15 ret = Z_MEM_ERROR;
16 }
17 else
18 {
19 z_stream* strm = (z_stream*)malloc(sizeof(z_stream));
20 switch (mode)
21 {
22 case 0:
23 {
24 strm->zalloc = Z_NULL;
25 strm->zfree = Z_NULL;
26 strm->opaque = Z_NULL;
27 ret = deflateInit(strm, level);
28 break;
29 }
30 case 1:
31 {
32 strm->zalloc = Z_NULL;
33 strm->zfree = Z_NULL;
34 strm->opaque = Z_NULL;
35 strm->avail_in = 0;
36 strm->next_in = Z_NULL;
37 ret = inflateInit(strm);
38 break;
39 }
40 }
41 if (ret != Z_OK)
42 {
43 free(strm);
44 *handle = NULL;
45 }
46 else
47 {
48 *handle = strm;
49 }
50 }
51 return ret;
52 }
53
54 void zlib_done(int32_t mode, void* handle)
55 {
56 z_stream* strm = (z_stream*)handle;
57 switch (mode)
58 {
59 case 0:
60 {
61 deflateEnd(strm);
62 break;
63 }
64 case 1:
65 {
66 inflateEnd(strm);
67 break;
68 }
69 }
70 free(strm);
71 }
72
73 void zlib_set_input(void* inChunk, uint32_t inAvail, void* handle)
74 {
75 z_stream* strm = (z_stream*)handle;
76 strm->next_in = inChunk;
77 strm->avail_in = inAvail;
78 }
79
80 int32_t zlib_deflate(void* outChunk, uint32_t outChunkSize, uint32_t* have, uint32_t* outAvail, void* handle, int32_t flush)
81 {
82 z_stream* strm = (z_stream*)handle;
83 strm->next_out = outChunk;
84 strm->avail_out = outChunkSize;
85 int ret = deflate(strm, flush);
86 *have = outChunkSize - strm->avail_out;
87 *outAvail = strm->avail_out;
88 return ret;
89 }
90
91 int32_t zlib_inflate(void* outChunk, uint32_t outChunkSize, uint32_t* have, uint32_t* outAvail, uint32_t* inAvail, void* handle)
92 {
93 z_stream* strm = (z_stream*)handle;
94 strm->next_out = outChunk;
95 strm->avail_out = outChunkSize;
96 int ret = inflate(strm, Z_NO_FLUSH);
97 *have = outChunkSize - strm->avail_out;
98 *outAvail = strm->avail_out;
99 *inAvail = strm->avail_in;
100 return ret;
101 }
102
103 const char* zlib_retval_str(int32_t retVal)
104 {
105 switch (retVal)
106 {
107 case Z_OK: return "Z_OK";
108 case Z_STREAM_END: return "Z_STREAM_END";
109 case Z_NEED_DICT: return "Z_NEED_DICT";
110 case Z_ERRNO: return strerror(errno);
111 case Z_STREAM_ERROR: return "Z_STREAM_ERROR";
112 case Z_DATA_ERROR: return "Z_DATA_ERROR";
113 case Z_MEM_ERROR: return "Z_MEM_ERROR";
114 case Z_BUF_ERROR: return "Z_BUF_ERROR";
115 case Z_VERSION_ERROR: return "Z_VERSION_ERROR";
116 }
117 return "";
118 }