3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "serialization.h"
22 #include "util/serialize.h"
27 /* report a zlib or i/o error */
28 static void zerr(int ret)
34 dstream<<"error reading stdin"<<std::endl;
36 dstream<<"error writing stdout"<<std::endl;
39 dstream<<"invalid compression level"<<std::endl;
42 dstream<<"invalid or incomplete deflate data"<<std::endl;
45 dstream<<"out of memory"<<std::endl;
48 dstream<<"zlib version mismatch!"<<std::endl;
51 dstream<<"return value = "<<ret<<std::endl;
55 // Make sure that z is deleted in case of exception
56 template <int (*F)(z_stream*)>
57 class ZlibAutoDeleter {
59 ZlibAutoDeleter(z_stream *ptr) : ptr_(ptr) {}
60 ~ZlibAutoDeleter() { F(ptr_); }
66 void compressZlib(const u8 *data, size_t data_size, std::ostream &os, int level)
69 const s32 bufsize = 16384;
70 char output_buffer[bufsize];
78 ret = deflateInit(&z, level);
80 throw SerializationError("compressZlib: deflateInit failed");
82 ZlibAutoDeleter<deflateEnd> deleter(&z);
84 // Point zlib to our input buffer
85 z.next_in = (Bytef*)&data[0];
86 z.avail_in = data_size;
90 z.next_out = (Bytef*)output_buffer;
91 z.avail_out = bufsize;
93 status = deflate(&z, Z_FINISH);
94 if(status == Z_NEED_DICT || status == Z_DATA_ERROR
95 || status == Z_MEM_ERROR)
98 throw SerializationError("compressZlib: deflate failed");
100 int count = bufsize - z.avail_out;
102 os.write(output_buffer, count);
103 // This determines zlib has given all output
104 if(status == Z_STREAM_END)
109 void compressZlib(const std::string &data, std::ostream &os, int level)
111 compressZlib((u8*)data.c_str(), data.size(), os, level);
114 void decompressZlib(std::istream &is, std::ostream &os, size_t limit)
117 const s32 bufsize = 16384;
118 char input_buffer[bufsize];
119 char output_buffer[bufsize];
122 int bytes_written = 0;
123 int input_buffer_len = 0;
129 ret = inflateInit(&z);
131 throw SerializationError("dcompressZlib: inflateInit failed");
133 ZlibAutoDeleter<inflateEnd> deleter(&z);
139 int output_size = bufsize;
140 z.next_out = (Bytef*)output_buffer;
141 z.avail_out = output_size;
144 int limit_remaining = limit - bytes_written;
145 if (limit_remaining <= 0) {
146 // we're aborting ahead of time - throw an error?
149 if (limit_remaining < output_size) {
150 z.avail_out = output_size = limit_remaining;
156 z.next_in = (Bytef*)input_buffer;
157 is.read(input_buffer, bufsize);
158 input_buffer_len = is.gcount();
159 z.avail_in = input_buffer_len;
166 status = inflate(&z, Z_NO_FLUSH);
168 if(status == Z_NEED_DICT || status == Z_DATA_ERROR
169 || status == Z_MEM_ERROR)
172 throw SerializationError("decompressZlib: inflate failed");
174 int count = output_size - z.avail_out;
176 os.write(output_buffer, count);
177 bytes_written += count;
178 if(status == Z_STREAM_END)
180 // Unget all the data that inflate didn't take
181 is.clear(); // Just in case EOF is set
182 for(u32 i=0; i < z.avail_in; i++)
185 if(is.fail() || is.bad())
187 dstream<<"unget #"<<i<<" failed"<<std::endl;
188 dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
189 throw SerializationError("decompressZlib: unget failed");
198 struct ZSTD_Deleter {
199 void operator() (ZSTD_CStream* cstream) {
200 ZSTD_freeCStream(cstream);
203 void operator() (ZSTD_DStream* dstream) {
204 ZSTD_freeDStream(dstream);
208 void compressZstd(const u8 *data, size_t data_size, std::ostream &os, int level)
210 // reusing the context is recommended for performance
211 // it will be destroyed when the thread ends
212 thread_local std::unique_ptr<ZSTD_CStream, ZSTD_Deleter> stream(ZSTD_createCStream());
215 ZSTD_initCStream(stream.get(), level);
217 const size_t bufsize = 16384;
218 char output_buffer[bufsize];
220 ZSTD_inBuffer input = { data, data_size, 0 };
221 ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
223 while (input.pos < input.size) {
224 size_t ret = ZSTD_compressStream(stream.get(), &output, &input);
225 if (ZSTD_isError(ret)) {
226 dstream << ZSTD_getErrorName(ret) << std::endl;
227 throw SerializationError("compressZstd: failed");
230 os.write(output_buffer, output.pos);
237 ret = ZSTD_endStream(stream.get(), &output);
238 if (ZSTD_isError(ret)) {
239 dstream << ZSTD_getErrorName(ret) << std::endl;
240 throw SerializationError("compressZstd: failed");
243 os.write(output_buffer, output.pos);
250 void compressZstd(const std::string &data, std::ostream &os, int level)
252 compressZstd((u8*)data.c_str(), data.size(), os, level);
255 void decompressZstd(std::istream &is, std::ostream &os)
257 // reusing the context is recommended for performance
258 // it will be destroyed when the thread ends
259 thread_local std::unique_ptr<ZSTD_DStream, ZSTD_Deleter> stream(ZSTD_createDStream());
261 ZSTD_initDStream(stream.get());
263 const size_t bufsize = 16384;
264 char output_buffer[bufsize];
265 char input_buffer[bufsize];
267 ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
268 ZSTD_inBuffer input = { input_buffer, 0, 0 };
272 if (input.size == input.pos) {
273 is.read(input_buffer, bufsize);
274 input.size = is.gcount();
278 ret = ZSTD_decompressStream(stream.get(), &output, &input);
279 if (ZSTD_isError(ret)) {
280 dstream << ZSTD_getErrorName(ret) << std::endl;
281 throw SerializationError("decompressZstd: failed");
284 os.write(output_buffer, output.pos);
289 // Unget all the data that ZSTD_decompressStream didn't take
290 is.clear(); // Just in case EOF is set
291 for (u32 i = 0; i < input.size - input.pos; i++) {
293 if (is.fail() || is.bad())
294 throw SerializationError("decompressZstd: unget failed");
298 void compress(u8 *data, u32 size, std::ostream &os, u8 version, int level)
302 // map the zlib levels [0,9] to [1,10]. -1 becomes 0 which indicates the default (currently 3)
303 compressZstd(data, size, os, level + 1);
309 compressZlib(data, size, os, level);
316 // Write length (u32)
320 os.write((char*)tmp, 4);
322 // We will be writing 8-bit pairs of more_count and byte
324 u8 current_byte = data[0];
325 for(u32 i=1; i<size; i++)
328 data[i] != current_byte
332 // write count and byte
333 os.write((char*)&more_count, 1);
334 os.write((char*)¤t_byte, 1);
336 current_byte = data[i];
343 // write count and byte
344 os.write((char*)&more_count, 1);
345 os.write((char*)¤t_byte, 1);
348 void compress(const SharedBuffer<u8> &data, std::ostream &os, u8 version, int level)
350 compress(*data, data.getSize(), os, version, level);
353 void compress(const std::string &data, std::ostream &os, u8 version, int level)
355 compress((u8*)data.c_str(), data.size(), os, version, level);
358 void decompress(std::istream &is, std::ostream &os, u8 version)
362 decompressZstd(is, os);
368 decompressZlib(is, os);
375 is.read((char*)tmp, 4);
376 u32 len = readU32(tmp);
378 // We will be reading 8-bit pairs of more_count and byte
385 is.read((char*)&more_count, 1);
387 is.read((char*)&byte, 1);
390 throw SerializationError("decompress: stream ended halfway");
392 for(s32 i=0; i<(u16)more_count+1; i++)
393 os.write((char*)&byte, 1);
395 count += (u16)more_count+1;