nonzero_ext

Traits to represent generic nonzero integer types

Rust ships with non-zero integer types now, which let programmers promise (memory-savingly!) that a number can never be zero. That's great, but sadly the standard library has no traits you can use to represent all the non-zero integer types.

Examples

Where this lack of traits in the standard library becomes problematic is if you want to write a function that takes a vector of integers, and that returns a vector of the corresponding non-zero integer types, minus any elements that were zero in the original. You can write that with the standard library quite easily for concrete types:

``` rust

use core::num::NonZeroU8;

fn onlynonzeros(v: Vec) -> Vec { let out: Vec = v .intoiter() .filtermap(|n| NonZeroU8::new(n)) .collect(); out } let expected: Vec = vec![NonZeroU8::new(20).unwrap(), NonZeroU8::new(5).unwrap()]; asserteq!(expected, only_nonzeros(vec![0, 20, 5])); ```

But what if you want to allow this function to work with any integer type that has a corresponding non-zero type? This crate can help:

``` rust fn onlynonzeros(v: Vec) -> Vec where I: Sized + NonZeroAble { let out: Vec = v .intoiter() .filtermap(|n| n.asnonzero()) .collect(); out }

// It works for u8: let inputu8: Vec = vec![0, 20, 5]; let expectedu8: Vec = vec![NonZeroU8::new(20).unwrap(), NonZeroU8::new(5).unwrap()]; asserteq!(expectedu8, onlynonzeros(inputu8));

// And it works for u32: let inputu32: Vec = vec![0, 20, 5]; let expectedu32: Vec = vec![NonZeroU32::new(20).unwrap(), NonZeroU32::new(5).unwrap()]; asserteq!(expectedu32, onlynonzeros(inputu32)); ```

License: Apache-2.0