serialization.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "serialization.h"
  17. #include "util/serialize.h"
  18. #include <zlib.h>
  19. #include <zstd.h>
  20. /* report a zlib or i/o error */
  21. void zerr(int ret)
  22. {
  23. dstream<<"zerr: ";
  24. switch (ret) {
  25. case Z_ERRNO:
  26. if (ferror(stdin))
  27. dstream<<"error reading stdin"<<std::endl;
  28. if (ferror(stdout))
  29. dstream<<"error writing stdout"<<std::endl;
  30. break;
  31. case Z_STREAM_ERROR:
  32. dstream<<"invalid compression level"<<std::endl;
  33. break;
  34. case Z_DATA_ERROR:
  35. dstream<<"invalid or incomplete deflate data"<<std::endl;
  36. break;
  37. case Z_MEM_ERROR:
  38. dstream<<"out of memory"<<std::endl;
  39. break;
  40. case Z_VERSION_ERROR:
  41. dstream<<"zlib version mismatch!"<<std::endl;
  42. break;
  43. default:
  44. dstream<<"return value = "<<ret<<std::endl;
  45. }
  46. }
  47. void compressZlib(const u8 *data, size_t data_size, std::ostream &os, int level)
  48. {
  49. z_stream z;
  50. const s32 bufsize = 16384;
  51. char output_buffer[bufsize];
  52. int status = 0;
  53. int ret;
  54. z.zalloc = Z_NULL;
  55. z.zfree = Z_NULL;
  56. z.opaque = Z_NULL;
  57. ret = deflateInit(&z, level);
  58. if(ret != Z_OK)
  59. throw SerializationError("compressZlib: deflateInit failed");
  60. // Point zlib to our input buffer
  61. z.next_in = (Bytef*)&data[0];
  62. z.avail_in = data_size;
  63. // And get all output
  64. for(;;)
  65. {
  66. z.next_out = (Bytef*)output_buffer;
  67. z.avail_out = bufsize;
  68. status = deflate(&z, Z_FINISH);
  69. if(status == Z_NEED_DICT || status == Z_DATA_ERROR
  70. || status == Z_MEM_ERROR)
  71. {
  72. zerr(status);
  73. throw SerializationError("compressZlib: deflate failed");
  74. }
  75. int count = bufsize - z.avail_out;
  76. if(count)
  77. os.write(output_buffer, count);
  78. // This determines zlib has given all output
  79. if(status == Z_STREAM_END)
  80. break;
  81. }
  82. deflateEnd(&z);
  83. }
  84. void compressZlib(const std::string &data, std::ostream &os, int level)
  85. {
  86. compressZlib((u8*)data.c_str(), data.size(), os, level);
  87. }
  88. void decompressZlib(std::istream &is, std::ostream &os, size_t limit)
  89. {
  90. z_stream z;
  91. const s32 bufsize = 16384;
  92. char input_buffer[bufsize];
  93. char output_buffer[bufsize];
  94. int status = 0;
  95. int ret;
  96. int bytes_written = 0;
  97. int input_buffer_len = 0;
  98. z.zalloc = Z_NULL;
  99. z.zfree = Z_NULL;
  100. z.opaque = Z_NULL;
  101. ret = inflateInit(&z);
  102. if(ret != Z_OK)
  103. throw SerializationError("dcompressZlib: inflateInit failed");
  104. z.avail_in = 0;
  105. for(;;)
  106. {
  107. int output_size = bufsize;
  108. z.next_out = (Bytef*)output_buffer;
  109. z.avail_out = output_size;
  110. if (limit) {
  111. int limit_remaining = limit - bytes_written;
  112. if (limit_remaining <= 0) {
  113. // we're aborting ahead of time - throw an error?
  114. break;
  115. }
  116. if (limit_remaining < output_size) {
  117. z.avail_out = output_size = limit_remaining;
  118. }
  119. }
  120. if(z.avail_in == 0)
  121. {
  122. z.next_in = (Bytef*)input_buffer;
  123. is.read(input_buffer, bufsize);
  124. input_buffer_len = is.gcount();
  125. z.avail_in = input_buffer_len;
  126. }
  127. if(z.avail_in == 0)
  128. {
  129. break;
  130. }
  131. status = inflate(&z, Z_NO_FLUSH);
  132. if(status == Z_NEED_DICT || status == Z_DATA_ERROR
  133. || status == Z_MEM_ERROR)
  134. {
  135. zerr(status);
  136. throw SerializationError("decompressZlib: inflate failed");
  137. }
  138. int count = output_size - z.avail_out;
  139. if(count)
  140. os.write(output_buffer, count);
  141. bytes_written += count;
  142. if(status == Z_STREAM_END)
  143. {
  144. // Unget all the data that inflate didn't take
  145. is.clear(); // Just in case EOF is set
  146. for(u32 i=0; i < z.avail_in; i++)
  147. {
  148. is.unget();
  149. if(is.fail() || is.bad())
  150. {
  151. dstream<<"unget #"<<i<<" failed"<<std::endl;
  152. dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
  153. throw SerializationError("decompressZlib: unget failed");
  154. }
  155. }
  156. break;
  157. }
  158. }
  159. inflateEnd(&z);
  160. }
  161. struct ZSTD_Deleter {
  162. void operator() (ZSTD_CStream* cstream) {
  163. ZSTD_freeCStream(cstream);
  164. }
  165. void operator() (ZSTD_DStream* dstream) {
  166. ZSTD_freeDStream(dstream);
  167. }
  168. };
  169. void compressZstd(const u8 *data, size_t data_size, std::ostream &os, int level)
  170. {
  171. // reusing the context is recommended for performance
  172. // it will be destroyed when the thread ends
  173. thread_local std::unique_ptr<ZSTD_CStream, ZSTD_Deleter> stream(ZSTD_createCStream());
  174. ZSTD_initCStream(stream.get(), level);
  175. const size_t bufsize = 16384;
  176. char output_buffer[bufsize];
  177. ZSTD_inBuffer input = { data, data_size, 0 };
  178. ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
  179. while (input.pos < input.size) {
  180. size_t ret = ZSTD_compressStream(stream.get(), &output, &input);
  181. if (ZSTD_isError(ret)) {
  182. dstream << ZSTD_getErrorName(ret) << std::endl;
  183. throw SerializationError("compressZstd: failed");
  184. }
  185. if (output.pos) {
  186. os.write(output_buffer, output.pos);
  187. output.pos = 0;
  188. }
  189. }
  190. size_t ret;
  191. do {
  192. ret = ZSTD_endStream(stream.get(), &output);
  193. if (ZSTD_isError(ret)) {
  194. dstream << ZSTD_getErrorName(ret) << std::endl;
  195. throw SerializationError("compressZstd: failed");
  196. }
  197. if (output.pos) {
  198. os.write(output_buffer, output.pos);
  199. output.pos = 0;
  200. }
  201. } while (ret != 0);
  202. }
  203. void compressZstd(const std::string &data, std::ostream &os, int level)
  204. {
  205. compressZstd((u8*)data.c_str(), data.size(), os, level);
  206. }
  207. void decompressZstd(std::istream &is, std::ostream &os)
  208. {
  209. // reusing the context is recommended for performance
  210. // it will be destroyed when the thread ends
  211. thread_local std::unique_ptr<ZSTD_DStream, ZSTD_Deleter> stream(ZSTD_createDStream());
  212. ZSTD_initDStream(stream.get());
  213. const size_t bufsize = 16384;
  214. char output_buffer[bufsize];
  215. char input_buffer[bufsize];
  216. ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
  217. ZSTD_inBuffer input = { input_buffer, 0, 0 };
  218. size_t ret;
  219. do
  220. {
  221. if (input.size == input.pos) {
  222. is.read(input_buffer, bufsize);
  223. input.size = is.gcount();
  224. input.pos = 0;
  225. }
  226. ret = ZSTD_decompressStream(stream.get(), &output, &input);
  227. if (ZSTD_isError(ret)) {
  228. dstream << ZSTD_getErrorName(ret) << std::endl;
  229. throw SerializationError("decompressZstd: failed");
  230. }
  231. if (output.pos) {
  232. os.write(output_buffer, output.pos);
  233. output.pos = 0;
  234. }
  235. } while (ret != 0);
  236. // Unget all the data that ZSTD_decompressStream didn't take
  237. is.clear(); // Just in case EOF is set
  238. for (u32 i = 0; i < input.size - input.pos; i++) {
  239. is.unget();
  240. if (is.fail() || is.bad())
  241. throw SerializationError("decompressZstd: unget failed");
  242. }
  243. }
  244. void compress(u8 *data, u32 size, std::ostream &os, u8 version, int level)
  245. {
  246. if(version >= 29)
  247. {
  248. // map the zlib levels [0,9] to [1,10]. -1 becomes 0 which indicates the default (currently 3)
  249. compressZstd(data, size, os, level + 1);
  250. return;
  251. }
  252. if(version >= 11)
  253. {
  254. compressZlib(data, size, os, level);
  255. return;
  256. }
  257. if(size == 0)
  258. return;
  259. // Write length (u32)
  260. u8 tmp[4];
  261. writeU32(tmp, size);
  262. os.write((char*)tmp, 4);
  263. // We will be writing 8-bit pairs of more_count and byte
  264. u8 more_count = 0;
  265. u8 current_byte = data[0];
  266. for(u32 i=1; i<size; i++)
  267. {
  268. if(
  269. data[i] != current_byte
  270. || more_count == 255
  271. )
  272. {
  273. // write count and byte
  274. os.write((char*)&more_count, 1);
  275. os.write((char*)&current_byte, 1);
  276. more_count = 0;
  277. current_byte = data[i];
  278. }
  279. else
  280. {
  281. more_count++;
  282. }
  283. }
  284. // write count and byte
  285. os.write((char*)&more_count, 1);
  286. os.write((char*)&current_byte, 1);
  287. }
  288. void compress(const SharedBuffer<u8> &data, std::ostream &os, u8 version, int level)
  289. {
  290. compress(*data, data.getSize(), os, version, level);
  291. }
  292. void compress(const std::string &data, std::ostream &os, u8 version, int level)
  293. {
  294. compress((u8*)data.c_str(), data.size(), os, version, level);
  295. }
  296. void decompress(std::istream &is, std::ostream &os, u8 version)
  297. {
  298. if(version >= 29)
  299. {
  300. decompressZstd(is, os);
  301. return;
  302. }
  303. if(version >= 11)
  304. {
  305. decompressZlib(is, os);
  306. return;
  307. }
  308. // Read length (u32)
  309. u8 tmp[4];
  310. is.read((char*)tmp, 4);
  311. u32 len = readU32(tmp);
  312. // We will be reading 8-bit pairs of more_count and byte
  313. u32 count = 0;
  314. for(;;)
  315. {
  316. u8 more_count=0;
  317. u8 byte=0;
  318. is.read((char*)&more_count, 1);
  319. is.read((char*)&byte, 1);
  320. if(is.eof())
  321. throw SerializationError("decompress: stream ended halfway");
  322. for(s32 i=0; i<(u16)more_count+1; i++)
  323. os.write((char*)&byte, 1);
  324. count += (u16)more_count+1;
  325. if(count == len)
  326. break;
  327. }
  328. }