paged_collections/concurrent/vec.rs
1//! A stable-address vector with shared appends and exclusive editing.
2
3use core::fmt;
4use core::iter::{Flatten, FusedIterator};
5use core::ops::{Index, IndexMut};
6
7use super::append::{AppendLog, DenseIter, PagesMut};
8use crate::page::DEFAULT_PAGE;
9use crate::paged_vec::PagedVec;
10
11/// A paged vector that supports appending through shared references.
12///
13/// Each push claims a distinct index and publishes its value without waiting
14/// for earlier writers. Existing elements keep their addresses while shared.
15/// [`get`](Self::get) can see every completed push, including values beyond
16/// the hole-free prefix reported by [`len`](Self::len). Iteration and page
17/// slices snapshot that prefix when called. When no push is in flight,
18/// `len() == reserved_len()`.
19///
20/// Removing, moving or mutating elements requires exclusive access. Pages
21/// stay allocated for reuse until [`shrink_to_fit`](Self::shrink_to_fit) or
22/// destruction. Uses `core` and `alloc` only.
23/// `Send` requires `T: Send`; `Sync` requires `T: Send + Sync`.
24pub struct ConcurrentPagedVec<T, const PAGE: usize = DEFAULT_PAGE> {
25 log: AppendLog<T, PAGE>,
26}
27
28// SAFETY: moving the vector transfers all owned cells and their destruction;
29// references into it cannot outlive their borrow.
30unsafe impl<T: Send, const PAGE: usize> Send for ConcurrentPagedVec<T, PAGE> {}
31// SAFETY: the append log gives each writer a distinct slot and publishes
32// immutable values; readers acquire publication and removal is exclusive.
33unsafe impl<T: Send + Sync, const PAGE: usize> Sync for ConcurrentPagedVec<T, PAGE> {}
34
35impl<T, const PAGE: usize> ConcurrentPagedVec<T, PAGE> {
36 /// Number of elements per page.
37 pub const PAGE: usize = PAGE;
38
39 /// Creates an empty vector without allocating.
40 ///
41 /// # Panics
42 ///
43 /// Panics if `PAGE` is zero or a page allocation would exceed `isize::MAX`.
44 pub fn new() -> Self {
45 Self {
46 log: AppendLog::new(),
47 }
48 }
49
50 /// Appends `value` and returns its distinct index.
51 ///
52 /// Does not wait for an earlier writer. No user code runs between claim
53 /// and publication, so a panic cannot leave a claimed, unwritten slot.
54 ///
55 /// # Panics
56 ///
57 /// Panics on length or allocation capacity overflow; allocation can fail.
58 pub fn push(&self, value: T) -> usize {
59 self.log
60 .push(value, usize::MAX)
61 .unwrap_or_else(|_| panic!("ConcurrentPagedVec length overflow"))
62 }
63
64 /// Appends every item with an individual [`push`](Self::push).
65 /// Other writers may interleave their values. If iteration panics, values
66 /// already pushed remain visible and no reservation is left unwritten.
67 pub fn push_all(&self, iter: impl IntoIterator<Item = T>) {
68 for value in iter {
69 self.push(value);
70 }
71 }
72
73 /// The element at `index`, once its push has published it.
74 /// This can return a value beyond [`len`](Self::len).
75 pub fn get(&self, index: usize) -> Option<&T> {
76 self.log.get(index)
77 }
78
79 /// Length of the hole-free, written prefix.
80 /// Can briefly lag behind completed pushes while an earlier push is in
81 /// flight. Exact, and equal to [`reserved_len`](Self::reserved_len),
82 /// when no push is in flight.
83 pub fn len(&self) -> usize {
84 self.log.len()
85 }
86
87 /// Whether the hole-free prefix is empty; subject to the lag of `len`.
88 pub fn is_empty(&self) -> bool {
89 self.len() == 0
90 }
91
92 /// Number of claimed positions, including writes still in flight.
93 /// This count does not prove that any particular element is readable.
94 pub fn reserved_len(&self) -> usize {
95 self.log.reserved_len()
96 }
97
98 /// Iterates over a snapshot of the committed prefix in index order.
99 pub fn iter(&self) -> DenseIter<'_, T, PAGE> {
100 self.log.iter()
101 }
102
103 /// Nonempty slices of a snapshot of the committed prefix, in page order.
104 /// Every slice except the last contains `PAGE` elements.
105 pub fn pages(
106 &self,
107 ) -> impl DoubleEndedIterator<Item = &[T]> + ExactSizeIterator + FusedIterator {
108 self.log.pages()
109 }
110
111 /// Mutable access to an element under exclusive access.
112 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
113 self.log.get_mut(index)
114 }
115
116 /// Iterates mutably over all elements, in index order.
117 pub fn iter_mut(&mut self) -> VecIterMut<'_, T> {
118 VecIterMut::new(&mut self.log)
119 }
120
121 /// Nonempty mutable page slices, in index order.
122 ///
123 /// The iterator is `Send` only if `T` is:
124 ///
125 /// ```
126 /// use paged_collections::concurrent::ConcurrentPagedVec;
127 /// let mut vector = ConcurrentPagedVec::<u32, 2>::new();
128 /// vector.push(0);
129 /// std::thread::scope(|scope| {
130 /// let mut pages = vector.pages_mut();
131 /// scope.spawn(move || pages.next().unwrap()[0] = 1);
132 /// });
133 /// assert_eq!(vector[0], 1);
134 /// ```
135 ///
136 /// ```compile_fail
137 /// use paged_collections::concurrent::ConcurrentPagedVec;
138 /// use std::{cell::Cell, rc::Rc};
139 /// let mut vector = ConcurrentPagedVec::<Rc<Cell<u32>>, 2>::new();
140 /// vector.push(Rc::new(Cell::new(0)));
141 /// std::thread::scope(|scope| {
142 /// let mut pages = vector.pages_mut();
143 /// scope.spawn(move || pages.next().unwrap()[0].set(1));
144 /// });
145 /// ```
146 pub fn pages_mut(&mut self) -> impl Iterator<Item = &mut [T]> {
147 self.log.pages_mut()
148 }
149
150 /// Removes and returns the last element. Keeps allocated pages.
151 pub fn pop(&mut self) -> Option<T> {
152 self.log.pop()
153 }
154
155 /// Drops elements from the back until at most `len` remain. Keeps pages.
156 /// If a destructor panics, that element is gone and earlier ones remain.
157 pub fn truncate(&mut self, len: usize) {
158 self.log.truncate(len);
159 }
160
161 /// Drops every element and clears readiness for subsequent reuse.
162 /// Keeps allocated pages; destructor panics behave as in `truncate`.
163 pub fn clear(&mut self) {
164 self.log.clear();
165 }
166
167 /// Frees pages wholly beyond the end of the vector, keeping directory chunks.
168 /// Existing elements keep their addresses. Shared appends can allocate the
169 /// released pages again.
170 pub fn shrink_to_fit(&mut self) {
171 self.log.shrink_to_fit();
172 }
173
174 /// Clones the committed prefix into a plain [`PagedVec`] in O(prefix length).
175 /// Like [`len`](Self::len) and [`iter`](Self::iter), this can omit
176 /// completed pushes beyond an earlier unpublished reservation. The
177 /// prefix forms a valid plain vector.
178 pub fn snapshot(&self) -> PagedVec<T, PAGE>
179 where
180 T: Clone,
181 {
182 self.iter().cloned().collect()
183 }
184
185 /// Moves the elements into a plain vector in index order, in O(len).
186 /// Element addresses can change; no cloning is required.
187 pub fn into_inner(self) -> PagedVec<T, PAGE> {
188 self.log.into_inner()
189 }
190}
191
192impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentPagedVec<T, PAGE> {
193 type Item = &'a T;
194 type IntoIter = DenseIter<'a, T, PAGE>;
195
196 fn into_iter(self) -> Self::IntoIter {
197 self.iter()
198 }
199}
200
201impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentPagedVec<T, PAGE> {
202 type Item = &'a mut T;
203 type IntoIter = VecIterMut<'a, T>;
204
205 fn into_iter(self) -> Self::IntoIter {
206 self.iter_mut()
207 }
208}
209
210/// Mutably iterates over the elements of a [`ConcurrentPagedVec`] in index order.
211#[must_use = "iterators are lazy and do nothing unless consumed"]
212pub struct VecIterMut<'a, T> {
213 inner: Flatten<PagesMut<'a, T>>,
214}
215
216impl<'a, T> VecIterMut<'a, T> {
217 pub(super) fn new<const PAGE: usize>(log: &'a mut AppendLog<T, PAGE>) -> Self {
218 Self {
219 inner: log.pages_mut().flatten(),
220 }
221 }
222}
223
224impl<'a, T> Iterator for VecIterMut<'a, T> {
225 type Item = &'a mut T;
226
227 fn next(&mut self) -> Option<Self::Item> {
228 self.inner.next()
229 }
230
231 fn size_hint(&self) -> (usize, Option<usize>) {
232 self.inner.size_hint()
233 }
234}
235
236impl<T> fmt::Debug for VecIterMut<'_, T> {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.debug_struct("VecIterMut").finish_non_exhaustive()
239 }
240}
241
242/// Clones the committed prefix via [`ConcurrentPagedVec::snapshot`],
243/// which can omit completed pushes beyond an unpublished reservation.
244impl<T: Clone, const PAGE: usize> Clone for ConcurrentPagedVec<T, PAGE> {
245 fn clone(&self) -> Self {
246 Self::from(self.snapshot())
247 }
248}
249
250impl<T, const PAGE: usize> Default for ConcurrentPagedVec<T, PAGE> {
251 fn default() -> Self {
252 Self::new()
253 }
254}
255
256impl<T: fmt::Debug, const PAGE: usize> fmt::Debug for ConcurrentPagedVec<T, PAGE> {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 f.debug_list().entries(self.iter()).finish()
259 }
260}
261
262impl<T, const PAGE: usize> Index<usize> for ConcurrentPagedVec<T, PAGE> {
263 type Output = T;
264
265 #[track_caller]
266 fn index(&self, index: usize) -> &T {
267 self.get(index)
268 .expect("index not visible in ConcurrentPagedVec")
269 }
270}
271
272impl<T, const PAGE: usize> IndexMut<usize> for ConcurrentPagedVec<T, PAGE> {
273 #[track_caller]
274 fn index_mut(&mut self, index: usize) -> &mut T {
275 self.get_mut(index)
276 .expect("index out of bounds in ConcurrentPagedVec")
277 }
278}
279
280impl<T, const PAGE: usize> Extend<T> for ConcurrentPagedVec<T, PAGE> {
281 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
282 self.push_all(iter);
283 }
284}
285
286impl<T, const PAGE: usize> FromIterator<T> for ConcurrentPagedVec<T, PAGE> {
287 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
288 let result = Self::new();
289 result.push_all(iter);
290 result
291 }
292}
293
294impl<T, const PAGE: usize> From<PagedVec<T, PAGE>> for ConcurrentPagedVec<T, PAGE> {
295 fn from(inner: PagedVec<T, PAGE>) -> Self {
296 inner.into_iter().collect()
297 }
298}
299
300#[cfg(feature = "serde")]
301mod serde_impl {
302 use super::*;
303 use serde::de::{Deserialize, Deserializer};
304 use serde::ser::{Serialize, Serializer};
305
306 /// Serializes the committed prefix as a valid plain vector sequence
307 /// in O(prefix length). The prefix can omit completed pushes beyond an
308 /// earlier unpublished reservation, as in [`ConcurrentPagedVec::iter`].
309 impl<T: Serialize, const PAGE: usize> Serialize for ConcurrentPagedVec<T, PAGE> {
310 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
311 serializer.collect_seq(self.iter())
312 }
313 }
314
315 /// Reads the plain [`PagedVec`] format and converts in O(len).
316 impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de> for ConcurrentPagedVec<T, PAGE> {
317 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
318 PagedVec::deserialize(deserializer).map(Self::from)
319 }
320 }
321}