collect_with
A utility crate for enhanced collection operations with capacity control.
Overview
Provides traits for collecting iterators into collections with:
- Precise capacity management
- Fallible collection operations
- Feature-gated collection types
Features
Standard Library Support
std:- Enables standard library integrations
- When disabled, uses
alloccrate for no_std environments
Collection Specialization
collect_vec:- Enables
CollectVectortrait for enhancedVeccollection - Provides
collect_vec_with()andcollect_vec_with_exact()
- Enables
ahash:- Enables
CollectAHashtrait for AHash-powered hash collections - Provides
collect_ahashmap_with()andcollect_ahashset_with()
- Enables
indexmap:- Enables
CollectIndextrait forIndexMap&IndexSetcollections - Provides
collect_indexmap_with()andcollect_indexset_with()
- Enables
Fallible Collection
try: Enables fallible collectionTryExtract: Trait for item extraction with error handling, converting fallible types likeOption<T>toResult<T, ()>.TryCollectWithtrait for error-propagating collection
Examples
Basic usage with collection
collect_with_capacity
use CollectWithCapacity;
let numbers = .;
assert_eq!;
collect_with closure
use CollectWith;
let s =
.into_iter
.flatten
.;
assert_eq!;
assert_eq!;
collect_vec_with
use CollectVector;
let numbers = .collect_vec_with;
assert_eq!;
Fallible collection (requires try feature)
use ;
let result =
.into_iter
.try_collect_vec_with; // -> Result<Vec<i32>, ()>
assert_eq!;
use ;
let result =
.into_iter
.map // &str -> Result<i32>
.; // -> Result<Vec<i32>, ParseIntError>
assert!;
collect indexmap (requires indexmap feature)
use IndexMap;
use CollectIndex;
let map =
.zip
.collect_indexmap_with; // u + 1 => 9 + 1 = 10
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
About the Final Capacity Size
For example, (0..10).collect_vec_with(|_size_bound| 2)
(0..10).size_hint()returns(10, Some(10)).
- lower_bound = 10 => lower
- upper_bound = Some(10) => upper
max(lower, upper.unwrap_or(lower))=> 10
- _size_bound is 10.
- The closure returns 2
- The final capacity is
max(_size_bound, 2)=>max(10, 2)= 10
- The vector is created with
Vec::with_capacity(10), instead ofVec::with_capacity(2).
If you need an exact capacity size, please use the .collect_with_exact() or .collect_vec_with_exact()
Traits
Core Components
ExtendWithCapacity: A trait for collections that can be pre-allocated with specific capacity and extended with elements.CollectWith/CollectWithCapacity: Primary collection traits
Optional Components
CollectVector(feature = "collect_vec"): Specialized Vec collection methodsCollectAHash(feature = "ahash"): AHash-based collection supportCollectIndex(feature = "indexmap"): IndexMap/IndexSet collection supportTryExtract/TryCollectWith(feature = "try")