pub trait AtMost<T, E, Factory>: Iterator<Item = Result<T, E>> + Sized{
// Provided method
fn at_most(
self,
min_count: usize,
factory: Factory,
) -> AtMostIter<Self, T, E, Factory> { ... }
}
Provided Methods§
sourcefn at_most(
self,
min_count: usize,
factory: Factory,
) -> AtMostIter<Self, T, E, Factory>
fn at_most( self, min_count: usize, factory: Factory, ) -> AtMostIter<Self, T, E, Factory>
Fails a validation iterator if it contains more than n
elements.
at_most(n, factory)
yields Ok(element)
values until n
elements are yielded,
or the end of the iterator is reached. If values are still in the iteration,
factory
will be applied on these together with the index of the error.
Elements already wrapped in Result::Err
will not be
counted towards reaching the n
elements upper bound.
§Examples
Basic usage:
struct MoreThan2(usize, i32);
let a = [1, 2, 3];
let mut iter = a.iter().map(|v| Ok(v)).at_most(2, |index, val| MoreThan2(index, *val));
assert_eq!(iter.next(), Some(Ok(&1)));
assert_eq!(iter.next(), Some(Ok(&2)));
assert_eq!(iter.next(), Some(Err(MoreThan2(2, 3))));
Generally, at_most
could be thought of as a not-quite-as-useful
complement to the at_least
adapter. It could also be used to ensure
that collecting an iterator does not result in an unexpected amount
of values in-memory:
struct MoreThan10;
let collection_result: Result<Vec<_>, _> = (0..)
.take(1_000_000_000)
.map(|i| Ok(i))
.at_most(10, |_, _| MoreThan10)
.collect::<Result<_, _>>();
assert_eq!(collection_result, Err(MoreThan10));
at_most
will not account for errors already in the iteration:
use validiter::AtMost;
#[derive(Debug, PartialEq)]
enum ValidErr {
OtherError(i32),
AtMostErr,
}
let mut iter = [Err(ValidErr::OtherError(0)), Ok(1)]
.into_iter()
.at_most(1, |_, _| ValidErr::AtMostErr);
assert_eq!(iter.next(), Some(Err(ValidErr::OtherError(0))));
assert_eq!(iter.next(), Some(Ok(1)));
Examples found in repository?
examples/collect_vec_with_max_len_simple_validation.rs (line 9)
6 7 8 9 10 11 12 13 14 15 16 17
fn main() {
let collection_failure = (0..10)
.map(|i| Ok(i))
.at_most(7, |err_index, i| TooMany(err_index, i))
.collect::<Result<Vec<_>, _>>();
match collection_failure {
Ok(_vector) => unreachable!(),
Err(TooMany(i, v)) => print!(
"{v} is the first value obtained after reaching limit, at index {i} of the iteration"
),
}
}
Object Safety§
This trait is not object safe.