Skip to content

Commit

Permalink
implement Buf for std::io::Cursor (#308)
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmonstar committed Nov 5, 2019
1 parent 96268a8 commit 856ed7c
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/buf/buf_impl.rs
Expand Up @@ -892,6 +892,39 @@ impl Buf for Option<[u8; 1]> {
}
}

#[cfg(feature = "std")]
impl<T: AsRef<[u8]>> Buf for std::io::Cursor<T> {
fn remaining(&self) -> usize {
let len = self.get_ref().as_ref().len();
let pos = self.position();

if pos >= len as u64 {
return 0;
}

len - pos as usize
}

fn bytes(&self) -> &[u8] {
let len = self.get_ref().as_ref().len();
let pos = self.position();

if pos >= len as u64 {
return &[];
}

&self.get_ref().as_ref()[pos as usize..]
}

fn advance(&mut self, cnt: usize) {
let pos = (self.position() as usize)
.checked_add(cnt).expect("overflow");

assert!(pos <= self.get_ref().as_ref().len());
self.set_position(pos as u64);
}
}

// The existence of this function makes the compiler catch if the Buf
// trait is "object-safe" or not.
fn _assert_trait_object(_b: &dyn Buf) {}

0 comments on commit 856ed7c

Please sign in to comment.