collect_with/
collect_vec.rs

1use alloc::vec::Vec;
2
3use crate::collect::CollectWith;
4
5/// Blanket implementation for iterators to add vector collection capabilities.
6///
7/// Provides `collect_vec_with()` and `collect_vec_with_exact()` methods
8impl<I: Iterator> CollectVector for I {}
9
10/// Trait providing enhanced vector collection strategies for iterators.
11///
12/// Essentially, it calls the `CollectWith` trait, simplifying
13/// `.collect_with::<Vec<_>>()` to `.collect_vec_with()`.
14///
15/// Extends iterators with methods for collecting items into a `Vec` with
16/// customizable capacity pre-allocation strategies.
17pub trait CollectVector: Iterator {
18  /// Collect iterator elements into a `Vec` with capacity calculation.
19  ///
20  /// - capacity:
21  ///   - Closure that calculates capacity based on iterator size hints.
22  /// - `|size_bound|`: `max(lower_bound, upper_bound)` from the iterator's
23  ///   `size_hint()`
24  ///
25  /// ## About the Final Capacity Size
26  ///
27  /// For example, `(0..10).collect_vec_with(|_size_bound| 2)`:
28  ///
29  /// 1. `(0..10).size_hint()` returns `(10, Some(10))`.
30  /// 2. _size_bound is 10.
31  /// 3. The closure returns 2, the final capacity is `max(10, 2)` = 10.
32  /// 4. The vector is created with Vec::with_capacity(10).
33  ///
34  /// If you need an exact capacity size, please use
35  /// [.collect_vec_with_exact()](crate::CollectVector::collect_vec_with_exact)
36  ///
37  /// ## Example
38  ///
39  /// ```
40  /// use collect_with::CollectVector;
41  ///
42  /// let nums = (0..10).collect_vec_with(|size_bound| size_bound + 2);
43  /// assert_eq!(nums.capacity(), 12);
44  /// ```
45  ///
46  /// Suitable when the exact element count is unknown but better-than-default
47  /// pre-allocation is desired.
48  fn collect_vec_with<F>(self, capacity: F) -> Vec<Self::Item>
49  where
50    F: FnOnce(usize) -> usize,
51    Self: Sized,
52  {
53    self.collect_with(capacity)
54  }
55
56  /// Collect iterator elements into a Vec with exact capacity calculation.
57  ///
58  /// ## Example
59  ///
60  /// ```
61  /// use collect_with::CollectVector;
62  ///
63  /// let _nums = (0..10)
64  ///   .collect_vec_with_exact(|size_bound| match size_bound {
65  ///     0 => 32,
66  ///     u => u,
67  /// });
68  /// ```
69  ///
70  /// Preferred when iterator provides exact size information via size_hint()
71  /// and precise allocation is critical.
72  fn collect_vec_with_exact<F>(self, capacity: F) -> Vec<Self::Item>
73  where
74    F: FnOnce(usize) -> usize,
75    Self: Sized,
76  {
77    self.collect_with_exact(capacity)
78  }
79}