Thanks to visit codestin.com
Credit goes to docs.rs

orx_concurrent_vec/
mut_elem.rs

1use crate::{ConcurrentVec, elem::ConcurrentElement};
2use orx_concurrent_option::SOME;
3use orx_pinned_vec::IntoConcurrentPinnedVec;
4
5impl<T, P> ConcurrentVec<T, P>
6where
7    P: IntoConcurrentPinnedVec<ConcurrentElement<T>>,
8{
9    /// Swaps two elements in the vector.
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::from_iter([0, 1, 2, 3]);
21    ///
22    /// let swapped = vec.swap(0, 2);
23    /// assert_eq!(swapped, true);
24    /// assert_eq!(&vec, &[2, 1, 0, 3]);
25    ///
26    /// let swapped = vec.swap(0, 4);
27    /// assert_eq!(swapped, false);
28    /// assert_eq!(&vec, &[2, 1, 0, 3]);
29    /// ```
30    pub fn swap(&self, i: usize, j: usize) -> bool {
31        let h_i = unsafe { self.mut_handle(i, SOME, SOME) };
32        let h_j = unsafe { self.mut_handle(j, SOME, SOME) };
33
34        match (h_i, h_j) {
35            (Some(h_i), Some(h_j)) => {
36                let mut_i = unsafe { h_i.get_mut() };
37                let mut_j = unsafe { h_j.get_mut() };
38                core::mem::swap(mut_i, mut_j);
39                true
40            }
41            _ => false,
42        }
43    }
44
45    /// Fills all positions of the vec 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.fill(42);
55    /// assert_eq!(&vec, &[42, 42, 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 vec 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::from_iter([0, 1, 2, 3]);
75    ///
76    /// let mut current = 0;
77    /// vec.fill_with(|i| {
78    ///     current += i as i32;
79    ///     current
80    /// });
81    /// assert_eq!(&vec, &[0, 1, 3, 6]);
82    /// ```
83    pub fn fill_with<F>(&self, mut value: F)
84    where
85        F: FnMut(usize) -> T,
86    {
87        for (i, elem) in self.iter().enumerate() {
88            elem.set(value(i));
89        }
90    }
91}