Line data Source code
1 : /* Copyright (C) 2025 Wildfire Games. 2 : * This file is part of 0 A.D. 3 : * 4 : * 0 A.D. is free software: you can redistribute it and/or modify 5 : * it under the terms of the GNU General Public License as published by 6 : * the Free Software Foundation, either version 2 of the License, or 7 : * (at your option) any later version. 8 : * 9 : * 0 A.D. is distributed in the hope that it will be useful, 10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 : * GNU General Public License for more details. 13 : * 14 : * You should have received a copy of the GNU General Public License 15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 : */ 17 : 18 : #include "precompiled.h" 19 : 20 : #include "Compress.h" 21 : 22 : #include "lib/byte_order.h" 23 : #include "lib/debug.h" 24 : #include "lib/external_libraries/zlib.h" 25 : 26 1 : void CompressZLib(const std::string& data, std::string& out, bool includeLengthHeader) 27 : { 28 1 : uLongf maxCompressedSize = compressBound(data.size()); 29 1 : uLongf destLen = maxCompressedSize; 30 : 31 1 : out.clear(); 32 : 33 1 : if (includeLengthHeader) 34 : { 35 : // Add a 4-byte uncompressed length header to the output 36 1 : out.resize(maxCompressedSize + 4); 37 1 : write_le32((void*)out.c_str(), data.size()); 38 1 : int zok = compress((Bytef*)out.c_str() + 4, &destLen, (const Bytef*)data.c_str(), data.size()); 39 1 : ENSURE(zok == Z_OK); 40 1 : out.resize(destLen + 4); 41 : } 42 : else 43 : { 44 0 : out.resize(maxCompressedSize); 45 0 : int zok = compress((Bytef*)out.c_str(), &destLen, (const Bytef*)data.c_str(), data.size()); 46 0 : ENSURE(zok == Z_OK); 47 0 : out.resize(destLen); 48 : } 49 1 : } 50 : 51 1 : void DecompressZLib(const std::string& data, std::string& out, bool includeLengthHeader) 52 : { 53 1 : ENSURE(includeLengthHeader); // otherwise we don't know how much to allocate 54 : 55 1 : out.clear(); 56 1 : out.resize(read_le32(data.c_str())); 57 : 58 1 : uLongf destLen = out.size(); 59 1 : int zok = uncompress((Bytef*)out.c_str(), &destLen, (const Bytef*)data.c_str() + 4, data.size() - 4); 60 1 : ENSURE(zok == Z_OK); 61 1 : ENSURE(destLen == out.size()); 62 : 63 : // TODO: better error reporting might be nice 64 1 : }