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