From 9a06fe69f9690ff475003e7c6d293d16e20d9317 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 4 Nov 2019 17:12:27 -0800 Subject: [PATCH] implement Buf for std::io::Cursor --- src/buf/buf_impl.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/buf/buf_impl.rs b/src/buf/buf_impl.rs index 99ecb545b..9ba12696a 100644 --- a/src/buf/buf_impl.rs +++ b/src/buf/buf_impl.rs @@ -892,6 +892,39 @@ impl Buf for Option<[u8; 1]> { } } +#[cfg(feature = "std")] +impl> Buf for std::io::Cursor { + 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) {}