Skip to main content

resource_timeline/storage/
inline.rs

1//! A fixed-capacity sequence over an inline array, without `unsafe`.
2//!
3//! [`Inline`] keeps its elements in a [`Buffer`], an array whose unused slots hold
4//! [`Slot::EMPTY`]. Insertion and removal rotate the occupied prefix in place, so every
5//! operation is safe code with the same complexity as the `Vec` counterpart.
6
7use core::fmt;
8use core::hash::{Hash, Hasher};
9use core::marker::PhantomData;
10use core::ops::{Deref, DerefMut};
11
12use super::{Seq, Slot, sealed};
13use crate::{Container, Error};
14
15/// The backing array of an [`Inline`] sequence.
16///
17/// Implemented for `[T; N]` (capacity `N`) and `[[T; 2]; N]` (capacity `2 N`, used for change
18/// points). The trait is sealed.
19pub trait Buffer<T: Slot>: Clone + sealed::Sealed {
20    /// A buffer whose every slot is [`Slot::EMPTY`].
21    const EMPTY: Self;
22
23    /// All slots, used or not.
24    fn slots(&self) -> &[T];
25
26    /// All slots, used or not, mutably.
27    fn slots_mut(&mut self) -> &mut [T];
28}
29
30impl<T: Slot, const N: usize> sealed::Sealed for [T; N] {}
31
32impl<T: Slot, const N: usize> Buffer<T> for [T; N] {
33    const EMPTY: Self = [const { T::EMPTY }; N];
34
35    fn slots(&self) -> &[T] {
36        self
37    }
38
39    fn slots_mut(&mut self) -> &mut [T] {
40        self
41    }
42}
43
44impl<T: Slot, const N: usize> sealed::Sealed for [[T; 2]; N] {}
45
46impl<T: Slot, const N: usize> Buffer<T> for [[T; 2]; N] {
47    const EMPTY: Self = [const { [const { T::EMPTY }; 2] }; N];
48
49    fn slots(&self) -> &[T] {
50        self.as_flattened()
51    }
52
53    fn slots_mut(&mut self) -> &mut [T] {
54        self.as_flattened_mut()
55    }
56}
57
58/// A sequence of at most as many elements as its buffer `B` has slots, stored inline.
59///
60/// Dereferences to the slice of used slots. Growing beyond the capacity fails with
61/// [`Error::CapacityExceeded`] and leaves the sequence unchanged. Equality, hashing and
62/// debug output look at the used slots only.
63pub struct Inline<T: Slot, B: Buffer<T>> {
64    /// The slots. The first `len` are used, the rest hold [`Slot::EMPTY`].
65    buffer: B,
66    /// The number of used slots. Never more than the number of slots in `buffer`.
67    len: usize,
68    /// Ties the element type to the sequence.
69    element: PhantomData<T>,
70}
71
72impl<T: Slot, B: Buffer<T>> Inline<T, B> {
73    /// The number of slots.
74    fn slot_count(&self) -> usize {
75        self.buffer.slots().len()
76    }
77
78    /// The error for a sequence that is full.
79    fn full(&self, container: Container) -> Error {
80        Error::CapacityExceeded {
81            container,
82            capacity: self.slot_count(),
83        }
84    }
85
86    /// Replaces the slot at `index` with the filler and returns its previous content.
87    fn take(&mut self, index: usize) -> T {
88        core::mem::replace(&mut self.buffer.slots_mut()[index], T::EMPTY)
89    }
90}
91
92impl<T: Slot, B: Buffer<T>> sealed::Sealed for Inline<T, B> {}
93
94impl<T: Slot, B: Buffer<T>> Seq<T> for Inline<T, B> {
95    const EMPTY: Self = Self {
96        buffer: B::EMPTY,
97        len: 0,
98        element: PhantomData,
99    };
100
101    fn capacity(&self) -> Option<usize> {
102        Some(self.slot_count())
103    }
104
105    fn try_reserve(&mut self, extra: usize, container: Container) -> Result<(), Error> {
106        if self.len.saturating_add(extra) > self.slot_count() {
107            return Err(self.full(container));
108        }
109
110        Ok(())
111    }
112
113    fn try_push(&mut self, item: T, container: Container) -> Result<(), Error> {
114        let index = self.len;
115        self.try_insert(index, item, container)
116    }
117
118    fn try_insert(&mut self, index: usize, item: T, container: Container) -> Result<(), Error> {
119        assert!(index <= self.len, "insertion index out of range");
120        if self.len == self.slot_count() {
121            return Err(self.full(container));
122        }
123
124        let len = self.len;
125        let slots = self.buffer.slots_mut();
126        slots[len] = item;
127        slots[index..=len].rotate_right(1);
128        self.len += 1;
129        Ok(())
130    }
131
132    fn remove(&mut self, index: usize) -> T {
133        assert!(index < self.len, "removal index out of range");
134        let len = self.len;
135        self.buffer.slots_mut()[index..len].rotate_left(1);
136        self.len -= 1;
137        self.take(len - 1)
138    }
139
140    fn pop(&mut self) -> Option<T> {
141        let last = self.len.checked_sub(1)?;
142        self.len = last;
143        Some(self.take(last))
144    }
145
146    fn retain(&mut self, mut keep: impl FnMut(&T) -> bool) {
147        let mut kept = 0;
148        for read in 0..self.len {
149            if keep(&self.buffer.slots()[read]) {
150                self.buffer.slots_mut().swap(kept, read);
151                kept += 1;
152            }
153        }
154
155        self.truncate(kept);
156    }
157
158    fn truncate(&mut self, len: usize) {
159        while self.len > len {
160            self.pop();
161        }
162    }
163}
164
165impl<T: Slot, B: Buffer<T>> Deref for Inline<T, B> {
166    type Target = [T];
167
168    fn deref(&self) -> &[T] {
169        &self.buffer.slots()[..self.len]
170    }
171}
172
173impl<T: Slot, B: Buffer<T>> DerefMut for Inline<T, B> {
174    fn deref_mut(&mut self) -> &mut [T] {
175        let len = self.len;
176        &mut self.buffer.slots_mut()[..len]
177    }
178}
179
180impl<T: Slot, B: Buffer<T>> Default for Inline<T, B> {
181    fn default() -> Self {
182        Self::EMPTY
183    }
184}
185
186impl<T: Slot, B: Buffer<T>> Clone for Inline<T, B> {
187    fn clone(&self) -> Self {
188        Self {
189            buffer: self.buffer.clone(),
190            len: self.len,
191            element: PhantomData,
192        }
193    }
194}
195
196impl<T: Slot, B: Buffer<T>> fmt::Debug for Inline<T, B> {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        f.debug_list().entries(self.iter()).finish()
199    }
200}
201
202impl<T: Slot, B: Buffer<T>> PartialEq for Inline<T, B> {
203    fn eq(&self, other: &Self) -> bool {
204        **self == **other
205    }
206}
207
208impl<T: Slot, B: Buffer<T>> Eq for Inline<T, B> {}
209
210impl<T: Slot, B: Buffer<T>> Hash for Inline<T, B> {
211    fn hash<H: Hasher>(&self, state: &mut H) {
212        (**self).hash(state);
213    }
214}
215
216impl<T: Slot, B: Buffer<T>, const M: usize> PartialEq<[T; M]> for Inline<T, B> {
217    fn eq(&self, other: &[T; M]) -> bool {
218        **self == *other
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    //! Unit tests of the inline sequence against `Vec` semantics.
225
226    use super::Inline;
227    use crate::storage::Seq;
228    use crate::{ActivityId, Container, Error};
229
230    /// A sequence of three activity ids.
231    type Three = Inline<ActivityId, [ActivityId; 3]>;
232
233    /// Shorthand for an activity id.
234    const fn id(value: u32) -> ActivityId {
235        ActivityId(value)
236    }
237
238    /// Pushing beyond the capacity fails with the named container and changes nothing.
239    #[test]
240    fn push_until_full() {
241        let mut seq = Three::EMPTY;
242        for value in 0..3 {
243            seq.try_push(id(value), Container::Impacts).expect("room");
244        }
245
246        assert_eq!(
247            seq.try_push(id(9), Container::Impacts),
248            Err(Error::CapacityExceeded {
249                container: Container::Impacts,
250                capacity: 3
251            })
252        );
253        assert_eq!(seq, [id(0), id(1), id(2)]);
254        assert_eq!(seq.capacity(), Some(3));
255    }
256
257    /// Insert, remove, pop and retain match the `Vec` operations of the same name.
258    #[test]
259    fn edits_match_vec() {
260        let mut seq = Three::EMPTY;
261        seq.try_insert(0, id(2), Container::Sets).expect("room");
262        seq.try_insert(0, id(0), Container::Sets).expect("room");
263        seq.try_insert(1, id(1), Container::Sets).expect("room");
264        assert_eq!(seq, [id(0), id(1), id(2)]);
265
266        assert_eq!(seq.remove(1), id(1));
267        assert_eq!(seq, [id(0), id(2)]);
268        assert_eq!(seq.pop(), Some(id(2)));
269        assert_eq!(seq.pop(), Some(id(0)));
270        assert_eq!(seq.pop(), None);
271
272        seq.try_extend_from_slice(&[id(4), id(5), id(6)], Container::Sets)
273            .expect("room");
274        seq.retain(|item| item.0 != 5);
275        assert_eq!(seq, [id(4), id(6)]);
276    }
277
278    /// Reserving beyond the capacity fails without touching the content.
279    #[test]
280    fn reserve_checks_the_capacity() {
281        let mut seq = Three::EMPTY;
282        seq.try_push(id(1), Container::Scratch).expect("room");
283        assert!(seq.try_reserve(2, Container::Scratch).is_ok());
284        assert_eq!(
285            seq.try_reserve(3, Container::Scratch),
286            Err(Error::CapacityExceeded {
287                container: Container::Scratch,
288                capacity: 3
289            })
290        );
291        assert_eq!(
292            seq.try_extend_from_slice(&[id(2), id(3), id(4)], Container::Scratch),
293            Err(Error::CapacityExceeded {
294                container: Container::Scratch,
295                capacity: 3
296            })
297        );
298        assert_eq!(seq, [id(1)]);
299    }
300
301    /// Removed slots are reset, so equality and hashing ignore stale content.
302    #[test]
303    fn equality_ignores_unused_slots() {
304        let mut a = Three::EMPTY;
305        a.try_push(id(7), Container::Impacts).expect("room");
306        a.try_push(id(8), Container::Impacts).expect("room");
307        a.pop();
308        let mut b = Three::EMPTY;
309        b.try_push(id(7), Container::Impacts).expect("room");
310        assert_eq!(a, b);
311
312        let mut doubled = Inline::<ActivityId, [[ActivityId; 2]; 2]>::EMPTY;
313        for value in [3, 1, 3, 3] {
314            doubled
315                .try_push(id(value), Container::ChangePoints)
316                .expect("room");
317        }
318
319        doubled.dedup();
320        assert_eq!(doubled, [id(3), id(1), id(3)]);
321    }
322}