sp-maybe-compressed-blob: reduce boilerplate code (#10814)

Signed-off-by: koushiro <koushiro.cqx@gmail.com>
This commit is contained in:
Qinxuan Chen
2022-02-08 16:52:20 +08:00
committed by GitHub
parent 2fb4258890
commit 1d62516fad
3 changed files with 9 additions and 16 deletions
+1
View File
@@ -9809,6 +9809,7 @@ dependencies = [
name = "sp-maybe-compressed-blob"
version = "4.1.0-dev"
dependencies = [
"thiserror",
"zstd",
]
@@ -11,4 +11,5 @@ documentation = "https://docs.rs/sp-maybe-compressed-blob"
readme = "README.md"
[dependencies]
thiserror = "1.0"
zstd = { version = "0.9.0", default-features = false }
@@ -18,7 +18,10 @@
//! Handling of blobs that may be compressed, based on an 8-byte magic identifier
//! at the head.
use std::{borrow::Cow, io::Read};
use std::{
borrow::Cow,
io::{Read, Write},
};
// An arbitrary prefix, that indicates a blob beginning with should be decompressed with
// Zstd compression.
@@ -34,25 +37,16 @@ const ZSTD_PREFIX: [u8; 8] = [82, 188, 83, 118, 70, 219, 142, 5];
pub const CODE_BLOB_BOMB_LIMIT: usize = 50 * 1024 * 1024;
/// A possible bomb was encountered.
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum Error {
/// Decoded size was too large, and the code payload may be a bomb.
#[error("Possible compression bomb encountered")]
PossibleBomb,
/// The compressed value had an invalid format.
#[error("Blob had invalid format")]
Invalid,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Error::PossibleBomb => write!(f, "Possible compression bomb encountered"),
Error::Invalid => write!(f, "Blob had invalid format"),
}
}
}
impl std::error::Error for Error {}
fn read_from_decoder(
decoder: impl Read,
blob_len: usize,
@@ -90,8 +84,6 @@ pub fn decompress(blob: &[u8], bomb_limit: usize) -> Result<Cow<[u8]>, Error> {
/// this will not compress the blob, as the decoder will not be able to be
/// able to differentiate it from a compression bomb.
pub fn compress(blob: &[u8], bomb_limit: usize) -> Option<Vec<u8>> {
use std::io::Write;
if blob.len() > bomb_limit {
return None
}
@@ -109,7 +101,6 @@ pub fn compress(blob: &[u8], bomb_limit: usize) -> Option<Vec<u8>> {
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
const BOMB_LIMIT: usize = 10;