Skip to content

Commit 20a8ff6

Browse files
koushiroark0f
authored andcommitted
sp-maybe-compressed-blob: reduce boilerplate code (paritytech#10814)
Signed-off-by: koushiro <[email protected]>
1 parent e02a826 commit 20a8ff6

File tree

3 files changed

+9
-16
lines changed

3 files changed

+9
-16
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

primitives/maybe-compressed-blob/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ documentation = "https://docs.rs/sp-maybe-compressed-blob"
1111
readme = "README.md"
1212

1313
[dependencies]
14+
thiserror = "1.0"
1415
zstd = { version = "0.9.0", default-features = false }

primitives/maybe-compressed-blob/src/lib.rs

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
//! Handling of blobs that may be compressed, based on an 8-byte magic identifier
1919
//! at the head.
2020
21-
use std::{borrow::Cow, io::Read};
21+
use std::{
22+
borrow::Cow,
23+
io::{Read, Write},
24+
};
2225

2326
// An arbitrary prefix, that indicates a blob beginning with should be decompressed with
2427
// Zstd compression.
@@ -34,25 +37,16 @@ const ZSTD_PREFIX: [u8; 8] = [82, 188, 83, 118, 70, 219, 142, 5];
3437
pub const CODE_BLOB_BOMB_LIMIT: usize = 50 * 1024 * 1024;
3538

3639
/// A possible bomb was encountered.
37-
#[derive(Debug, Clone, PartialEq)]
40+
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
3841
pub enum Error {
3942
/// Decoded size was too large, and the code payload may be a bomb.
43+
#[error("Possible compression bomb encountered")]
4044
PossibleBomb,
4145
/// The compressed value had an invalid format.
46+
#[error("Blob had invalid format")]
4247
Invalid,
4348
}
4449

45-
impl std::fmt::Display for Error {
46-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
47-
match *self {
48-
Error::PossibleBomb => write!(f, "Possible compression bomb encountered"),
49-
Error::Invalid => write!(f, "Blob had invalid format"),
50-
}
51-
}
52-
}
53-
54-
impl std::error::Error for Error {}
55-
5650
fn read_from_decoder(
5751
decoder: impl Read,
5852
blob_len: usize,
@@ -90,8 +84,6 @@ pub fn decompress(blob: &[u8], bomb_limit: usize) -> Result<Cow<[u8]>, Error> {
9084
/// this will not compress the blob, as the decoder will not be able to be
9185
/// able to differentiate it from a compression bomb.
9286
pub fn compress(blob: &[u8], bomb_limit: usize) -> Option<Vec<u8>> {
93-
use std::io::Write;
94-
9587
if blob.len() > bomb_limit {
9688
return None
9789
}
@@ -109,7 +101,6 @@ pub fn compress(blob: &[u8], bomb_limit: usize) -> Option<Vec<u8>> {
109101
#[cfg(test)]
110102
mod tests {
111103
use super::*;
112-
use std::io::Write;
113104

114105
const BOMB_LIMIT: usize = 10;
115106

0 commit comments

Comments
 (0)