rt_vec/
rt_vec.rs

1use std::ops::{Deref, DerefMut};
2
3use rt_ref::{BorrowFail, Cell, Ref, RefMut};
4
5/// Map from `TypeId` to type.
6#[derive(Debug)]
7pub struct RtVec<V>(Vec<Cell<V>>);
8
9impl<V> Default for RtVec<V> {
10    fn default() -> Self {
11        Self(Default::default())
12    }
13}
14
15macro_rules! borrow_panic {
16    ($index:ident) => {
17        panic!(
18            "Expected to borrow index `{index}`, but it does not exist.",
19            index = $index
20        )
21    };
22}
23
24/// A [`Vec`] that allows multiple mutable borrows to different entries.
25///
26/// The [`borrow`] and [`borrow_mut`] methods take `&self`, allowing multiple
27/// mutable borrows of different entries at the same time. This is achieved via
28/// interior mutability. In case you violate the borrowing rules of Rust
29/// (multiple reads xor one write), you will get a panic.
30///
31/// For non-packing versions of these methods, use [`try_borrow`] and
32/// [`try_borrow_mut`].
33///
34/// [`borrow`]: Self::borrow
35/// [`borrow_mut`]: Self::borrow_mut
36/// [`try_borrow`]: Self::try_borrow
37/// [`try_borrow_mut`]: Self::try_borrow_mut
38impl<V> RtVec<V> {
39    /// Creates an empty `RtVec`.
40    ///
41    /// The `RtVec` is initially created with a capacity of 0, so it will not
42    /// allocate until it is first inserted into.
43    ///
44    /// # Examples
45    ///
46    /// ```rust
47    /// use rt_vec::RtVec;
48    ///
49    /// let mut rt_vec = RtVec::<u32>::new();
50    /// ```
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    /// Creates an empty `RtVec` with the specified capacity.
56    ///
57    /// The `RtVec` will be able to hold at least capacity elements without
58    /// reallocating. If capacity is 0, the vec will not allocate.
59    ///
60    /// # Examples
61    ///
62    /// ```rust
63    /// use rt_vec::RtVec;
64    ///
65    /// let rt_vec: RtVec<i32> = RtVec::with_capacity(10);
66    /// ```
67    pub fn with_capacity(capacity: usize) -> Self {
68        Self(Vec::with_capacity(capacity))
69    }
70
71    /// Returns the number of elements the vec can hold without reallocating.
72    ///
73    /// This number is a lower bound; the `RtVec<V>` might be able to hold
74    /// more, but is guaranteed to be able to hold at least this many.
75    ///
76    /// # Examples
77    ///
78    /// ```rust
79    /// use rt_vec::RtVec;
80    /// let rt_vec: RtVec<i32> = RtVec::with_capacity(100);
81    /// assert!(rt_vec.capacity() >= 100);
82    /// ```
83    pub fn capacity(&self) -> usize {
84        self.0.capacity()
85    }
86
87    /// Inserts an element at position `index` within the vector, shifting all
88    /// elements after it to the right.
89    ///
90    /// # Panics
91    ///
92    /// Panics if `index > len`.
93    ///
94    /// # Examples
95    ///
96    /// ```rust
97    /// # use rt_vec::RtVec;
98    /// #
99    /// let mut rt_vec = RtVec::new();
100    ///
101    /// rt_vec.push('a');
102    /// rt_vec.push('b');
103    /// assert_eq!(*rt_vec.borrow(0), 'a');
104    /// assert_eq!(*rt_vec.borrow(1), 'b');
105    /// ```
106    pub fn push(&mut self, v: V) {
107        self.0.push(Cell::new(v));
108    }
109
110    /// Inserts an element at position `index` within the vector, shifting all
111    /// elements after it to the right.
112    ///
113    /// # Panics
114    ///
115    /// Panics if `index > len`.
116    ///
117    /// # Examples
118    ///
119    /// ```rust
120    /// # use rt_vec::RtVec;
121    /// #
122    /// let mut rt_vec = RtVec::new();
123    /// rt_vec.push('a');
124    /// rt_vec.insert(0, 'b');
125    ///
126    /// assert_eq!(*rt_vec.borrow(0), 'b');
127    /// assert_eq!(*rt_vec.borrow(1), 'a');
128    /// ```
129    pub fn insert(&mut self, index: usize, v: V) {
130        self.0.insert(index, Cell::new(v));
131    }
132
133    /// Returns `true` if the vec contains no elements.
134    ///
135    /// # Examples
136    ///
137    /// ```rust
138    /// # use rt_vec::RtVec;
139    /// #
140    /// let mut rt_vec = RtVec::new();
141    /// assert!(rt_vec.is_empty());
142    ///
143    /// rt_vec.push('a');
144    /// assert!(!rt_vec.is_empty());
145    /// ```
146    pub fn is_empty(&self) -> bool {
147        self.0.is_empty()
148    }
149
150    /// Removes and returns the element at position `index` within the vector,
151    /// shifting all elements after it to the left.
152    ///
153    /// Note: Because this shifts over the remaining elements, it has a
154    /// worst-case performance of *O(n)*. If you don’t need the order of
155    /// elements to be preserved, use [`swap_remove`] instead.
156    ///
157    /// # Panics
158    ///
159    /// Panics if `index` is out of bounds.
160    ///
161    /// # Examples
162    ///
163    /// ```rust
164    /// # use rt_vec::RtVec;
165    /// #
166    /// let mut rt_vec = RtVec::new();
167    /// rt_vec.push('a');
168    /// assert_eq!(rt_vec.remove(0), 'a');
169    /// ```
170    ///
171    /// [`swap_remove`]: Self::swap_remove
172    pub fn remove(&mut self, index: usize) -> V {
173        let cell = self.0.remove(index);
174        Cell::into_inner(cell)
175    }
176
177    /// Removes an element from the vector and returns it.
178    ///
179    /// The removed element is replaced by the last element of the vector.
180    ///
181    /// This does not preserve ordering, but is *O*(1). If you need to preserve
182    /// the element order, use [`remove`] instead.
183    ///
184    /// # Panics
185    ///
186    /// Panics if `index` is out of bounds.
187    ///
188    /// # Examples
189    ///
190    /// ```rust
191    /// # use rt_vec::RtVec;
192    /// #
193    /// let mut v = vec!["foo", "bar", "baz", "qux"];
194    ///
195    /// assert_eq!(v.swap_remove(1), "bar");
196    /// assert_eq!(v, ["foo", "qux", "baz"]);
197    ///
198    /// assert_eq!(v.swap_remove(0), "foo");
199    /// assert_eq!(v, ["baz", "qux"]);
200    /// ```
201    ///
202    /// [`remove`]: Self::remove
203    pub fn swap_remove(&mut self, index: usize) -> V {
204        let cell = self.0.swap_remove(index);
205        Cell::into_inner(cell)
206    }
207
208    /// Returns a reference to the value corresponding to the index.
209    ///
210    /// See [`try_borrow`] for a non-panicking version of this function.
211    ///
212    /// # Panics
213    ///
214    /// * Panics if the value is already borrowed mutably.
215    ///
216    /// [`try_borrow`]: Self::try_borrow
217    pub fn borrow(&self, index: usize) -> Ref<V> {
218        self.0
219            .get(index)
220            .map(|cell| Ref::new(cell.borrow()))
221            .unwrap_or_else(|| borrow_panic!(index))
222    }
223
224    /// Returns a reference to the value if it exists and is not mutably
225    /// borrowed.
226    ///
227    /// * Returns `BorrowFail::ValueNotFound` if `index` is out of bounds.
228    /// * Returns `BorrowFail::BorrowConflictImm` if the value is already
229    ///   borrowed mutably.
230    pub fn try_borrow(&self, index: usize) -> Result<Ref<V>, BorrowFail> {
231        self.0
232            .get(index)
233            .ok_or(BorrowFail::ValueNotFound)
234            .and_then(|cell| cell.try_borrow().map(Ref::new))
235    }
236
237    /// Returns a reference to the value if it exists and is not borrowed.
238    ///
239    /// See [`try_borrow_mut`] for a non-panicking version of this function.
240    ///
241    /// # Panics
242    ///
243    /// Panics if the value is already borrowed either immutably or mutably.
244    ///
245    /// [`try_borrow_mut`]: Self::try_borrow_mut
246    pub fn borrow_mut(&self, index: usize) -> RefMut<V> {
247        self.0
248            .get(index)
249            .map(|cell| RefMut::new(cell.borrow_mut()))
250            .unwrap_or_else(|| borrow_panic!(index))
251    }
252
253    /// Returns a mutable reference to the value if it is successfully borrowed
254    /// mutably.
255    ///
256    /// * Returns `BorrowFail::ValueNotFound` if `index` is out of bounds.
257    /// * Returns `BorrowFail::BorrowConflictMut` if the value is already
258    ///   borrowed.
259    pub fn try_borrow_mut(&self, index: usize) -> Result<RefMut<V>, BorrowFail> {
260        self.0
261            .get(index)
262            .ok_or(BorrowFail::ValueNotFound)
263            .and_then(|r_cell| {
264                r_cell
265                    .try_borrow_mut()
266                    .map(|cell_ref_mut| RefMut::new(cell_ref_mut))
267            })
268    }
269
270    /// Returns a reference to the value corresponding to the index if it is not
271    /// borrowed.
272    ///
273    /// Returns `None` if `index` is out of bounds.
274    ///
275    /// See [`try_borrow`] for a version of this that returns a `Result` with
276    /// the reason why the value is not returned.
277    ///
278    /// # Panics
279    ///
280    /// Panics if the value is already borrowed mutably.
281    ///
282    /// [`try_borrow`]: Self::try_borrow
283    pub fn get(&self, index: usize) -> Option<Ref<V>> {
284        self.0.get(index).map(|cell| Ref::new(cell.borrow()))
285    }
286
287    /// Retrieves a value without fetching, which is cheaper, but only
288    /// available with `&mut self`.
289    pub fn get_mut(&mut self, index: usize) -> Option<&mut V> {
290        self.get_value_mut(index)
291    }
292
293    /// Retrieves a value without fetching, which is cheaper, but only
294    /// available with `&mut self`.
295    pub fn get_value_mut(&mut self, index: usize) -> Option<&mut V> {
296        self.0.get_mut(index).map(Cell::get_mut)
297    }
298
299    /// Get raw access to the underlying cell.
300    pub fn get_raw(&self, index: usize) -> Option<&Cell<V>> {
301        self.0.get(index)
302    }
303}
304
305impl<V> Deref for RtVec<V> {
306    type Target = Vec<Cell<V>>;
307
308    fn deref(&self) -> &Self::Target {
309        &self.0
310    }
311}
312
313impl<V> DerefMut for RtVec<V> {
314    fn deref_mut(&mut self) -> &mut Self::Target {
315        &mut self.0
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use rt_ref::BorrowFail;
322
323    use super::RtVec;
324
325    #[derive(Debug, Default, PartialEq)]
326    struct Res;
327
328    #[derive(Debug, Default, PartialEq)]
329    struct Value(u32);
330
331    #[test]
332    fn insert() {
333        let mut rt_vec = RtVec::new();
334        rt_vec.insert(0, Res);
335
336        assert_eq!(Res, *rt_vec.borrow(0));
337    }
338
339    #[test]
340    fn with_capacity_reserves_enough_capacity() {
341        let rt_vec: RtVec<i32> = RtVec::with_capacity(100);
342        assert!(rt_vec.capacity() >= 100);
343    }
344
345    #[test]
346    fn deref_and_deref_mut() {
347        let mut rt_vec = RtVec::new();
348        rt_vec.insert(0, 0);
349        rt_vec.insert(1, 1);
350
351        rt_vec.iter_mut().for_each(|v| *v.borrow_mut() += 1);
352
353        let a = rt_vec.remove(0);
354        assert_eq!(1, a);
355
356        let b = rt_vec.iter().next();
357        assert_eq!(Some(2), b.map(|v| *v.borrow()));
358    }
359
360    #[test]
361    fn is_empty_returns_true_when_map_does_not_contain_items() {
362        let rt_vec = RtVec::<u32>::new();
363
364        assert!(rt_vec.is_empty());
365    }
366
367    #[test]
368    fn is_empty_returns_false_when_map_contains_items() {
369        let mut rt_vec = RtVec::new();
370
371        rt_vec.push(0);
372
373        assert!(!rt_vec.is_empty());
374    }
375
376    #[test]
377    fn get_mut_returns_mutable_reference_to_value() {
378        let mut rt_vec = RtVec::new();
379        rt_vec.push(Value(1));
380
381        let value = rt_vec.get_mut(0);
382
383        assert!(value.is_some());
384
385        if let Some(value) = value {
386            *value = Value(2);
387        }
388
389        let value = rt_vec.get_mut(0).map(|value| value.0);
390
391        assert_eq!(Some(2), value);
392    }
393
394    #[test]
395    #[should_panic(expected = "but it was already borrowed")]
396    fn read_write_fails() {
397        let mut rt_vec = RtVec::new();
398        rt_vec.push(Res);
399
400        let _read = rt_vec.borrow(0);
401        let _write = rt_vec.borrow_mut(0);
402    }
403
404    #[test]
405    #[should_panic(expected = "but it was already borrowed mutably")]
406    fn write_read_fails() {
407        let mut rt_vec = RtVec::new();
408        rt_vec.push(Res);
409
410        let _write = rt_vec.borrow_mut(0);
411        let _read = rt_vec.borrow(0);
412    }
413
414    #[test]
415    fn remove_insert() {
416        let mut rt_vec = RtVec::new();
417        rt_vec.push(Res);
418
419        assert_eq!(Res, *rt_vec.borrow(0));
420
421        rt_vec.remove(0);
422
423        assert_eq!(None, rt_vec.get(0));
424
425        rt_vec.push(Res);
426
427        assert_eq!(Res, *rt_vec.borrow(0));
428    }
429
430    #[test]
431    fn swap_remove() {
432        let mut rt_vec = RtVec::new();
433        rt_vec.push(0);
434        rt_vec.push(1);
435        rt_vec.push(2);
436
437        rt_vec.swap_remove(1);
438
439        assert_eq!(2, *rt_vec.borrow(1));
440    }
441
442    #[test]
443    #[should_panic(expected = "Expected to borrow index `0`, but it does not exist.")]
444    fn borrow_before_insert_panics() {
445        let rt_vec = RtVec::<i32>::new();
446
447        rt_vec.borrow(0);
448    }
449
450    #[test]
451    #[should_panic(expected = "Expected to borrow index `0`, but it does not exist.")]
452    fn borrow_mut_before_insert_panics() {
453        let rt_vec = RtVec::<i32>::new();
454
455        rt_vec.borrow_mut(0);
456    }
457
458    #[test]
459    fn borrow_mut_try_borrow_returns_borrow_conflict_imm() {
460        let mut rt_vec = RtVec::new();
461        rt_vec.push(Res);
462
463        let _res = rt_vec.borrow_mut(0);
464
465        assert_eq!(Err(BorrowFail::BorrowConflictImm), rt_vec.try_borrow(0));
466    }
467
468    #[test]
469    fn borrow_try_borrow_mut_returns_borrow_conflict_mut() {
470        let mut rt_vec = RtVec::new();
471        rt_vec.push(Res);
472
473        let _res = rt_vec.borrow(0);
474
475        assert_eq!(Err(BorrowFail::BorrowConflictMut), rt_vec.try_borrow_mut(0));
476    }
477
478    #[test]
479    fn borrow_mut_borrow_mut_returns_borrow_conflict_mut() {
480        let mut rt_vec = RtVec::new();
481        rt_vec.push(Res);
482
483        let _res = rt_vec.borrow_mut(0);
484
485        assert_eq!(Err(BorrowFail::BorrowConflictMut), rt_vec.try_borrow_mut(0));
486    }
487
488    #[test]
489    fn try_borrow_before_insert_returns_value_not_found() {
490        let rt_vec = RtVec::<Res>::new();
491
492        assert_eq!(Err(BorrowFail::ValueNotFound), rt_vec.try_borrow(0));
493    }
494
495    #[test]
496    fn try_borrow_mut_before_insert_returns_value_not_found() {
497        let rt_vec = RtVec::<Res>::new();
498
499        assert_eq!(Err(BorrowFail::ValueNotFound), rt_vec.try_borrow_mut(0));
500    }
501
502    #[test]
503    #[should_panic(expected = "Expected to borrow index `0`, but it does not exist.")]
504    fn borrow_before_insert_panics_value_not_found() {
505        let rt_vec = RtVec::<Res>::new();
506
507        rt_vec.borrow(0);
508    }
509
510    #[test]
511    #[should_panic(expected = "Expected to borrow index `0`, but it does not exist.")]
512    fn borrow_mut_before_insert_panics_value_not_found() {
513        let rt_vec = RtVec::<Res>::new();
514
515        rt_vec.borrow_mut(0);
516    }
517}