-
-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathdecompress_zstd.cpp
More file actions
70 lines (58 loc) · 2.16 KB
/
decompress_zstd.cpp
File metadata and controls
70 lines (58 loc) · 2.16 KB
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
#include "utils/decompress/decompress_zstd.h"
#include <zstd.h> // For ZSTD_*, ZSTD_DStream, etc.
#include <vector>
#include <memory>
namespace cpptrace {
namespace detail {
Result<monostate, internal_error> decompress_zstd(
bspan decompressed_data,
base_file& compressed_file,
off_t offset,
size_t compressed_size
) {
std::unique_ptr<ZSTD_DStream, decltype(&ZSTD_freeDStream)> dstream(ZSTD_createDStream(), ZSTD_freeDStream);
if(!dstream) {
return internal_error("ZSTD_createDStream failed");
}
size_t init_ret = ZSTD_initDStream(dstream.get());
if(ZSTD_isError(init_ret)) {
return internal_error(std::string("ZSTD_initDStream failed: ") + ZSTD_getErrorName(init_ret));
}
static const size_t CHUNK_SIZE = ZSTD_DStreamInSize();
std::vector<char> chunk_buffer(CHUNK_SIZE);
ZSTD_outBuffer output = {};
output.dst = decompressed_data.data();
output.size = decompressed_data.size();
output.pos = 0;
size_t total_read = 0;
while(total_read < compressed_size) {
size_t to_read = std::min(CHUNK_SIZE, compressed_size - total_read);
auto read_res = compressed_file.read_span(
cpptrace::detail::make_span(chunk_buffer.begin(), chunk_buffer.begin() + static_cast<std::ptrdiff_t>(to_read)),
static_cast<off_t>(offset + total_read)
);
if(!read_res) {
return read_res.unwrap_error();
}
ZSTD_inBuffer input = {};
input.src = chunk_buffer.data();
input.size = to_read;
input.pos = 0;
while(input.pos < input.size) {
size_t decompress_ret = ZSTD_decompressStream(dstream.get(), &output, &input);
if(ZSTD_isError(decompress_ret)) {
return internal_error(std::string("ZSTD_decompressStream failed: ") + ZSTD_getErrorName(decompress_ret));
}
if(decompress_ret == 0) {
break;
}
}
total_read += to_read;
}
if(output.pos != decompressed_data.size()) {
return internal_error("zstd decompressed size mismatch");
}
return monostate{};
}
} // namespace detail
} // namespace cpptrace