orx_concurrent_vec/concurrent_slice/
mut_elem.rs

1use super::ConcurrentSlice;
2use crate::elem::ConcurrentElement;
3use orx_fixed_vec::IntoConcurrentPinnedVec;
4
5impl<T, P> ConcurrentSlice<'_, T, P>
6where
7    P: IntoConcurrentPinnedVec<ConcurrentElement<T>>,
8{
9    /// Swaps two elements in the slice.
10    ///
11    /// Returns:
12    /// * true of both `i` and `j` are in bounds and values are swapped,
13    /// * false if at least one of the indices is out of bounds.
14    ///
15    /// # Examples
16    ///
17    /// ```rust
18    /// use orx_concurrent_vec::*;
19    ///
20    /// let vec = ConcurrentVec::new();
21    /// vec.extend([0, 1, 2, 3, 4, 5]);
22    ///
23    /// let slice = vec.slice(1..5);
24    ///
25    /// let swapped = slice.swap(0, 2);
26    /// assert_eq!(swapped, true);
27    /// assert_eq!(&slice, &[3, 2, 1, 4]);
28    ///
29    /// let swapped = slice.swap(0, 4); // out-of-bounds
30    /// assert_eq!(swapped, false);
31    /// assert_eq!(&slice, &[3, 2, 1, 4]);
32    ///
33    /// assert_eq!(&vec, &[0, 3, 2, 1, 4, 5]);
34    /// ```
35    pub fn swap(&self, i: usize, j: usize) -> bool {
36        let idx_i = self.idx(i);
37        let idx_j = self.idx(j);
38
39        match (idx_i, idx_j) {
40            (Some(i), Some(j)) => self.vec.swap(i, j),
41            _ => false,
42        }
43    }
44
45    /// Fills all positions of the slice with the given `value`.
46    ///
47    /// # Examples
48    ///
49    /// ```
50    /// use orx_concurrent_vec::*;
51    ///
52    /// let vec = ConcurrentVec::from_iter([0, 1, 2, 3]);
53    ///
54    /// vec.slice(2..).fill(42);
55    /// assert_eq!(&vec, &[0, 1, 42, 42]);
56    /// ```
57    pub fn fill(&self, value: T)
58    where
59        T: Clone,
60    {
61        for elem in self.iter() {
62            elem.set(value.clone());
63        }
64    }
65
66    /// Fills all positions of the slice with the the values
67    /// created by successively calling `value(i)` for each position.
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// use orx_concurrent_vec::*;
73    ///
74    /// let vec = ConcurrentVec::new();
75    /// vec.extend([0, 1, 2, 3, 4, 5, 6]);
76    ///
77    /// let slice = vec.slice(0..=3);
78    ///
79    /// let mut current = 0;
80    /// slice.fill_with(|i| {
81    ///     current += i as i32;
82    ///     current
83    /// });
84    /// assert_eq!(&slice, &[0, 1, 3, 6]);
85    /// assert_eq!(&vec, &[0, 1, 3, 6, 4, 5, 6]);
86    /// ```
87    pub fn fill_with<F>(&self, mut value: F)
88    where
89        F: FnMut(usize) -> T,
90    {
91        for (i, elem) in self.iter().enumerate() {
92            elem.set(value(i));
93        }
94    }
95}