protocol/wire/middleware/
compression.rs

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