Skip to content

Commit

Permalink
mention Read::take in the doc for the compressor and implement it for…
Browse files Browse the repository at this point in the history
… the nostd_io module
  • Loading branch information
KillingSpark committed Dec 23, 2024
1 parent 7be4381 commit d7643f4
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/encoding/frame_compressor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ impl<R: Read, W: Write, M: Matcher> FrameCompressor<R, W, M> {
///
/// This will repeatedly call [Read::read] on the source to fill up blocks until the source returns 0 on the read call.
/// Also [Write::write_all] will be called on the drain after each block has been encoded.
///
/// To avoid endlessly encoding from a potentially endless source (like a network socket) you can use the
/// [Read::take] function
pub fn compress(&mut self) {
self.match_generator.reset(self.compression_level);
let source = self.uncompressed_data.as_mut().unwrap();
Expand Down
44 changes: 44 additions & 0 deletions src/io_nostd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ pub trait Read {
}
Ok(())
}

fn take(self, limit: u64) -> Take<Self> where Self: Sized {
Take { inner: self, limit }
}
}

impl Read for &[u8] {
Expand Down Expand Up @@ -154,6 +158,46 @@ where
}
}

pub struct Take<R: Read> {
inner: R,
limit: u64,
}

impl<R: Read> Take<R> {
pub fn limit(&self) -> u64 {
self.limit
}

pub fn set_limit(&mut self, limit: u64) {
self.limit = limit;
}

pub fn get_ref(&self) -> &R {
&self.inner
}

pub fn get_mut(&mut self) -> &mut R {
&mut self.inner
}

pub fn into_inner(self) -> R {
self.inner
}
}

impl<R: Read> Read for Take<R> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
if self.limit == 0 {
return Ok(0);
}

let at_most = (self.limit as usize).min(buf.len());
let bytes = self.inner.read(&mut buf[..at_most])?;
self.limit -= bytes as u64;
Ok(bytes)
}
}

pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
fn flush(&mut self) -> Result<(), Error>;
Expand Down

0 comments on commit d7643f4

Please sign in to comment.