use alloc::rc::Rc; use alloc::vec; use core::mem; use core::panic::RefUnwindSafe; use core::slice; pub(crate) struct RcVec { inner: Rc>, } pub(crate) struct RcVecBuilder { inner: Vec, } pub(crate) struct RcVecMut<'a, T> { inner: &'a mut Vec, } #[derive(Clone)] pub(crate) struct RcVecIntoIter { inner: vec::IntoIter, } impl RcVec { pub fn is_empty(&self) -> bool { self.inner.is_empty() } pub fn len(&self) -> usize { self.inner.len() } pub fn iter(&self) -> slice::Iter { self.inner.iter() } pub fn make_mut(&mut self) -> RcVecMut where T: Clone, { RcVecMut { inner: Rc::make_mut(&mut self.inner), } } pub fn get_mut(&mut self) -> Option> { let inner = Rc::get_mut(&mut self.inner)?; Some(RcVecMut { inner }) } pub fn make_owned(mut self) -> RcVecBuilder where T: Clone, { let vec = if let Some(owned) = Rc::get_mut(&mut self.inner) { mem::take(owned) } else { Vec::clone(&self.inner) }; RcVecBuilder { inner: vec } } } impl RcVecBuilder { pub fn new() -> Self { RcVecBuilder { inner: Vec::new() } } pub fn with_capacity(cap: usize) -> Self { RcVecBuilder { inner: Vec::with_capacity(cap), } } pub fn push(&mut self, element: T) { self.inner.push(element); } pub fn extend(&mut self, iter: impl IntoIterator) { self.inner.extend(iter); } pub fn as_mut(&mut self) -> RcVecMut { RcVecMut { inner: &mut self.inner, } } pub fn build(self) -> RcVec { RcVec { inner: Rc::new(self.inner), } } } impl<'a, T> RcVecMut<'a, T> { pub fn push(&mut self, element: T) { self.inner.push(element); } pub fn extend(&mut self, iter: impl IntoIterator) { self.inner.extend(iter); } pub fn pop(&mut self) -> Option { self.inner.pop() } pub fn as_mut(&mut self) -> RcVecMut { RcVecMut { inner: self.inner } } } impl Clone for RcVec { fn clone(&self) -> Self { RcVec { inner: Rc::clone(&self.inner), } } } impl IntoIterator for RcVecBuilder { type Item = T; type IntoIter = RcVecIntoIter; fn into_iter(self) -> Self::IntoIter { RcVecIntoIter { inner: self.inner.into_iter(), } } } impl Iterator for RcVecIntoIter { type Item = T; fn next(&mut self) -> Option { self.inner.next() } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl RefUnwindSafe for RcVec where T: RefUnwindSafe {}