djin_protocol/wire/middleware/
compression.rs1use crate::{wire, Error};
4use flate2;
5
6use std::io::prelude::*;
7use std::io::Cursor;
8
9#[derive(Copy, Clone, Debug)]
11pub enum Algorithm
12{
13 Zlib,
17}
18
19#[derive(Clone, Debug)]
21pub enum Compression
22{
23 Disabled,
25 Enabled(Algorithm),
27}
28
29impl wire::Middleware for Compression
30{
31 fn encode_data(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
32 match *self {
33 Compression::Enabled(algorithm) => match algorithm {
34 Algorithm::Zlib => {
35 let e = flate2::write::ZlibEncoder::new(data, flate2::Compression::best());
36 Ok(e.finish()?)
37 },
38 },
39 Compression::Disabled => Ok(data),
40 }
41 }
42
43 fn decode_data(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
45 match *self {
46 Compression::Enabled(algorithm) => match algorithm {
47 Algorithm::Zlib => {
48 let d = flate2::read::ZlibDecoder::new(Cursor::new(data));
49 let bytes: Result<Vec<u8>, _> = d.bytes().collect();
50 Ok(bytes?)
51 },
52 },
53 Compression::Disabled => Ok(data),
54 }
55 }
56}
57