pingora_header_serde/
dict.rsuse std::fs;
use zstd::dict;
pub fn train<P: AsRef<std::path::Path>>(dir_path: P) -> Vec<u8> {
let files = fs::read_dir(dir_path)
.unwrap()
.filter_map(|entry| entry.ok().map(|f| f.path()));
dict::from_files(files, 64 * 1024 * 1024).unwrap()
}
#[cfg(test)]
mod test {
use super::*;
use crate::resp_header_to_buf;
use pingora_http::ResponseHeader;
fn gen_test_dict() -> Vec<u8> {
let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("samples/test");
train(path)
}
fn gen_test_header() -> ResponseHeader {
let mut header = ResponseHeader::build(200, None).unwrap();
header
.append_header("Date", "Thu, 23 Dec 2021 11:23:29 GMT")
.unwrap();
header
.append_header("Last-Modified", "Sat, 09 Oct 2021 22:41:34 GMT")
.unwrap();
header.append_header("Connection", "keep-alive").unwrap();
header.append_header("Vary", "Accept-encoding").unwrap();
header.append_header("Content-Encoding", "gzip").unwrap();
header
.append_header("Access-Control-Allow-Origin", "*")
.unwrap();
header
}
#[test]
fn test_ser_with_dict() {
let dict = gen_test_dict();
let serde = crate::HeaderSerde::new(Some(dict));
let serde_no_dict = crate::HeaderSerde::new(None);
let header = gen_test_header();
let compressed = serde.serialize(&header).unwrap();
let compressed_no_dict = serde_no_dict.serialize(&header).unwrap();
let mut buf = vec![];
let uncompressed = resp_header_to_buf(&header, &mut buf);
assert!(compressed.len() < uncompressed);
assert!(compressed.len() < compressed_no_dict.len());
}
#[test]
fn test_deserialize_with_dict() {
let dict = gen_test_dict();
let serde = crate::HeaderSerde::new(Some(dict));
let serde_no_dict = crate::HeaderSerde::new(None);
let header = gen_test_header();
let compressed = serde.serialize(&header).unwrap();
let compressed_no_dict = serde_no_dict.serialize(&header).unwrap();
let from_dict_header = serde.deserialize(&compressed).unwrap();
let from_no_dict_header = serde_no_dict.deserialize(&compressed_no_dict).unwrap();
assert_eq!(from_dict_header.status, from_no_dict_header.status);
assert_eq!(from_dict_header.headers, from_no_dict_header.headers);
}
#[test]
fn test_ser_de_with_dict() {
let dict = gen_test_dict();
let serde = crate::HeaderSerde::new(Some(dict));
let header = gen_test_header();
let compressed = serde.serialize(&header).unwrap();
let header2 = serde.deserialize(&compressed).unwrap();
assert_eq!(header.status, header2.status);
assert_eq!(header.headers, header2.headers);
}
}