1 /* Copyright (C) 2011 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/external_libraries/zlib.h"
24
CompressZLib(const std::string & data,std::string & out,bool includeLengthHeader)25 void CompressZLib(const std::string& data, std::string& out, bool includeLengthHeader)
26 {
27 uLongf maxCompressedSize = compressBound(data.size());
28 uLongf destLen = maxCompressedSize;
29
30 out.clear();
31
32 if (includeLengthHeader)
33 {
34 // Add a 4-byte uncompressed length header to the output
35 out.resize(maxCompressedSize + 4);
36 write_le32((void*)out.c_str(), data.size());
37 int zok = compress((Bytef*)out.c_str() + 4, &destLen, (const Bytef*)data.c_str(), data.size());
38 ENSURE(zok == Z_OK);
39 out.resize(destLen + 4);
40 }
41 else
42 {
43 out.resize(maxCompressedSize);
44 int zok = compress((Bytef*)out.c_str(), &destLen, (const Bytef*)data.c_str(), data.size());
45 ENSURE(zok == Z_OK);
46 out.resize(destLen);
47 }
48 }
49
DecompressZLib(const std::string & data,std::string & out,bool includeLengthHeader)50 void DecompressZLib(const std::string& data, std::string& out, bool includeLengthHeader)
51 {
52 ENSURE(includeLengthHeader); // otherwise we don't know how much to allocate
53
54 out.clear();
55 out.resize(read_le32(data.c_str()));
56
57 uLongf destLen = out.size();
58 int zok = uncompress((Bytef*)out.c_str(), &destLen, (const Bytef*)data.c_str() + 4, data.size() - 4);
59 ENSURE(zok == Z_OK);
60 ENSURE(destLen == out.size());
61
62 // TODO: better error reporting might be nice
63 }
64