File: ZipUtil.cpp

package info (click to toggle)
bornagain 23.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,936 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 318; ruby: 173; xml: 130; makefile: 51; ansic: 24
file content (223 lines) | stat: -rw-r--r-- 7,071 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/IO/ZipUtil.cpp
//! @brief     Implements functions in namespace ZipUtil.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2023
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Device/IO/ZipUtil.h"
#include "Base/Util/PathUtil.h"
#include "Base/Util/StringUtil.h"
#include <bzlib.h> // For Bzip2 decompression
#include <fstream>
#include <zlib.h> // For Gzip decompression

namespace {

const std::string GzipExtension = ".gz";
const std::string BzipExtension = ".bz2";

bool isGZipped(const std::string& fname)
{
    return Base::Path::hasExtension(fname, GzipExtension);
}

bool isBZipped(const std::string& fname)
{
    return Base::Path::hasExtension(fname, BzipExtension);
}

bool isCompressed(const std::string& fname)
{
    return isGZipped(fname) || isBZipped(fname);
}

bool isNativeBinary(const std::string& fname)
{
    const std::string ext = ZipUtil::uncompressedExtension(fname);
    return ext == ".tif" || ext == ".tiff";
}

bool isBinary(const std::string& fname)
{
    return isCompressed(fname) || isNativeBinary(fname);
}

} // namespace


std::string ZipUtil::uncompressedExtension(std::string fname)
{
    if (isGZipped(fname))
        fname = fname.substr(0, fname.size() - GzipExtension.size());
    else if (isBZipped(fname))
        fname = fname.substr(0, fname.size() - BzipExtension.size());

    return Base::String::to_lower(Base::Path::extension(fname));
}

std::stringstream ZipUtil::file2stream(const std::string& fname)
{
    if (!Base::Path::IsFileExists(fname))
        throw std::runtime_error("File does not exist: " + fname);

    // Open the input file
    std::ifstream input_stream;
    std::ios_base::openmode openmode = std::ios::in;
    if (isBinary(fname))
        openmode |= std::ios_base::binary;
    input_stream.open(Base::Path::osPath(fname), openmode);

    if (!input_stream.is_open())
        throw std::runtime_error("Cannot open file for reading: " + fname);
    if (!input_stream.good())
        throw std::runtime_error("File is not good, probably it is a directory: " + fname);

    // Read the file content into a string
    std::ostringstream raw_stream;
    raw_stream << input_stream.rdbuf();
    std::string file_content = raw_stream.str();

    // Decompressed content will be written to this stringstream
    std::stringstream ss;

    // Decompress if necessary
    if (::isGZipped(fname)) {
        // Gzip decompression
        z_stream zs = {};
        zs.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(file_content.data()));
        zs.avail_in = file_content.size();

        if (inflateInit2(&zs, 15 + 32) != Z_OK) // 15 + 32 enables Gzip decoding
            throw std::runtime_error("Failed to initialize Gzip decompression");

        char buffer[4096];
        do {
            zs.next_out = reinterpret_cast<Bytef*>(buffer);
            zs.avail_out = sizeof(buffer);

            int ret = inflate(&zs, Z_NO_FLUSH);
            if (ret != Z_OK && ret != Z_STREAM_END) {
                inflateEnd(&zs);
                throw std::runtime_error("Gzip decompression failed");
            }

            ss.write(buffer, sizeof(buffer) - zs.avail_out);
        } while (zs.avail_out == 0);

        inflateEnd(&zs);

    } else if (::isBZipped(fname)) {
        // Bzip2 decompression
        bz_stream bzs = {};
        bzs.next_in = const_cast<char*>(file_content.data());
        bzs.avail_in = file_content.size();

        if (BZ2_bzDecompressInit(&bzs, 0, 0) != BZ_OK)
            throw std::runtime_error("Failed to initialize Bzip2 decompression");

        char buffer[4096];
        do {
            bzs.next_out = buffer;
            bzs.avail_out = sizeof(buffer);

            int ret = BZ2_bzDecompress(&bzs);
            if (ret != BZ_OK && ret != BZ_STREAM_END) {
                BZ2_bzDecompressEnd(&bzs);
                throw std::runtime_error("Bzip2 decompression failed");
            }

            ss.write(buffer, sizeof(buffer) - bzs.avail_out);
        } while (bzs.avail_out == 0);

        BZ2_bzDecompressEnd(&bzs);

    } else {
        // If not compressed, simply copy the file content
        ss.str(file_content);
    }

    return ss;
}

void ZipUtil::stream2file(const std::string& fname, std::stringstream& s)
{
    std::ofstream fout;
    std::ios_base::openmode openmode = std::ios::out;
    if (isBinary(fname))
        openmode |= std::ios_base::binary;

    fout.open(Base::Path::osPath(fname), openmode);

    if (!fout.is_open())
        throw std::runtime_error("Cannot open file for writing: " + fname);
    if (!fout.good())
        throw std::runtime_error("File is not good, probably it is a directory: " + fname);

    const std::string& content = s.str(); // Get the content from the stringstream

    if (isGZipped(fname)) {
        // Gzip compression
        z_stream zs = {};
        if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY)
            != Z_OK)
            throw std::runtime_error("Failed to initialize Gzip compression");

        zs.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(content.data()));
        zs.avail_in = content.size();

        char buffer[4096];
        do {
            zs.next_out = reinterpret_cast<Bytef*>(buffer);
            zs.avail_out = sizeof(buffer);

            int ret = deflate(&zs, Z_FINISH);
            if (ret != Z_OK && ret != Z_STREAM_END) {
                deflateEnd(&zs);
                throw std::runtime_error("Gzip compression failed");
            }

            fout.write(buffer, sizeof(buffer) - zs.avail_out);
        } while (zs.avail_out == 0);

        deflateEnd(&zs);

    } else if (isBZipped(fname)) {
        // Bzip2 compression
        bz_stream bzs = {};
        if (BZ2_bzCompressInit(&bzs, 9, 0, 0) != BZ_OK) // 9 = max compression level
            throw std::runtime_error("Failed to initialize Bzip2 compression");

        bzs.next_in = const_cast<char*>(content.data());
        bzs.avail_in = content.size();

        char buffer[4096];
        do {
            bzs.next_out = buffer;
            bzs.avail_out = sizeof(buffer);

            int ret = BZ2_bzCompress(&bzs, BZ_FINISH);
            if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK && ret != BZ_STREAM_END) {
                BZ2_bzCompressEnd(&bzs);
                throw std::runtime_error("Bzip2 compression failed");
            }

            fout.write(buffer, sizeof(buffer) - bzs.avail_out);
        } while (bzs.avail_out == 0);

        BZ2_bzCompressEnd(&bzs);

    } else {
        // Write uncompressed content
        fout.write(content.data(), content.size());
    }

    fout.close();
}