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 ///
9 /// TODO?: Upstream ManagedVec into the main `managed` crate?
10 pub struct ManagedVec<'a, 'b, T: 'a> {
11     buf: &'b mut ManagedSlice<'a, T>,
12     len: usize,
13 }
14 
15 impl<'a, 'b, T> ManagedVec<'a, 'b, T> {
new(buf: &'b mut ManagedSlice<'a, T>) -> Self16     pub fn new(buf: &'b mut ManagedSlice<'a, T>) -> Self {
17         ManagedVec { buf, len: 0 }
18     }
19 
clear(&mut self)20     pub fn clear(&mut self) {
21         match &mut self.buf {
22             ManagedSlice::Borrowed(_) => self.len = 0,
23             #[cfg(feature = "alloc")]
24             ManagedSlice::Owned(buf) => buf.clear(),
25         }
26     }
27 
push(&mut self, value: T) -> Result<(), CapacityError<T>>28     pub fn push(&mut self, value: T) -> Result<(), CapacityError<T>> {
29         match &mut self.buf {
30             ManagedSlice::Borrowed(buf) => {
31                 if self.len < buf.len() {
32                     buf[self.len] = value;
33                     self.len += 1;
34                     Ok(())
35                 } else {
36                     Err(CapacityError(value))
37                 }
38             }
39             #[cfg(feature = "alloc")]
40             ManagedSlice::Owned(buf) => {
41                 buf.push(value);
42                 Ok(())
43             }
44         }
45     }
46 }
47