Skip to content

Commit

Permalink
FIX: Clippy offenses pass 1
Browse files Browse the repository at this point in the history
  • Loading branch information
bsodmike committed Sep 8, 2024
1 parent a943081 commit 188b5eb
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 28 deletions.
2 changes: 1 addition & 1 deletion examples/read_limited.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn main() -> LimitReaderResult<()> {
);

let data = limit_reader.buffer();
let text = String::from_utf8(data[..bytes_read].to_vec())?;
let text = String::from_utf8(data[..(bytes_read as usize)].to_vec())?;

println!("First line from README: {}", &text);

Expand Down
5 changes: 5 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ use std::{
};

/// Boxed error, a ptr to the Error via dynamic dispatch allocated on the heap at run time.
#[allow(clippy::module_name_repetitions)]
pub type BoxError = Box<dyn StdError + Send + Sync>;

/// Default error type for create.
#[allow(clippy::module_name_repetitions)]
pub type LimitReaderError = Error;

/// Error type
Expand All @@ -19,6 +21,8 @@ pub struct Error {

#[derive(Debug)]
#[non_exhaustive]
#[allow(clippy::module_name_repetitions)]
#[allow(clippy::enum_variant_names)]
pub enum ErrorKind {
IoError,
Utf8Error,
Expand All @@ -27,6 +31,7 @@ pub enum ErrorKind {

impl ErrorKind {
pub(crate) fn as_str(&self) -> &'static str {
#[allow(clippy::enum_glob_use)]
use ErrorKind::*;
// tidy-alphabetical-start
match *self {
Expand Down
44 changes: 26 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//!
//! Exposes [`LimitReader`] which is a limit reader, that protects against zip-bombs and other nefarious activities.
//!
//! This crate is heavily inspired by Jon Gjengset's "Crust of Rust" episode on the inner workings of git on YouTube (<https://youtu.be/u0VotuGzD_w?si=oIuV9CITSWHJXKBu&t=3503>) and mitigrating Zip-bombs.
//! This crate is heavily inspired by Jon Gjengset's "Crust of Rust" episode on the inner workings of git on `YouTube` (<https://youtu.be/u0VotuGzD_w?si=oIuV9CITSWHJXKBu&t=3503>) and mitigrating Zip-bombs.

use derive_builder::Builder;
use error::LimitReaderError;
Expand Down Expand Up @@ -37,7 +37,7 @@ pub mod prelude {
/// The [LimitReader] reads into `buf` which is held within the record struct.
pub struct LimitReader {
buf: [u8; Self::DEFAULT_BUF_SIZE],
expected_size: usize,
expected_size: u64,
decode_zlib: bool,
decode_gzip: bool,
}
Expand All @@ -56,20 +56,20 @@ impl LimitReader {
/// Create a new [`LimitReader`] with a [`LimitReader::DEFAULT_BUF_SIZE`] for the limit-readers max threshold.
pub fn new() -> Self {
Self {
buf: [0; Self::DEFAULT_BUF_SIZE],
expected_size: Self::DEFAULT_BUF_SIZE - 1,
buf: [0; Self::DEFAULT_BUF_SIZE as usize],
expected_size: (Self::DEFAULT_BUF_SIZE - 1) as u64,
decode_zlib: false,
decode_gzip: false,
}
}

/// Return a reference to the internal buffer.
pub fn buffer(&self) -> &[u8; Self::DEFAULT_BUF_SIZE] {
pub fn buffer(&self) -> &[u8; Self::DEFAULT_BUF_SIZE as usize] {
&self.buf
}

/// Increase the allowed limit on the [`LimitReader`]
pub fn limit(&mut self, limit: usize) -> &mut Self {
pub fn limit(&mut self, limit: u64) -> &mut Self {
self.expected_size = limit;

self
Expand Down Expand Up @@ -110,6 +110,10 @@ impl LimitReader {
}

/// Given an accessible source file, this will automatically limit the contents read to the size of the buffer itself. This will silently truncate read bytes into the buffer, without raising an error.
///
/// # Errors
///
/// FIXME
pub fn read_limited(&mut self, source: PathBuf) -> Result<LimitReaderOutput> {
let source_bytes = std::fs::metadata(&source)?.len();
let f = std::fs::File::open(source)?;
Expand Down Expand Up @@ -153,18 +157,21 @@ pub struct LimitReaderOutput {

impl LimitReaderOutput {
/// Return bytes read by the underlying reader.
pub fn bytes_read(&self) -> usize {
self.bytes_read as usize
#[must_use]
pub fn bytes_read(&self) -> u64 {
self.bytes_read
}

/// Size in bytes of the underlying file accessible to the reader.
pub fn source_size(&self) -> usize {
self.source_size as usize
#[must_use]
pub fn source_size(&self) -> u64 {
self.source_size
}

/// Unread bytes (from the underlying file accessible to the reader).
pub fn bytes_remaining(&self) -> usize {
(self.source_size - self.bytes_read) as usize
#[must_use]
pub fn bytes_remaining(&self) -> u64 {
self.source_size - self.bytes_read
}
}

Expand Down Expand Up @@ -243,12 +250,12 @@ mod tests {
writeln!(file, "{}", &text).unwrap();

let mut limit_reader = LimitReader::new();
let limit = 8_usize;
let limit = 8_u64;
limit_reader.limit(limit);

match limit_reader.read(file_path) {
Ok(read_size) => {
assert!(read_size == limit);
assert!(read_size == limit.try_into().unwrap());
}
Err(err) => {
assert_eq!("Error: too many bytes", err.to_string());
Expand Down Expand Up @@ -325,7 +332,7 @@ mod tests {
writeln!(file, "{}", &text).unwrap();

let mut limit_reader = LimitReader::new();
let limit = 8_usize;
let limit = 8_u64;
limit_reader.limit(limit);

match limit_reader.read_limited(file_path.clone()) {
Expand All @@ -350,10 +357,11 @@ mod tests {
Ok(reader_output) => {
let bytes_read = reader_output.bytes_read();
let persisted_text =
String::from_utf8(limit_reader.buf[..bytes_read].to_vec()).unwrap();
String::from_utf8(limit_reader.buf[..(bytes_read as usize)].to_vec())
.unwrap();
assert_eq!(
persisted_text,
format!("{}", &text[..bytes_read]).to_string()
format!("{}", &text[..(bytes_read as usize)]).to_string()
);
}
Err(_) => unreachable!(),
Expand All @@ -373,7 +381,7 @@ mod tests {
writeln!(file, "{}", &text).unwrap();

let mut limit_reader = LimitReader::new();
let limit = 8_usize;
let limit = 8_u64;
limit_reader
// RA block
.limit(limit)
Expand Down
22 changes: 13 additions & 9 deletions src/readable.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[allow(clippy::wildcard_imports)]
use super::*;

pub struct MyBufReader<Z: Read>(pub Z);
Expand All @@ -13,6 +14,7 @@ pub trait Readable {
}

pub(crate) mod falible {
#[allow(clippy::wildcard_imports)]
use super::*;

impl<R> Readable for LimitReaderFallible<R>
Expand All @@ -29,15 +31,15 @@ pub(crate) mod falible {
R: Read,
{
reader: R,
limit: usize,
limit: u64,
reader_count: usize,
}

impl<R> LimitReaderFallible<R>
where
R: Read,
{
pub fn new(r: R, limit: usize) -> Self {
pub fn new(r: R, limit: u64) -> Self {
Self {
reader: r,
limit,
Expand All @@ -50,15 +52,16 @@ pub(crate) mod falible {
where
R: Read,
{
#[allow(clippy::cast_possible_truncation)]
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
// NOTE: using +1 in the range below trips the error.
buf = &mut buf[..self.limit + 1];
buf = &mut buf[..=(self.limit as usize)];

let bytes_read = self.reader.read(buf)?;
if bytes_read > self.limit {
if bytes_read > self.limit as usize {
return Err(io::Error::new(io::ErrorKind::Other, "too many bytes"));
}
self.limit -= bytes_read;
self.limit -= bytes_read as u64;
self.reader_count += 1;

Ok(bytes_read)
Expand All @@ -78,6 +81,7 @@ pub(crate) mod falible {
}

pub(crate) mod infalible {
#[allow(clippy::wildcard_imports)]
use super::*;

impl<R> Readable for LimitReaderInfallible<R>
Expand All @@ -94,15 +98,15 @@ pub(crate) mod infalible {
R: Read,
{
reader: R,
limit: usize,
limit: u64,
reader_count: usize,
}

impl<R> LimitReaderInfallible<R>
where
R: Read,
{
pub fn new(r: R, limit: usize) -> Self {
pub fn new(r: R, limit: u64) -> Self {
Self {
reader: r,
limit,
Expand All @@ -116,9 +120,9 @@ pub(crate) mod infalible {
R: Read,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let max_read = self.limit.min(buf.len()); // min of limit and buf.len()
let max_read = self.limit.min(buf.len() as u64); // min of limit and buf.len()

let bytes_read = self.reader.read(&mut buf[..max_read])?;
let bytes_read = self.reader.read(&mut buf[..max_read as usize])?;
self.reader_count += 1;

Ok(bytes_read)
Expand Down

0 comments on commit 188b5eb

Please sign in to comment.