orx_split_vec/growth/doubling/
from.rs

1use super::constants::CUMULATIVE_CAPACITIES;
2use crate::{Doubling, Fragment, SplitVec};
3use alloc::vec::Vec;
4
5impl<T: Clone> From<Vec<T>> for SplitVec<T, Doubling> {
6    /// Converts a `Vec` into a `SplitVec`.
7    ///
8    /// # Examples
9    ///
10    /// ```
11    /// use orx_split_vec::*;
12    ///
13    /// let vec = vec!['a', 'b', 'c'];
14    /// let vec_capacity = vec.capacity();
15    ///
16    /// let split_vec: SplitVec<_, Doubling> = vec.into();
17    ///
18    /// assert_eq!(split_vec, &['a', 'b', 'c']);
19    /// assert_eq!(1, split_vec.fragments().len());
20    /// assert!(vec_capacity <= split_vec.capacity());
21    /// ```
22    fn from(value: Vec<T>) -> Self {
23        let len = value.len();
24        let f = CUMULATIVE_CAPACITIES
25            .iter()
26            .enumerate()
27            .find(|(_, cum_cap)| **cum_cap >= len)
28            .map(|(f, _)| f)
29            .expect("overflow");
30
31        let mut fragments = Vec::with_capacity(f + 1);
32        let mut original_idx = 0;
33        let mut remaining_len = len;
34        let mut curr_f = 1;
35        while remaining_len > 0 {
36            let capacity = &CUMULATIVE_CAPACITIES[curr_f];
37            let mut fragment = Fragment::new(*capacity);
38
39            let copy_len = if capacity <= &remaining_len {
40                *capacity
41            } else {
42                remaining_len
43            };
44
45            fragment.extend_from_slice(&value[original_idx..(original_idx + copy_len)]);
46
47            original_idx += copy_len;
48            remaining_len -= copy_len;
49            fragments.push(fragment);
50            curr_f += 1;
51        }
52
53        Self::from_raw_parts(len, fragments, Doubling)
54    }
55}