-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
gzipstring.h
105 lines (83 loc) · 2.66 KB
/
gzipstring.h
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
// Copyright 2010-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OR_TOOLS_BASE_GZIPSTRING_H_
#define OR_TOOLS_BASE_GZIPSTRING_H_
#include <string>
#include "ortools/base/logging.h"
#include "zlib.h"
bool GunzipString(absl::string_view str, std::string* out) {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.next_in = Z_NULL;
zs.avail_in = 0;
zs.next_out = Z_NULL;
if (inflateInit2(&zs, /*window_bits=*/15 + 32) != Z_OK) {
return false;
}
zs.next_in = (Bytef*)str.data();
zs.avail_in = str.size();
int status;
char buffer[32768];
// Decompress string by block.
do {
zs.next_out = reinterpret_cast<Bytef*>(buffer);
zs.avail_out = sizeof(buffer);
status = inflate(&zs, 0);
if (out->size() < zs.total_out) {
out->append(buffer, zs.total_out - out->size());
}
} while (status == Z_OK);
inflateEnd(&zs);
if (status != Z_STREAM_END) { // an error occurred that was not EOF
VLOG(1) << "Exception during zlib decompression: (" << status << ") "
<< zs.msg;
return false;
}
return true;
}
bool GzipString(absl::string_view uncompressed, std::string* compressed) {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.next_in = Z_NULL;
zs.avail_in = 0;
zs.next_out = Z_NULL;
if (deflateInit(&zs, Z_BEST_COMPRESSION) != Z_OK) {
VLOG(1) << "Cannot initialize zlib compression.";
return false;
}
zs.next_in = (Bytef*)uncompressed.data();
zs.avail_in = uncompressed.size(); // set the z_stream's input
int status;
char buffer[32768];
// compress block by block.
do {
zs.next_out = reinterpret_cast<Bytef*>(buffer);
zs.avail_out = sizeof(buffer);
status = deflate(&zs, Z_FINISH);
if (compressed->size() < zs.total_out) {
compressed->append(buffer, zs.total_out - compressed->size());
}
} while (status == Z_OK);
deflateEnd(&zs);
if (status != Z_STREAM_END) { // an error occurred that was not EOF
VLOG(1) << "Exception during zlib compression: (" << status << ") "
<< zs.msg;
return false;
}
return true;
}
#endif // OR_TOOLS_BASE_GZIPSTRING_H_