inplace_it/alloc_array.rs
1use core::mem::MaybeUninit;
2use alloc::vec::Vec;
3
4use crate::try_inplace_array;
5use crate::guards::UninitializedSliceMemoryGuard;
6
7/// `alloc_array` is used when `inplace_or_alloc_array` realize that the size of requested array of `T`
8/// is too large and should be replaced in the heap.
9///
10/// It allocates a vector with `size` elements and fills it up with help of `init` closure
11/// and then pass a reference to a slice of the vector into the `consumer` closure.
12/// `consumer`'s result will be returned.
13pub fn alloc_array<T, R, Consumer: FnOnce(UninitializedSliceMemoryGuard<T>) -> R>(size: usize, consumer: Consumer) -> R {
14 unsafe {
15 let mut memory_holder = Vec::<MaybeUninit<T>>::with_capacity(size);
16 memory_holder.set_len(size);
17 let result = consumer(UninitializedSliceMemoryGuard::new(&mut *memory_holder));
18 memory_holder.set_len(0);
19 result
20 }
21}
22
23/// `inplace_or_alloc_array` is a central function of this crate.
24/// It's trying to place an array of `T` on the stack and pass the guard of memory into the
25/// `consumer` closure. `consumer`'s result will be returned.
26///
27/// If the result of array of `T` is more than 4096 then the vector will be allocated
28/// in the heap and will be used instead of stack-based fixed-size array.
29///
30/// Sometimes size of allocated array might be more than requested. For sizes larger than 32,
31/// the following formula is used: `roundUp(size/32)*32`. This is a simplification that used
32/// for keeping code short, simple and able to optimize.
33/// For example, for requested 50 item `[T; 64]` will be allocated.
34/// For 120 items - `[T; 128]` and so on.
35///
36/// Note that rounding size up is working for fixed-sized arrays only. If function decides to
37/// allocate a vector then its size will be equal to requested.
38///
39/// # Examples
40///
41/// ```rust
42/// use inplace_it::{
43/// inplace_or_alloc_array,
44/// UninitializedSliceMemoryGuard,
45/// };
46///
47/// let sum: u16 = inplace_or_alloc_array(100, |uninit_guard: UninitializedSliceMemoryGuard<u16>| {
48/// assert_eq!(uninit_guard.len(), 128);
49/// // For now, our memory is placed/allocated but uninitialized.
50/// // Let's initialize it!
51/// let guard = uninit_guard.init(|index| index as u16 * 2);
52/// // For now, memory contains content like [0, 2, 4, 6, ..., 252, 254]
53/// guard.iter().sum()
54/// });
55/// // Sum of [0, 2, 4, 6, ..., 252, 254] = sum of [0, 1, 2, 3, ..., 126, 127] * 2 = ( 127 * (127+1) ) / 2 * 2
56/// assert_eq!(sum, 127 * 128);
57/// ```
58pub fn inplace_or_alloc_array<T, R, Consumer>(size: usize, consumer: Consumer) -> R
59 where Consumer: FnOnce(UninitializedSliceMemoryGuard<T>) -> R
60{
61 match try_inplace_array(size, consumer) {
62 Ok(result) => result,
63 Err(consumer) => alloc_array(size, consumer),
64 }
65}
66
67/// `inplace_or_alloc_from_iter` is helper function used to easy trying to place data from `Iterator`.
68///
69/// It tries to get upper bound of `size_hint` of iterator and forward it to `inplace_or_alloc_array` function.
70/// It there is not upper bound hint from iterator, then it just `collect` your data into `Vec`.
71///
72/// If iterator contains more data that `size_hint` said
73/// (and more than `try_inplace_array` function placed on stack),
74/// then items will be moved and collected (by iterating) into `Vec` also.
75///
76/// # Examples
77///
78/// ```rust
79/// // Some random number to demonstrate
80/// let count = 42;
81/// let iterator = 0..count;
82///
83/// let result = ::inplace_it::inplace_or_alloc_from_iter(iterator.clone(), |mem| {
84/// assert_eq!(mem.len(), count);
85/// assert!(mem.iter().cloned().eq(iterator));
86///
87/// // Some result
88/// format!("{}", mem.len())
89/// });
90/// assert_eq!(result, format!("{}", count));
91/// ```
92pub fn inplace_or_alloc_from_iter<Iter, R, Consumer>(iter: Iter, consumer: Consumer) -> R
93 where Iter: Iterator,
94 Consumer: FnOnce(&mut [Iter::Item]) -> R,
95{
96 match iter.size_hint().1 {
97 Some(upper_bound_hint) => {
98 inplace_or_alloc_array(upper_bound_hint, |uninitialized_guard| {
99 match uninitialized_guard.init_with_dyn_iter(iter) {
100 Ok(mut guard) => consumer(&mut *guard),
101 Err(mut vec) => consumer(&mut *vec),
102 }
103 })
104 }
105 None => {
106 let mut vec = iter.collect::<Vec<_>>();
107 consumer(&mut *vec)
108 }
109 }
110}