| 28 | namespace mdf { |
| 29 | |
| 30 | bool Deflate(std::streambuf& in, std::streambuf& out) { |
| 31 | z_stream s{}; |
| 32 | std::vector<uint8_t> buf_in(kZlibChunk, 0); |
| 33 | std::vector<uint8_t> buf_out(kZlibChunk, 0); |
| 34 | |
| 35 | auto ret = deflateInit(&s, Z_DEFAULT_COMPRESSION); |
| 36 | if (ret != Z_OK) { |
| 37 | return false; |
| 38 | } |
| 39 | |
| 40 | /* compress until end of file */ |
| 41 | int flush; |
| 42 | do { |
| 43 | s.avail_in = static_cast<uInt>(in.sgetn( |
| 44 | reinterpret_cast<char*>(buf_in.data()), kZlibChunk ) ); |
| 45 | flush = s.avail_in < kZlibChunk ? Z_FINISH : Z_NO_FLUSH; |
| 46 | s.next_in = buf_in.data(); |
| 47 | |
| 48 | /* run deflate() on input until output buffer not full, finish |
| 49 | compression if all the sources has been read in */ |
| 50 | do { |
| 51 | s.avail_out = kZlibChunk; |
| 52 | s.next_out = buf_out.data(); |
| 53 | ret = deflate(&s, flush); /* no bad return value */ |
| 54 | if (ret == Z_STREAM_ERROR) { /* state not clobbered */ |
| 55 | return false; |
| 56 | } |
| 57 | const auto have = kZlibChunk - s.avail_out; |
| 58 | if (out.sputn( reinterpret_cast<char*>(buf_out.data()), |
| 59 | static_cast<std::streamsize>(have) ) != have ) { |
| 60 | deflateEnd(&s); |
| 61 | return false; |
| 62 | } |
| 63 | } while (s.avail_out == 0); |
| 64 | if (s.avail_in != 0) { /* all input will be used */ |
| 65 | return false; |
| 66 | } |
| 67 | /* done when last data in file processed */ |
| 68 | } while (flush != Z_FINISH); |
| 69 | /* stream will be complete */ |
| 70 | if (ret != Z_STREAM_END) { /* all input will be used */ |
| 71 | return false; |
| 72 | } |
| 73 | |
| 74 | /* clean up and return */ |
| 75 | deflateEnd(&s); |
| 76 | return true; |
| 77 | } |
| 78 | |
| 79 | bool Deflate(const std::string& filename, ByteArray& buf_out) { |
| 80 | try { |