Debian Codegraph @

common/GzipWriter.h

raw
1 /*
2 * GzipWriter.h
3 * ------------
4 * Purpose: Simple wrapper around zlib's Gzip writer
5 * Notes : miniz doesn't implement Gzip writing, so this is only compatible with zlib.
6 * Authors: OpenMPT Devs
7 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
8 */
9
10
11 #pragma once
12
13 #include "openmpt/all/BuildSettings.hpp"
14
15 #include "mpt/io/io.hpp"
16 #include "mpt/io/io_stdstream.hpp"
17
18 #include "mptString.h"
19
20 #ifdef MPT_WITH_ZLIB
21
22 #include <ctime>
23
24 #include <zlib.h>
25
26 OPENMPT_NAMESPACE_BEGIN
27
28 inline void WriteGzip(std::ostream &output, std::string &outData, const mpt::ustring &fileName)
29 {
30 z_stream strm{};
31 int zlib_errc = Z_OK;
32 strm.avail_in = static_cast<uInt>(outData.size());
33 strm.next_in = reinterpret_cast<Bytef *>(outData.data());
34 zlib_errc = deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED, 15 | 16, 9, Z_DEFAULT_STRATEGY);
35 if(zlib_errc == Z_MEM_ERROR)
36 {
37 mpt::throw_out_of_memory();
38 } else if(zlib_errc < Z_OK)
39 {
40 throw std::runtime_error{"zlib: deflateInit2() failed"};
41 }
42 gz_header gzHeader{};
43 gzHeader.time = static_cast<uLong>(std::time(nullptr));
44 std::string filenameISO = mpt::ToCharset(mpt::Charset::ISO8859_1, fileName);
45 gzHeader.name = reinterpret_cast<Bytef *>(filenameISO.data());
46 zlib_errc = deflateSetHeader(&strm, &gzHeader);
47 if(zlib_errc == Z_MEM_ERROR)
48 {
49 deflateEnd(&strm);
50 mpt::throw_out_of_memory();
51 } else if(zlib_errc < Z_OK)
52 {
53 deflateEnd(&strm);
54 throw std::runtime_error{"zlib: deflateSetHeader() failed"};
55 }
56 try
57 {
58 do
59 {
60 std::array<Bytef, mpt::IO::BUFFERSIZE_TINY> buffer;
61 strm.avail_out = static_cast<uInt>(buffer.size());
62 strm.next_out = buffer.data();
63 zlib_errc = deflate(&strm, Z_FINISH);
64 if(zlib_errc == Z_BUF_ERROR)
65 {
66 // expected
67 } else if(zlib_errc == Z_MEM_ERROR)
68 {
69 mpt::throw_out_of_memory();
70 } else if(zlib_errc < Z_OK)
71 {
72 throw std::runtime_error{"zlib: deflate() failed"};
73 }
74 mpt::IO::WritePartial(output, buffer, buffer.size() - strm.avail_out);
75 } while(strm.avail_out == 0);
76 } catch(mpt::out_of_memory e)
77 {
78 deflateEnd(&strm);
79 mpt::rethrow_out_of_memory(e);
80 } catch(const std::exception &)
81 {
82 deflateEnd(&strm);
83 throw;
84 } catch(...)
85 {
86 deflateEnd(&strm);
87 throw;
88 }
89 deflateEnd(&strm);
90 }
91
92 OPENMPT_NAMESPACE_END
93
94 #endif