collect_failable
A set of traits for collecting values into containers that must uphold invariants during construction or extension. These traits let you propagate structured errors instead of panicking or silently discarding data. Examples include preventing duplicate keys in a HashMap or respecting capacity limits in types like ArrayVec.
Traits
This crate provides several complementary traits for failable collection:
TryFromIterator– failably build a container from anIntoIterator.TryCollectEx– failably collect anIntoIteratorinto a container.TryExtendandTryExtendSafe– failably extend a container with anIntoIterator, with different error guarantees.TryExtendOne– failable extend a container with a single item.TryUnzip– failably unzip anIntoIteratorof pairs into two containers (requires featuretuple, enabled by default).Capacity- expose capacity size hints for collection types (e.g.,ArrayVec).
Additionally, several implementations are provided for common and popular containers. See the implementations section for more details.
Installation
It's on crates.io.
Features
This crate provides the following optional features:
alloc(default) – Enables support for allocation-dependent types (BTreeMap,BTreeSet,Result,Rc,Vec,Box). Required for most functionality. When disabled, only the core traits are available.std(default) – Enables standard library support, includingHashMapandHashSetimplementations. When disabled, the crate operates inno_stdmode withalloc.unsafe(default) – EnablesTryFromIteratorimplementations for arrays using unsafe code.tuple(default) – Enables tuple extension (TryExtendfor tuples) andTryUnziptrait, requiring a public dependency on theeithercrate (re-exported ascollect_failable::Either).arrayvec– EnablesTryFromIteratorandTryExtendimplementations forArrayVec.hashbrown– EnablesTryFromIteratorandTryExtendimplementations forhashbrown::HashMapandhashbrown::HashSet.indexmap– EnablesTryFromIteratorandTryExtendimplementations forindexmap::IndexMapandindexmap::IndexSet.
No-std Support
This crate supports no_std environments when the std feature is disabled. The alloc feature provides allocation-dependent functionality (BTreeMap, BTreeSet, etc.) without requiring the full standard library.
Note: HashMap and HashSet require the std feature because they depend on the standard library's default hasher. For no_std environments, consider BTreeMap/BTreeSet (with alloc) or hashbrown/indexmap (with their respective features).
Usage
TryFromIterator and TryCollectEx
Construct a container from an iterator, with errors for invalid input. This behaves like FromIterator but returns Result<Self, E> instead of panicking or ignoring failures.
use BTreeMap;
use TryFromIterator;
// try_from_iter is the core method - works on any TryFromIterator implementor
let map = try_from_iter.expect;
assert_eq!;
// duplicate keys produce an error containing the colliding item
let err = try_from_iter.expect_err;
assert_eq!;
// errors contain all data needed to reconstruct the consumed iterator
// order is: rejected item, then collected items, then remaining iterator
let recovered: = err.into_iter.collect;
assert_eq!;
TryCollectEx provides a more convenient alternative, similar to collect
use HashMap;
use TryCollectEx;
let map: = .into_iter.try_collect_ex.unwrap;
assert_eq!;
TryExtend and TryExtendSafe
Extend an existing container with items that may violate its invariants. Two different trait exposes two styles of error behavior:
TryExtendSafe– strong guarantee on an error, the container must remain unchanged.TryExtend– basic guarantee the container may have partially ingested items, but must remain valid.
Use TryExtendSafe if you must avoid mutation on failure; otherwise, prefer the faster TryExtend.
use HashMap;
use TryExtendSafe;
let mut map = new;
map.try_extend_safe.expect;
assert_eq!;
// on a failure, the container is not modified
map.try_extend_safe.expect_err;
assert_eq!;
TryExtendOne
Extend a collection with a single item. This trait always provides a strong guarantee: on failure, the collection remains unchanged. Implemented as a seperate trait with no default implementation due to limitations imposed by the trait definition.
TryUnzip
Fallible equivalent of Iterator::unzip. Given an iterator of (A, B) items, produce two collections that implement Default + TryExtend, stopping on the first failure.
use ;
use TryUnzip;
// Unzip into two different container types
let data = vec!;
let : = data.into_iter.try_unzip.expect;
assert_eq!;
assert_eq!;
Implementations
Implementations for various containers are provided.
- HashMap, HashSet (feature
std, enabled by default) - BTreeMap, BTreeSet (feature
alloc, enabled by default) - Array (feature
unsafe, enabled by default) - ArrayVec (feature
arrayvec) - hashbrown::HashMap, hashbrown::HashSet (feature
hashbrown) - indexmap::IndexMap, indexmap::IndexSet (feature
indexmap)
Tuple Implementations
Tuples of arity 2 implement TryExtend when their inner types do (requires feature tuple, enabled by default). For constructing tuple collections from IntoIterator TryUnzip is available.
Array Implementation
Arrays implement TryFromIterator for IntoIterator that yield exactly the right number of elements. This uses unsafe internally and is gated behind the unsafe feature (enabled by default).
Result Implementation
TryFromIterator is implemented for Result<C, E>, where C implements TryFromIterator<T>, similar to the FromIterator implementation for Result. This allows short-circuiting collection of failable values into a container whose construction is also failable.