Skip to main content

orx_split_vec/growth/recursive/
recursive_growth.rs

1use crate::{Doubling, Fragment, Growth, SplitVec};
2use alloc::string::String;
3use orx_pseudo_default::PseudoDefault;
4
5/// Equivalent to [`Doubling`] strategy except for the following:
6///
7/// * enables zero-cost (no-ops) `append` operation:
8///   * we can append standard vectors, vectors of vectors, split vectors, etc., any data that implements `IntoFragments` trait,
9///   * by simply accepting it as a whole fragment,
10///   * according to benchmarks documented in the crate definition:
11///     * `SplitVec<_, Recursive>` is infinitely faster than other growth strategies or standard vector :)
12///     * since its time complexity is independent of size of the data to be appended.
13/// * at the expense of providing slower random-access performance:
14///   * random access time complexity of `Doubling` strategy is constant time;
15///   * that of `Recursive` strategy is linear in the number of fragments;
16///   * according to benchmarks documented in the crate definition:
17///     * `SplitVec<_, Doubling>` or standard vector are around 4 to 7 times faster than `SplitVec<_, Recursive>`,
18///     * and 1.5 times faster when the elements get very large (16 x `u64`).
19///
20/// Note that other operations such as serial access are equivalent to `Doubling` strategy.
21///
22/// # Examples
23///
24/// ```
25/// use orx_split_vec::*;
26///
27/// // SplitVec<usize, Recursive>
28/// let mut vec = SplitVec::with_recursive_growth();
29///
30/// vec.push('a');
31/// assert_eq!(vec, &['a']);
32///
33/// vec.append(vec!['b', 'c']);
34/// assert_eq!(vec, &['a', 'b', 'c']);
35///
36/// vec.append(vec![vec!['d'], vec!['e', 'f']]);
37/// assert_eq!(vec, &['a', 'b', 'c', 'd', 'e', 'f']);
38///
39/// let other_split_vec: SplitVec<_> = vec!['g', 'h'].into();
40/// vec.append(other_split_vec);
41/// assert_eq!(vec, &['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']);
42/// ```
43#[derive(Debug, Default, Clone, PartialEq)]
44pub struct Recursive;
45
46impl PseudoDefault for Recursive {
47    fn pseudo_default() -> Self {
48        Default::default()
49    }
50}
51
52impl Growth for Recursive {
53    #[inline(always)]
54    fn new_fragment_capacity_from(
55        &self,
56        fragment_capacities: impl ExactSizeIterator<Item = usize>,
57    ) -> usize {
58        Doubling.new_fragment_capacity_from(fragment_capacities)
59    }
60
61    fn maximum_concurrent_capacity<T>(
62        &self,
63        fragments: &[Fragment<T>],
64        fragments_capacity: usize,
65    ) -> usize {
66        assert!(fragments_capacity >= fragments.len());
67
68        let current_capacity = fragments.iter().map(|x| x.capacity()).sum();
69        let mut last_capacity = fragments.last().map(|x| x.capacity()).unwrap_or(2);
70
71        let mut total_capacity = current_capacity;
72
73        for _ in fragments.len()..fragments_capacity {
74            last_capacity *= 2;
75            total_capacity += last_capacity;
76        }
77
78        total_capacity
79    }
80
81    fn required_fragments_len<T>(
82        &self,
83        fragments: &[Fragment<T>],
84        maximum_capacity: usize,
85    ) -> Result<usize, String> {
86        fn overflown_err() -> String {
87            alloc::format!(
88                "Maximum cumulative capacity that can be reached by the Recursive strategy is {}.",
89                usize::MAX
90            )
91        }
92
93        let current_capacity: usize = fragments.iter().map(|x| x.capacity()).sum();
94        let mut last_capacity = fragments.last().map(|x| x.capacity()).unwrap_or(2);
95
96        let mut total_capacity = current_capacity;
97        let mut f = fragments.len();
98
99        while total_capacity < maximum_capacity {
100            let (new_last_capacity, overflown) = last_capacity.overflowing_mul(2);
101            if overflown {
102                return Err(overflown_err());
103            }
104            last_capacity = new_last_capacity;
105
106            let (new_total_capacity, overflown) = total_capacity.overflowing_add(last_capacity);
107            if overflown {
108                return Err(overflown_err());
109            }
110
111            total_capacity = new_total_capacity;
112            f += 1;
113        }
114
115        Ok(f)
116    }
117
118    fn maximum_concurrent_capacity_bound<T>(
119        &self,
120        fragments: &[Fragment<T>],
121        fragments_capacity: usize,
122    ) -> usize {
123        Doubling.maximum_concurrent_capacity_bound(fragments, fragments_capacity)
124    }
125}
126
127impl<T> SplitVec<T, Recursive> {
128    /// Strategy which allows to create a fragment with double the capacity
129    /// of the prior fragment every time the split vector needs to expand.
130    ///
131    /// Notice that this is similar to the `Doubling` growth strategy.
132    /// However, `Recursive` and `Doubling` strategies have the two following important differences in terms of performance:
133    ///
134    /// * Random access by indices is much faster with `Doubling`.
135    /// * Recursive strategy enables copy-free `append` method which merges another vector to this vector in constant time.
136    ///
137    /// All other operations are expected to have similar complexity.
138    ///
139    /// ## Random Access
140    ///
141    /// * `Doubling` strategy provides a constant time access by random indices.
142    /// * `Recursive` strategy provides a random access time complexity that is linear in the number of fragments.
143    ///   Note that this is significantly faster than the linear-in-number-of-elements complexity of linked lists;
144    ///   however, significantly slower than the `Doubling` strategy's constant time.
145    ///
146    /// ## Append
147    ///
148    /// * `Recursive` strategy provides `append` operation which allows merging two vectors in constant time without copies.
149    ///
150    /// `SplitVec::append` method should not be confused with `std::vec::Vec::append` method:
151    /// * The split vector version consumes the vector to be appended.
152    ///   It takes advantage of its split nature and appends the other vector simply by owning its pointer.
153    ///   In other words, the other vector is appended to this vector with no cost and no copies.
154    /// * The standard vector version mutates the vector to be appended,
155    ///   moving all its element to the first vector leaving the latter empty.
156    ///   This operation is carried out by memory copies.
157    ///
158    /// # Examples
159    ///
160    /// ```
161    /// use orx_split_vec::*;
162    ///
163    /// // SplitVec<usize, Doubling>
164    /// let mut vec = SplitVec::with_recursive_growth();
165    ///
166    /// assert_eq!(1, vec.fragments().len());
167    /// assert_eq!(Some(4), vec.fragments().first().map(|f| f.capacity()));
168    /// assert_eq!(Some(0), vec.fragments().first().map(|f| f.len()));
169    ///
170    /// // fill the first 5 fragments
171    /// let expected_fragment_capacities = vec![4, 8, 16, 32];
172    /// let num_items: usize = expected_fragment_capacities.iter().sum();
173    /// for i in 0..num_items {
174    ///     vec.push(i);
175    /// }
176    ///
177    /// assert_eq!(
178    ///     expected_fragment_capacities,
179    ///     vec.fragments()
180    ///     .iter()
181    ///     .map(|f| f.capacity())
182    ///     .collect::<Vec<_>>()
183    /// );
184    /// assert_eq!(
185    ///     expected_fragment_capacities,
186    ///     vec.fragments().iter().map(|f| f.len()).collect::<Vec<_>>()
187    /// );
188    ///
189    /// // create the 6-th fragment doubling the capacity
190    /// vec.push(42);
191    /// assert_eq!(
192    ///     vec.fragments().len(),
193    ///     expected_fragment_capacities.len() + 1
194    /// );
195    ///
196    /// assert_eq!(vec.fragments().last().map(|f| f.capacity()), Some(32 * 2));
197    /// assert_eq!(vec.fragments().last().map(|f| f.len()), Some(1));
198    /// ```
199    pub fn with_recursive_growth() -> Self {
200        SplitVec::with_doubling_growth().into()
201    }
202
203    /// Creates a new split vector with `Recursive` growth and initial `fragments_capacity`.
204    ///
205    /// This method differs from [`SplitVec::with_recursive_growth`] only by the pre-allocation of fragments collection.
206    /// Note that this (only) important for concurrent programs:
207    /// * SplitVec already keeps all elements pinned to their locations;
208    /// * Creating a buffer for storing the meta information is important for keeping the meta information pinned as well.
209    ///   This is relevant and important for concurrent programs.
210    ///
211    /// # Panics
212    ///
213    /// Panics if `fragments_capacity == 0`.
214    pub fn with_recursive_growth_and_fragments_capacity(fragments_capacity: usize) -> Self {
215        SplitVec::with_doubling_growth_and_fragments_capacity(fragments_capacity).into()
216    }
217
218    /// Creates a new split vector with `Recursive` growth and maximum concurrent capacity which depends
219    /// on the pointer size of the target architecture.
220    ///
221    /// This method differs from [`SplitVec::with_recursive_growth`] only by the pre-allocation of fragments collection,
222    /// which never contains more elements than 33.
223    pub fn with_recursive_growth_and_max_concurrent_capacity() -> Self {
224        SplitVec::with_doubling_growth_and_max_concurrent_capacity().into()
225    }
226}