collect_with/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![cfg_attr(__unstable_doc, feature(doc_auto_cfg, doc_notable_trait))]
3/*!
4# collect_with
5
6A utility crate for enhanced collection operations with capacity control.
7
8## Overview
9
10Provides traits for collecting iterators into collections with:
11
12- Precise capacity management
13- Fallible collection operations
14- Feature-gated collection types
15
16## Features
17
18### Standard Library Support
19
20- `std`:
21  - Enables standard library integrations
22  - When disabled, uses `alloc` crate for **no_std** environments
23
24### Collection Specialization
25
26- `collect_vec`:
27  - Enables `CollectVector` trait for enhanced `Vec` collection
28  - Provides `collect_vec_with()` and `collect_vec_with_exact()`
29- `ahash`:
30  - Enables `CollectAHash` trait for AHash-powered hash collections
31  - Provides `collect_ahashmap_with()` and `collect_ahashset_with()`
32- `indexmap`:
33  - Enables `CollectIndex` trait for `IndexMap` & `IndexSet` collections
34  - Provides `collect_indexmap_with()` and `collect_indexset_with()`
35
36### Fallible Collection
37
38- `try`: Enables fallible collection
39  - `TryExtract`: Trait for item extraction with error handling,
40    converting fallible types like `Option<T>` to `Result<T, ()>`.
41  - `TryCollectWith` trait for error-propagating collection
42
43## Examples
44
45### Basic usage with collection
46
47```rust
48use collect_with::CollectWithCapacity;
49
50let numbers = (0..10).collect_with_capacity::<Vec<_>>(20);
51assert_eq!(numbers.capacity(), 20);
52```
53
54```rust
55use collect_with::CollectWith;
56
57let s = [vec!["a"], vec!["b", "c", "d"]]
58  .into_iter()
59  .flatten()
60  .collect_with::<String>(|size| match size {
61    0 => 8,
62    n => n,
63  });
64assert_eq!(s.len(), 4);
65assert_eq!(s.capacity(), 8);
66```
67
68```rust
69# #[cfg(feature = "collect_vec")] {
70use collect_with::CollectVector;
71
72let numbers = (0..10).collect_vec_with(|hint|{
73  match hint {
74    0 => 12,
75    n => n + 5,
76  }
77});
78assert_eq!(numbers.capacity(), 15);
79# }
80```
81
82### Fallible collection (requires `try` feature)
83
84```rust
85# #[cfg(all(feature = "try", feature = "collect_vec"))] {
86let result = [Some(12), Some(42), Some(77)]
87  .into_iter()
88  .try_collect_vec_with(|u| u); // Result<Vec<i32>, ()>
89
90assert_eq!(result.as_deref(), Ok(&[12, 42, 77][..]));
91
92// -----
93use collect_with::{TryCollectWith, TryExtract};
94
95let result = ["42", "76", "abc"]
96  .into_iter()
97  .map(|x| x.parse::<i32>())  // &str -> Result<i32>
98  .try_collect_with::<Vec<_>, _, _>(|u| u + 3); // -> Result<Vec<i32>, ParseIntError>
99
100assert!(result.is_err());
101# }
102```
103
104## About the Final Capacity Size
105
106For example, `(0..10).collect_vec_with(|_size_bound| 2)`
107
1081. `(0..10).size_hint()` returns `(10, Some(10))`.
1092.
110
111- lower_bound = 10 => lower
112- upper_bound = Some(10) => upper
113- `max(lower, upper.unwrap_or(lower))` => 10
114
1153. _size_bound is 10.
1164.
117
118- The closure returns 2
119- The final capacity is `max(_size_bound, 2)` => `max(10, 2)` = 10
120
1215. The vector is created with `Vec::with_capacity(10)`, instead of `Vec::with_capacity(2)`.
122
123If you need an exact capacity size, please use the `.collect_with_exact()` or `.collect_vec_with_exact()`
124
125## Traits
126
127### Core Components
128
129- `ExtendWithCapacity`: Base trait for capacity-aware collections
130- `CollectWith`/`CollectWithCapacity`: Primary collection traits
131
132### Optional Components
133
134- `CollectVector` (feature = "collect_vec"): Specialized Vec collection methods
135- `CollectAHash` (feature = "ahash"): AHash-based collection support
136- `CollectIndex` (feature = "indexmap"): IndexMap/IndexSet collection support
137- `TryExtract`/`TryCollectWith` (feature = "try")
138*/
139
140extern crate alloc;
141
142mod extend;
143pub use extend::ExtendWithCapacity;
144
145// ---------
146mod collect;
147pub use collect::{CollectWith, CollectWithCapacity};
148
149// ---------
150
151#[cfg(feature = "collect_vec")]
152mod collect_vec;
153#[cfg(feature = "collect_vec")]
154pub use collect_vec::CollectVector;
155
156#[cfg(feature = "ahash")]
157mod collect_ahash;
158#[cfg(feature = "ahash")]
159pub use collect_ahash::CollectAHash;
160
161#[cfg(feature = "indexmap")]
162mod collect_index;
163#[cfg(feature = "indexmap")]
164pub use collect_index::CollectIndex;
165// ---------
166#[cfg(feature = "try")]
167mod try_extract;
168#[cfg(feature = "try")]
169pub use try_extract::TryExtract;
170
171#[cfg(feature = "try")]
172mod try_collect;
173#[cfg(feature = "try")]
174pub use try_collect::TryCollectWith;
175
176// ---------
177mod common;