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