| 89 | } |
| 90 | |
| 91 | bool GZip::zip(const QByteArray& uncompressedBytes, QByteArray& compressedBytes) |
| 92 | { |
| 93 | if (uncompressedBytes.size() == 0) { |
| 94 | compressedBytes = uncompressedBytes; |
| 95 | return true; |
| 96 | } |
| 97 | |
| 98 | unsigned compLength = qMin(uncompressedBytes.size(), 16); |
| 99 | compressedBytes.clear(); |
| 100 | compressedBytes.resize(compLength); |
| 101 | |
| 102 | z_stream zs; |
| 103 | memset(&zs, 0, sizeof(zs)); |
| 104 | |
| 105 | if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (16 + MAX_WBITS), 8, Z_DEFAULT_STRATEGY) != Z_OK) { |
| 106 | return false; |
| 107 | } |
| 108 | |
| 109 | zs.next_in = (Bytef*)uncompressedBytes.data(); |
| 110 | zs.avail_in = uncompressedBytes.size(); |
| 111 | |
| 112 | int ret; |
| 113 | compressedBytes.resize(uncompressedBytes.size()); |
| 114 | |
| 115 | unsigned offset = 0; |
| 116 | unsigned temp = 0; |
| 117 | do { |
| 118 | auto remaining = compressedBytes.size() - offset; |
| 119 | if (remaining < 1) { |
| 120 | compressedBytes.resize(compressedBytes.size() * 2); |
| 121 | } |
| 122 | zs.next_out = reinterpret_cast<Bytef*>((compressedBytes.data() + offset)); |
| 123 | temp = zs.avail_out = compressedBytes.size() - offset; |
| 124 | ret = deflate(&zs, Z_FINISH); |
| 125 | offset += temp - zs.avail_out; |
| 126 | } while (ret == Z_OK); |
| 127 | |
| 128 | compressedBytes.resize(offset); |
| 129 | |
| 130 | if (deflateEnd(&zs) != Z_OK) { |
| 131 | return false; |
| 132 | } |
| 133 | |
| 134 | if (ret != Z_STREAM_END) { |
| 135 | return false; |
| 136 | } |
| 137 | return true; |
| 138 | } |