1use core::mem;
2use core::slice;
3use std::panic::RefUnwindSafe;
4use std::rc::Rc;
5use std::vec;
6
7pub(crate) struct RcVec<T> {
8 inner: Rc<Vec<T>>,
9}
10
11pub(crate) struct RcVecBuilder<T> {
12 inner: Vec<T>,
13}
14
15pub(crate) struct RcVecMut<'a, T> {
16 inner: &'a mut Vec<T>,
17}
18
19#[derive(Clone)]
20pub(crate) struct RcVecIntoIter<T> {
21 inner: vec::IntoIter<T>,
22}
23
24impl<T> RcVec<T> {
25 pub fn is_empty(&self) -> bool {
26 self.inner.is_empty()
27 }
28
29 pub fn len(&self) -> usize {
30 self.inner.len()
31 }
32
33 pub fn iter(&self) -> slice::Iter<T> {
34 self.inner.iter()
35 }
36
37 pub fn make_mut(&mut self) -> RcVecMut<T>
38 where
39 T: Clone,
40 {
41 RcVecMut {
42 inner: Rc::make_mut(&mut self.inner),
43 }
44 }
45
46 pub fn get_mut(&mut self) -> Option<RcVecMut<T>> {
47 let inner = Rc::get_mut(&mut self.inner)?;
48 Some(RcVecMut { inner })
49 }
50
51 pub fn make_owned(mut self) -> RcVecBuilder<T>
52 where
53 T: Clone,
54 {
55 let vec = if let Some(owned) = Rc::get_mut(&mut self.inner) {
56 mem::replace(owned, Vec::new())
57 } else {
58 Vec::clone(&self.inner)
59 };
60 RcVecBuilder { inner: vec }
61 }
62}
63
64impl<T> RcVecBuilder<T> {
65 pub fn new() -> Self {
66 RcVecBuilder { inner: Vec::new() }
67 }
68
69 pub fn with_capacity(cap: usize) -> Self {
70 RcVecBuilder {
71 inner: Vec::with_capacity(cap),
72 }
73 }
74
75 pub fn push(&mut self, element: T) {
76 self.inner.push(element);
77 }
78
79 pub fn extend(&mut self, iter: impl IntoIterator<Item = T>) {
80 self.inner.extend(iter);
81 }
82
83 pub fn as_mut(&mut self) -> RcVecMut<T> {
84 RcVecMut {
85 inner: &mut self.inner,
86 }
87 }
88
89 pub fn build(self) -> RcVec<T> {
90 RcVec {
91 inner: Rc::new(self.inner),
92 }
93 }
94}
95
96impl<'a, T> RcVecMut<'a, T> {
97 pub fn push(&mut self, element: T) {
98 self.inner.push(element);
99 }
100
101 pub fn extend(&mut self, iter: impl IntoIterator<Item = T>) {
102 self.inner.extend(iter);
103 }
104
105 pub fn pop(&mut self) -> Option<T> {
106 self.inner.pop()
107 }
108
109 pub fn as_mut(&mut self) -> RcVecMut<T> {
110 RcVecMut { inner: self.inner }
111 }
112}
113
114impl<T> Clone for RcVec<T> {
115 fn clone(&self) -> Self {
116 RcVec {
117 inner: Rc::clone(&self.inner),
118 }
119 }
120}
121
122impl<T> IntoIterator for RcVecBuilder<T> {
123 type Item = T;
124 type IntoIter = RcVecIntoIter<T>;
125
126 fn into_iter(self) -> Self::IntoIter {
127 RcVecIntoIter {
128 inner: self.inner.into_iter(),
129 }
130 }
131}
132
133impl<T> Iterator for RcVecIntoIter<T> {
134 type Item = T;
135
136 fn next(&mut self) -> Option<Self::Item> {
137 self.inner.next()
138 }
139
140 fn size_hint(&self) -> (usize, Option<usize>) {
141 self.inner.size_hint()
142 }
143}
144
145impl<T> RefUnwindSafe for RcVec<T> where T: RefUnwindSafe {}
146