-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecompression.rs
More file actions
69 lines (58 loc) · 2.3 KB
/
decompression.rs
File metadata and controls
69 lines (58 loc) · 2.3 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
use zstd_safe::{DCtx, InBuffer, OutBuffer};
/// A zstd decompressor for PERF_RECORD_COMPRESSED records.
pub struct ZstdDecompressor {
dctx: Option<DCtx<'static>>,
/// Buffer for partial perf records that span multiple compressed chunks
partial_record_buffer: Vec<u8>,
}
impl Default for ZstdDecompressor {
fn default() -> Self {
Self::new()
}
}
impl ZstdDecompressor {
pub fn new() -> Self {
Self {
dctx: None,
partial_record_buffer: Vec::new(),
}
}
/// Decompress a chunk of zstd data.
pub fn decompress(&mut self, compressed_data: &[u8]) -> Result<Vec<u8>, std::io::Error> {
let dctx = self.dctx.get_or_insert_with(DCtx::create);
let mut decompressed = vec![0; compressed_data.len() * 4];
let mut in_buffer = InBuffer::around(compressed_data);
let mut total_out = 0;
while in_buffer.pos < in_buffer.src.len() {
let available = decompressed.len() - total_out;
let mut out_buffer = OutBuffer::around(&mut decompressed[total_out..]);
match dctx.decompress_stream(&mut out_buffer, &mut in_buffer) {
Ok(_) => {
total_out += out_buffer.pos();
if out_buffer.pos() == available {
decompressed.resize(decompressed.len() + compressed_data.len() * 4, 0);
}
}
Err(code) => {
let error_name = zstd_safe::get_error_name(code);
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Zstd decompression failed: {}", error_name),
));
}
}
}
decompressed.truncate(total_out);
// Prepend any partial record data from the previous chunk
if !self.partial_record_buffer.is_empty() {
let mut combined = std::mem::take(&mut self.partial_record_buffer);
combined.extend_from_slice(&decompressed);
decompressed = combined;
}
Ok(decompressed)
}
/// Save partial record data that spans to the next compressed chunk.
pub fn save_partial_record(&mut self, data: &[u8]) {
self.partial_record_buffer = data.to_vec();
}
}