Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
sp-maybe-compressed-blob: reduce boilerplate code (#10814)
Browse files Browse the repository at this point in the history
Signed-off-by: koushiro <koushiro.cqx@gmail.com>
  • Loading branch information
koushiro authored Feb 8, 2022
1 parent 57bf92e commit c8bef76
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 16 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions primitives/maybe-compressed-blob/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
23 changes: 7 additions & 16 deletions primitives/maybe-compressed-blob/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
Expand All @@ -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;

Expand Down

0 comments on commit c8bef76

Please sign in to comment.