Skip to content

Commit

Permalink
implement Buf for IoSlice and BufMut for IoSliceMut
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmonstar committed Oct 16, 2019
1 parent 43ac8e5 commit fa9f479
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/buf/buf_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1016,6 +1016,30 @@ impl Buf for Option<[u8; 1]> {
}
}

impl<'a> Buf for IoSlice<'a> {
#[inline]
fn remaining(&self) -> usize {
self.len()
}

#[inline]
fn bytes(&self) -> &[u8] {
self
}

#[inline]
fn advance(&mut self, cnt: usize) {
//*self = IoSlice::new(&self[cnt..]);
*self = unsafe {
// Deref for IoSlice gives an anonymous lifetime,
// so we transmute it to actual lifetime it has, 'a.
//
// See https://github.com/rust-lang/rust/issues/62726#issuecomment-542826827
IoSlice::new(std::mem::transmute::<&[u8], &'a [u8]>(&self[cnt..]))
};
}
}

// 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) {}
22 changes: 22 additions & 0 deletions src/buf/buf_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1018,6 +1018,28 @@ impl BufMut for Vec<u8> {
}
}

impl<'a> BufMut for IoSliceMut<'a> {
#[inline]
fn remaining_mut(&self) -> usize {
self.len()
}

#[inline]
unsafe fn advance_mut(&mut self, cnt: usize) {
// DerefMut for IoSliceMut gives an anonymous lifetime,
// so we transmute it to actual lifetime it has, 'a.
//
// See https://github.com/rust-lang/rust/issues/62726#issuecomment-542826827
*self = IoSliceMut::new(std::mem::transmute::<&mut [u8], &'a mut [u8]>(&mut self[cnt..]))
}

#[inline]
unsafe fn bytes_mut(&mut self) -> &mut [u8] {
self
}

}

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

0 comments on commit fa9f479

Please sign in to comment.