#non-zero #iterator #count #traits #empty #elements #extend

count-to-non-zero

Extends Rust’s Iterator trait to include a count_to_non_zero method, returning an Option for a more expressive and type-safe way of counting elements. This crate provides a convenient and idiomatic approach to obtaining non-zero element counts from iterators, enhancing code readability and safety by leveraging Rust’s type system. Perfect for applications where distinguishing between empty and non-empty iterators is crucial, without the overhead of manual count checks.

1 unstable release

0.3.0 Mar 16, 2024

#1581 in Rust patterns

Download history 32/week @ 2024-07-22 19/week @ 2024-07-29 9/week @ 2024-08-05 2/week @ 2024-08-12 8/week @ 2024-09-02 1/week @ 2024-09-16 18/week @ 2024-09-23 28/week @ 2024-09-30 15/week @ 2024-10-14 41/week @ 2024-11-04

56 downloads per month

MIT/Apache

6KB

CountToNonZero

Overview

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.

Features

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>.

Usage

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"),
    }
}

No runtime deps