1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright 2021-2022 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or MIT.

//! Compression utility and types.

use std::str::FromStr;

use crate::error::Result;

/// Different compression type
/// allowed and their u8 representation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum CompressionType {
	NoCompression = 0,
	Lz4 = 1,
	Snappy = 2,
}

/// Compression implementation.
#[derive(Debug)]
pub struct Compress {
	inner: Compressor,
	pub threshold: u32,
}

impl Compress {
	pub fn new(kind: CompressionType, threshold: u32) -> Self {
		Compress { inner: kind.into(), threshold }
	}
}

pub const NO_COMPRESSION: Compress =
	Compress { inner: Compressor::NoCompression(NoCompression), threshold: u32::MAX };

#[derive(Debug)]
enum Compressor {
	NoCompression(NoCompression),
	Lz4(lz4::Lz4),
	Snappy(snappy::Snappy),
}

impl From<u8> for CompressionType {
	fn from(comp_type: u8) -> Self {
		match comp_type {
			a if a == CompressionType::NoCompression as u8 => CompressionType::NoCompression,
			a if a == CompressionType::Lz4 as u8 => CompressionType::Lz4,
			a if a == CompressionType::Snappy as u8 => CompressionType::Snappy,
			_ => panic!("Unknown compression."),
		}
	}
}

impl From<CompressionType> for Compressor {
	fn from(comp_type: CompressionType) -> Self {
		match comp_type {
			CompressionType::NoCompression => Compressor::NoCompression(NoCompression),
			CompressionType::Lz4 => Compressor::Lz4(lz4::Lz4::new()),
			CompressionType::Snappy => Compressor::Snappy(snappy::Snappy::new()),
			#[allow(unreachable_patterns)]
			_ => unimplemented!("Missing compression implementation."),
		}
	}
}

impl From<&Compress> for CompressionType {
	fn from(compression: &Compress) -> Self {
		match compression.inner {
			Compressor::NoCompression(_) => CompressionType::NoCompression,
			Compressor::Lz4(_) => CompressionType::Lz4,
			Compressor::Snappy(_) => CompressionType::Snappy,
			#[allow(unreachable_patterns)]
			_ => unimplemented!("Missing compression implementation."),
		}
	}
}

impl FromStr for CompressionType {
	type Err = crate::Error;

	fn from_str(s: &str) -> Result<Self> {
		match s.to_lowercase().as_str() {
			"none" => Ok(CompressionType::NoCompression),
			"lz4" => Ok(CompressionType::Lz4),
			"snappy" => Ok(CompressionType::Snappy),
			_ => Err(crate::Error::Compression),
		}
	}
}

impl Compress {
	pub fn compress(&self, buf: &[u8]) -> Vec<u8> {
		match &self.inner {
			Compressor::NoCompression(inner) => inner.compress(buf),
			Compressor::Lz4(inner) => inner.compress(buf),
			Compressor::Snappy(inner) => inner.compress(buf),
			#[allow(unreachable_patterns)]
			_ => unimplemented!("Missing compression implementation."),
		}
	}

	pub fn decompress(&self, buf: &[u8]) -> Result<Vec<u8>> {
		Ok(match &self.inner {
			Compressor::NoCompression(inner) => inner.decompress(buf)?,
			Compressor::Lz4(inner) => inner.decompress(buf)?,
			Compressor::Snappy(inner) => inner.decompress(buf)?,
			#[allow(unreachable_patterns)]
			_ => unimplemented!("Missing compression implementation."),
		})
	}
}

#[derive(Debug)]
struct NoCompression;

impl NoCompression {
	fn compress(&self, buf: &[u8]) -> Vec<u8> {
		buf.to_vec()
	}

	fn decompress(&self, buf: &[u8]) -> Result<Vec<u8>> {
		Ok(buf.to_vec())
	}
}

mod lz4 {
	use crate::error::{Error, Result};

	#[derive(Debug)]
	pub(super) struct Lz4;

	impl Lz4 {
		pub(super) fn new() -> Self {
			Lz4
		}

		pub(super) fn compress(&self, buf: &[u8]) -> Vec<u8> {
			lz4::block::compress(buf, Some(lz4::block::CompressionMode::DEFAULT), true).unwrap()
		}

		pub(super) fn decompress(&self, buf: &[u8]) -> Result<Vec<u8>> {
			lz4::block::decompress(buf, None).map_err(|_| Error::Compression)
		}
	}
}

mod snappy {
	use crate::error::{Error, Result};
	use std::io::{Read, Write};

	#[derive(Debug)]
	pub(super) struct Snappy;

	impl Snappy {
		pub(super) fn new() -> Self {
			Snappy
		}

		pub(super) fn compress(&self, value: &[u8]) -> Vec<u8> {
			let mut buf = Vec::with_capacity(value.len() << 3);
			{
				let mut encoder = snap::write::FrameEncoder::new(&mut buf);
				encoder.write_all(value).expect("Expect in memory write to succeed.");
			}
			buf
		}

		pub(super) fn decompress(&self, value: &[u8]) -> Result<Vec<u8>> {
			let mut buf = Vec::with_capacity(value.len());
			let mut decoder = snap::read::FrameDecoder::new(value);
			decoder.read_to_end(&mut buf).map_err(|_| Error::Compression)?;
			Ok(buf)
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_compression_interfaces() {
		let original = vec![42; 100];
		let types =
			vec![CompressionType::NoCompression, CompressionType::Snappy, CompressionType::Lz4];

		for compression_type in types {
			let compress = Compress::new(compression_type, 0);
			let v = compress.compress(&original[..]);
			assert!(v.len() <= 100);
			let round_tripped = compress.decompress(&v[..]).unwrap();
			assert_eq!(original, round_tripped);
		}
	}

	#[test]
	fn test_compression_from_str() {
		let correct_cases = [
			("lz4", CompressionType::Lz4),
			("snappy", CompressionType::Snappy),
			("none", CompressionType::NoCompression),
			("SNAPPy", CompressionType::Snappy),
		];

		for (input, expected_compression) in correct_cases {
			assert_eq!(expected_compression, CompressionType::from_str(input).unwrap());
		}

		let invalid_cases = ["lz5", "", "cthulhu"];

		for input in invalid_cases {
			assert!(CompressionType::from_str(input).is_err());
		}
	}
}