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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use anyhow::anyhow;
use anyhow::bail;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use bytes::Bytes;
fn code_to_err(code: zstd_safe::ErrorCode) -> Error {
anyhow!(zstd_safe::get_error_name(code))
}
pub struct Compressor {
cctx: zstd_safe::CCtx<'static>,
dict_loaded: bool,
}
impl Compressor {
pub fn new() -> Self {
Self {
cctx: zstd_safe::CCtx::create(),
dict_loaded: false,
}
}
fn reset_dict(&mut self) -> Result<()> {
if self.dict_loaded {
self.cctx
.load_dictionary(&[])
.map_err(code_to_err)
.context("Failed to load empty dictionary")?;
self.dict_loaded = false;
}
Ok(())
}
pub fn load_dict(&mut self, dict: &[u8]) -> Result<()> {
self.cctx
.load_dictionary(dict)
.map_err(code_to_err)
.context("Failed to load dictionary")?;
self.dict_loaded = true;
Ok(())
}
pub fn compress_with_loaded_dict(&mut self, frame: &[u8]) -> Result<Bytes> {
let mut buf = Vec::with_capacity(zstd_safe::compress_bound(frame.len()));
self.cctx
.compress2(&mut buf, frame)
.map_err(code_to_err)
.context("zstd compress2 failed")?;
Ok(buf.into())
}
pub fn compress_with_dict_reset(&mut self, frame: &[u8]) -> Result<Bytes> {
self.reset_dict().context("Failed to reload dict")?;
self.compress_with_loaded_dict(frame)
.context("Failed to compress without dict")
}
}
pub struct Decompressor<K> {
dctx: zstd_safe::DCtx<'static>,
dict: Bytes,
dict_key: Option<K>,
}
impl<K> Decompressor<K> {
pub fn new() -> Self {
Self {
dctx: zstd_safe::DCtx::create(),
dict: Bytes::new(),
dict_key: None,
}
}
pub fn get_dict(&self) -> &Bytes {
&self.dict
}
pub fn get_dict_key(&self) -> Option<&K> {
self.dict_key.as_ref()
}
fn reset_dict(&mut self) -> Result<()> {
if !self.dict.is_empty() {
self.dctx
.load_dictionary(&[])
.map_err(code_to_err)
.context("Failed to load empty dictionary")?;
self.dict = Bytes::new();
self.dict_key = None;
}
Ok(())
}
pub fn load_dict(&mut self, dict: Bytes, key: K) -> Result<()> {
self.dctx
.load_dictionary(&dict)
.map_err(code_to_err)
.context("Failed to load zstd dictionary by reference")?;
self.dict = dict;
self.dict_key = Some(key);
Ok(())
}
pub fn decompress_with_loaded_dict(&mut self, frame: &[u8]) -> Result<Bytes> {
let capacity = match zstd_safe::get_frame_content_size(frame) {
zstd_safe::CONTENTSIZE_ERROR => bail!("Error getting frame content size"),
zstd_safe::CONTENTSIZE_UNKNOWN => bail!("Unknown decompressed size"),
capacity => capacity as usize,
};
let mut buf = Vec::with_capacity(capacity);
self.dctx
.decompress(&mut buf, frame)
.map_err(code_to_err)
.context("zstd decompress failed")?;
Ok(buf.into())
}
pub fn decompress_with_dict_reset(&mut self, frame: &[u8]) -> Result<Bytes> {
self.reset_dict().context("Failed to reload dict")?;
self.decompress_with_loaded_dict(frame)
.context("Failed to decompress without dict")
}
}
#[cfg(test)]
mod test {
use super::*;
fn gen_data(n: usize) -> Vec<u8> {
use std::hash::Hasher;
let mut data = Vec::with_capacity(n);
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write_u64(0xfaceb00c);
while data.len() < n {
let val = hasher.finish();
data.extend(val.to_be_bytes());
hasher.write_u64(val);
}
data
}
#[test]
fn compressor_decompressor() {
let mut c = Compressor::new();
let mut d = Decompressor::new();
let data: Bytes = gen_data(128).into();
let comp_default = c
.compress_with_loaded_dict(&data)
.expect("Failed to compress");
c.load_dict(&data).expect("Fail to load dict");
let comp_with_dict = c
.compress_with_loaded_dict(&data)
.expect("Failed to compress");
let comp_dict_reset = c
.compress_with_dict_reset(&data)
.expect("Failed to compress");
assert!(comp_with_dict.len() < comp_default.len());
assert_eq!(comp_dict_reset, comp_default);
let decomp_default = d
.decompress_with_loaded_dict(&comp_default)
.expect("Failed to decompress");
d.load_dict(data.clone(), ()).expect("Failed to load dict");
let decomp_with_dict = d
.decompress_with_loaded_dict(&comp_with_dict)
.expect("Failed to decompress");
let decomp_dict_reset = d
.decompress_with_dict_reset(&comp_dict_reset)
.expect("Failed to decompress");
assert_eq!(decomp_default, data);
assert_eq!(decomp_with_dict, data);
assert_eq!(decomp_dict_reset, data);
}
#[test]
fn compatibility() {
let data: Bytes = gen_data(128).into();
{
let comp = Compressor::new()
.compress_with_dict_reset(&data)
.expect("Failed to compress");
let decomp = zstd::stream::decode_all(&*comp).expect("Failed to decompress");
assert_eq!(decomp, data);
}
{
let comp = zstd::bulk::compress(&data, 0).expect("Failed to compress");
let decomp = Decompressor::<()>::new()
.decompress_with_dict_reset(&comp)
.expect("Failed to decompress");
assert_eq!(decomp, data);
}
}
}