|
51 | 51 | #include <curl/curl.h>
|
52 | 52 | #endif
|
53 | 53 |
|
| 54 | +#include "zconf.h" |
| 55 | +#include "zlib.h" |
| 56 | + |
54 | 57 | #ifdef WIN32
|
55 | 58 | #include <io.h>
|
56 | 59 | #else
|
@@ -1264,3 +1267,69 @@ string ToTimeStringLong(double seconds) {
|
1264 | 1267 | return TString::Format("%.2f %s", seconds / (60.0 * 60.0 * 24.0), "days").Data();
|
1265 | 1268 | }
|
1266 | 1269 | }
|
| 1270 | + |
| 1271 | +/////////////////////////////////////////////// |
| 1272 | +/// It will decompress a std::string that has been initialized from a gzip file. |
| 1273 | +/// |
| 1274 | +bool TRestTools::GzipInflate(const std::string& compressedBytes, std::string& uncompressedBytes) { |
| 1275 | + if (compressedBytes.size() == 0) { |
| 1276 | + uncompressedBytes = compressedBytes; |
| 1277 | + return true; |
| 1278 | + } |
| 1279 | + |
| 1280 | + uncompressedBytes.clear(); |
| 1281 | + |
| 1282 | + unsigned full_length = compressedBytes.size(); |
| 1283 | + unsigned half_length = compressedBytes.size() / 2; |
| 1284 | + |
| 1285 | + unsigned uncompLength = full_length; |
| 1286 | + char* uncomp = (char*)calloc(sizeof(char), uncompLength); |
| 1287 | + |
| 1288 | + z_stream strm; |
| 1289 | + strm.next_in = (Bytef*)compressedBytes.c_str(); |
| 1290 | + strm.avail_in = compressedBytes.size(); |
| 1291 | + strm.total_out = 0; |
| 1292 | + strm.zalloc = Z_NULL; |
| 1293 | + strm.zfree = Z_NULL; |
| 1294 | + |
| 1295 | + bool done = false; |
| 1296 | + |
| 1297 | + if (inflateInit2(&strm, (16 + MAX_WBITS)) != Z_OK) { |
| 1298 | + free(uncomp); |
| 1299 | + return false; |
| 1300 | + } |
| 1301 | + |
| 1302 | + while (!done) { |
| 1303 | + // If our output buffer is too small |
| 1304 | + if (strm.total_out >= uncompLength) { |
| 1305 | + // Increase size of output buffer |
| 1306 | + char* uncomp2 = (char*)calloc(sizeof(char), uncompLength + half_length); |
| 1307 | + memcpy(uncomp2, uncomp, uncompLength); |
| 1308 | + uncompLength += half_length; |
| 1309 | + free(uncomp); |
| 1310 | + uncomp = uncomp2; |
| 1311 | + } |
| 1312 | + |
| 1313 | + strm.next_out = (Bytef*)(uncomp + strm.total_out); |
| 1314 | + strm.avail_out = uncompLength - strm.total_out; |
| 1315 | + |
| 1316 | + // Inflate another chunk. |
| 1317 | + int err = inflate(&strm, Z_SYNC_FLUSH); |
| 1318 | + if (err == Z_STREAM_END) |
| 1319 | + done = true; |
| 1320 | + else if (err != Z_OK) { |
| 1321 | + break; |
| 1322 | + } |
| 1323 | + } |
| 1324 | + |
| 1325 | + if (inflateEnd(&strm) != Z_OK) { |
| 1326 | + free(uncomp); |
| 1327 | + return false; |
| 1328 | + } |
| 1329 | + |
| 1330 | + for (size_t i = 0; i < strm.total_out; ++i) { |
| 1331 | + uncompressedBytes += uncomp[i]; |
| 1332 | + } |
| 1333 | + free(uncomp); |
| 1334 | + return true; |
| 1335 | +} |
0 commit comments