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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
|
/*
* compressor.cpp
*
* Created on: 23.03.2013
* Author: bju
*/
#include "compressor.h"
#include <zlib.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#define CHUNK 16384
cCompressor::cCompressor() {
size = 0;
data = NULL;
}
cCompressor::~cCompressor() {
}
bool cCompressor::CompressGzip(string text) {
int in_fd[2];
if (pipe(in_fd) < 0) {
return false;
}
int out_fd[2];
if (pipe(out_fd) < 0) {
return false;
}
int pid = fork();
if (pid < 0) {
return false;
}
if (pid == 0) {
// child
close(in_fd[1]);
close(out_fd[0]);
dup2(in_fd[0], 0);
dup2(out_fd[1], 1);
execlp("gzip", "gzip", "-c", "-9", NULL);
exit(-1);
} else {
// parent
close(in_fd[0]);
close(out_fd[1]);
write(in_fd[1], text.c_str(), text.length());
close(in_fd[1]);
char buf[32*1024];
for(;;) {
int count = read(out_fd[0], buf, sizeof(buf));
if (count < 0) {
close(out_fd[0]);
return false;
}
if (count == 0)
break;
char * newdata = (char *)malloc(size + count);
if (data != NULL) {
memcpy(newdata, data, size);
}
memcpy(newdata + size, buf, count);
if (data != NULL) {
free(data);
}
data = newdata;
size += count;
}
close(out_fd[0]);
}
return true;
}
bool cCompressor::CompressZlib(string text) {
int ret, flush;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
int level = 9;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, level);
if (ret != Z_OK)
return false;
string input = text;
uInt len;
do {
len = input.length();
if (len > CHUNK) {
len = CHUNK;
}
flush = len > 0 ? Z_NO_FLUSH : Z_FINISH;
strm.avail_in = len;
strm.next_in = (unsigned char *)input.c_str();
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush);
if (ret < 0) {
if (data != NULL) {
free(data);
}
return false;
}
have = CHUNK - strm.avail_out;
char * newdata = (char *)malloc(size + have);
if (data != NULL) {
memcpy(newdata, data, size);
}
memcpy(newdata + size, out, have);
if (data != NULL) {
free(data);
}
data = newdata;
size += have;
} while (strm.avail_out == 0);
input = input.substr(len);
} while (flush != Z_FINISH);
// clean up and return
(void)deflateEnd(&strm);
return true;
}
char * cCompressor::GetData() {
return data;
}
size_t cCompressor::getDataSize() {
return size;
}
|