djin_protocol/wire/middleware/
compression.rs

1//! A middleware for compressing all transmitted data.
2
3use crate::{wire, Error};
4use flate2;
5
6use std::io::prelude::*;
7use std::io::Cursor;
8
9/// Defines a compression algorithm.
10#[derive(Copy, Clone, Debug)]
11pub enum Algorithm
12{
13    /// The zlib compression algorithm.
14    ///
15    /// https://en.wikipedia.org/wiki/Zlib
16    Zlib,
17}
18
19/// Compression middleware.
20#[derive(Clone, Debug)]
21pub enum Compression
22{
23    /// No compression or decompression should be applied to the data.
24    Disabled,
25    /// Compression and decompression should be applied to the data.
26    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    /// Un-processes some data.
44    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