| 38 | #include <QByteArray> |
| 39 | |
| 40 | bool GZip::unzip(const QByteArray &compressedBytes, QByteArray &uncompressedBytes) |
| 41 | { |
| 42 | if (compressedBytes.size() == 0) |
| 43 | { |
| 44 | uncompressedBytes = compressedBytes; |
| 45 | return true; |
| 46 | } |
| 47 | |
| 48 | unsigned uncompLength = compressedBytes.size(); |
| 49 | uncompressedBytes.clear(); |
| 50 | uncompressedBytes.resize(uncompLength); |
| 51 | |
| 52 | z_stream strm; |
| 53 | memset(&strm, 0, sizeof(strm)); |
| 54 | strm.next_in = (Bytef *)compressedBytes.data(); |
| 55 | strm.avail_in = compressedBytes.size(); |
| 56 | |
| 57 | bool done = false; |
| 58 | |
| 59 | if (inflateInit2(&strm, (16 + MAX_WBITS)) != Z_OK) |
| 60 | { |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | int err = Z_OK; |
| 65 | |
| 66 | while (!done) |
| 67 | { |
| 68 | // If our output buffer is too small |
| 69 | if (strm.total_out >= uncompLength) |
| 70 | { |
| 71 | uncompressedBytes.resize(uncompLength * 2); |
| 72 | uncompLength *= 2; |
| 73 | } |
| 74 | |
| 75 | strm.next_out = (Bytef *)(uncompressedBytes.data() + strm.total_out); |
| 76 | strm.avail_out = uncompLength - strm.total_out; |
| 77 | |
| 78 | // Inflate another chunk. |
| 79 | err = inflate(&strm, Z_SYNC_FLUSH); |
| 80 | if (err == Z_STREAM_END) |
| 81 | done = true; |
| 82 | else if (err != Z_OK) |
| 83 | { |
| 84 | break; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | if (inflateEnd(&strm) != Z_OK || !done) |
| 89 | { |
| 90 | return false; |
| 91 | } |
| 92 | |
| 93 | uncompressedBytes.resize(strm.total_out); |
| 94 | return true; |
| 95 | } |
| 96 | |
| 97 | bool GZip::zip(const QByteArray &uncompressedBytes, QByteArray &compressedBytes) |