Function step_count_checked

Source
pub fn step_count_checked<T: Step + Default>(
    iter: impl IntoIterator,
) -> Option<T>
Expand description

Consumes the iterator, counting the number of iterations. This uses the Step trait to keep track of the count of iterations. The count starts from the default value provided by the Default trait. Returns None if the count exceeded the capcity of the count type (T).

This function always fully consumes the iterator, even if None is returned.

Note: This function takes any implementation of IntoIterator, which includes iterators themselves.

ยงExamples

Basic usage:

let arr = [1, 2, 3];
let count: Option<u16> = step_count_checked(arr);
assert_eq!(count, Some(3));

Overflow:

let arr = [(); u8::MAX as usize + 1];
let count: Option<u8> = step_count_checked(arr);
assert!(count.is_none());

Consumption:

let mut range = -1..u8::MAX as isize;
let count: Option<u8> = step_count_checked(&mut range);
assert!(count.is_none());
assert!(range.is_empty());