Module trie_rs::try_collect

source ·
Expand description

Try to collect from an iterator; operation may fail.

Any type can that be collect()ed can be try_collect()ed without fail.

§Usage

The simplest usage is like this.

use trie_rs::try_collect::*;
let bytes: Vec<u8> = vec![72, 105];
let s: String = bytes.into_iter().try_collect().unwrap();
assert_eq!(s, "Hi");

§Motivation

I really wanted to be able to turn a Iterator<Item = u8> into a String more easily, so that one could accumulate trie entries as Vec<u8>s or as Strings. This is made complicated by the fact that String does not have a FromIterator<u8> implementation, and the method it does have from_utf8() is fallible; it returns a Result.

Thus TryFromIterator is simply a fallible version of std::iter::FromIterator. And try_collect() is collect() fallible cousin as well.

§Technical Note

TryFromIterator<A, M> accepts a generic type M marker parameter. In general usage, the caller will simply pass along a generic M type.

The reason it exists is so we can specify a blanket implementation of TryFromIterator for all std::iter::FromIterators, and we can also specify one for String.

Without this marker type, it’s not possible to have a blanket and specialized implementation of the trait.

Traits§