forked from agavra/compression-golf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzstd.rs
More file actions
43 lines (36 loc) · 1.03 KB
/
zstd.rs
File metadata and controls
43 lines (36 loc) · 1.03 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
//! # Zstd Codec
//!
//! **Strategy:** Plain JSON serialization compressed with Zstd.
//!
//! This applies Zstd compression to the naive JSON representation.
use bytes::Bytes;
use std::error::Error;
use crate::codec::EventCodec;
use crate::{EventKey, EventValue};
pub struct ZstdCodec {
level: i32,
name: String,
}
impl ZstdCodec {
pub fn new(level: i32) -> Self {
Self {
level,
name: format!("Zstd({})", level),
}
}
}
impl EventCodec for ZstdCodec {
fn name(&self) -> &str {
&self.name
}
fn encode(&self, events: &[(EventKey, EventValue)]) -> Result<Bytes, Box<dyn Error>> {
let json = serde_json::to_vec(events)?;
let compressed = zstd::encode_all(json.as_slice(), self.level)?;
Ok(Bytes::from(compressed))
}
fn decode(&self, bytes: &[u8]) -> Result<Vec<(EventKey, EventValue)>, Box<dyn Error>> {
let decompressed = zstd::decode_all(bytes)?;
let events = serde_json::from_slice(&decompressed)?;
Ok(events)
}
}