1 use managed::ManagedSlice; 2 3 /// Error value indicating insufficient capacity. 4 #[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] 5 pub struct CapacityError<Element>(pub Element); 6 7 /// Wraps a ManagedSlice in a vec-like interface. 8 pub struct ManagedVec<'a, 'b, T: 'a> { 9 buf: &'b mut ManagedSlice<'a, T>, 10 len: usize, 11 } 12 13 impl<'a, 'b, T> ManagedVec<'a, 'b, T> { new(buf: &'b mut ManagedSlice<'a, T>) -> Self14 pub fn new(buf: &'b mut ManagedSlice<'a, T>) -> Self { 15 ManagedVec { buf, len: 0 } 16 } 17 clear(&mut self)18 pub fn clear(&mut self) { 19 // While it's very tempting to just call `Vec::clear` in the `Owned` case, doing 20 // so would modify the length of the underlying `ManagedSlice`, which isn't 21 // desirable. 22 self.len = 0; 23 } 24 push(&mut self, value: T) -> Result<(), CapacityError<T>>25 pub fn push(&mut self, value: T) -> Result<(), CapacityError<T>> { 26 if self.len < self.buf.len() { 27 self.buf[self.len] = value; 28 self.len += 1; 29 Ok(()) 30 } else { 31 match &mut self.buf { 32 ManagedSlice::Borrowed(_) => Err(CapacityError(value)), 33 #[cfg(feature = "alloc")] 34 ManagedSlice::Owned(buf) => { 35 buf.push(value); 36 Ok(()) 37 } 38 } 39 } 40 } 41 as_slice<'c: 'b>(&'c self) -> &'b [T]42 pub fn as_slice<'c: 'b>(&'c self) -> &'b [T] { 43 &self.buf[..self.len] 44 } 45 } 46