| 1 | use std::io::IoSlice; |
| 2 | use std::ops::Deref; |
| 3 | use std::slice; |
| 4 | |
| 5 | pub struct IoBufs<'a, 'b>(&'b mut [IoSlice<'a>]); |
| 6 | |
| 7 | impl<'a, 'b> IoBufs<'a, 'b> { |
| 8 | pub fn new(slices: &'b mut [IoSlice<'a>]) -> Self { |
| 9 | IoBufs(slices) |
| 10 | } |
| 11 | |
| 12 | pub fn is_empty(&self) -> bool { |
| 13 | self.0.is_empty() |
| 14 | } |
| 15 | |
| 16 | pub fn advance(mut self, n: usize) -> IoBufs<'a, 'b> { |
| 17 | let mut to_remove = 0; |
| 18 | let mut remaining_len = n; |
| 19 | for slice in self.0.iter() { |
| 20 | if remaining_len < slice.len() { |
| 21 | break; |
| 22 | } else { |
| 23 | remaining_len -= slice.len(); |
| 24 | to_remove += 1; |
| 25 | } |
| 26 | } |
| 27 | self.0 = self.0.split_at_mut(to_remove).1; |
| 28 | if let Some(slice) = self.0.first_mut() { |
| 29 | let tail = &slice[remaining_len..]; |
| 30 | // Safety: recasts slice to the original lifetime |
| 31 | let tail = unsafe { slice::from_raw_parts(tail.as_ptr(), tail.len()) }; |
| 32 | *slice = IoSlice::new(tail); |
| 33 | } else if remaining_len != 0 { |
| 34 | panic!("advance past the end of the slice vector" ); |
| 35 | } |
| 36 | self |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl<'a, 'b> Deref for IoBufs<'a, 'b> { |
| 41 | type Target = [IoSlice<'a>]; |
| 42 | fn deref(&self) -> &[IoSlice<'a>] { |
| 43 | self.0 |
| 44 | } |
| 45 | } |
| 46 | |