Crates.io | count-to-non-zero |
lib.rs | count-to-non-zero |
version | 0.3.0 |
source | src |
created_at | 2024-03-16 22:10:50.317883 |
updated_at | 2024-03-16 22:10:50.317883 |
description | Extends Rust's Iterator trait to include a `count_to_non_zero` method, returning an Option |
homepage | |
repository | https://github.com/cyphersnake/count-non-zero.git |
max_upload_size | |
id | 1176019 |
size | 5,039 |
The CountToNonZeroExt crate provides an extension trait for Rust's standard Iterator
trait, enabling the counting of non-zero elements in iterators in a way that returns an Option<NonZeroUsize>
. This approach optimally integrates with Rust's type system to offer a compile-time guarantee that the result, when present, is indeed non-zero. This functionality is particularly useful in scenarios where distinguishing between zero and non-zero counts is critical and can lead to more efficient code by leveraging the NonZeroUsize type's ability to optimize memory layouts and conditional logic.
Extends the Iterator
trait with the count_to_non_zero
method.
The count_to_non_zero
method counts the elements for which the iterator yields values, returning an Option<NonZeroUsize>
.
use std::num::NonZeroUsize;
use count_to_non_zero::CountToNonZeroExt;
fn main() {
let data = vec![1, 2, 0, 4];
let count = data.into_iter().filter(|el| el % 2 == 0).count_to_non_zero();
match count {
Some(non_zero_count) => println!("Non-zero count of elements: {}", non_zero_count),
None => println!("Iterator is empty"),
}
}