Crate nzliteral

Crate nzliteral 

Source
Expand description

Macro to easily create NonZero constants

Must be defined from a non-zero literal. Fails to compile if the literal is 0.

The nzliteral!() macro is called with just a literal number. The type of the literal determines the type of NonZero literal to create.

If the literal is a 0, the macro will fail to compile. If the literal is not 0, the macro creates a NonZero value of the appropriate type without dealing with unwrap()ping the result.

If the argument is a variable or an expression, the macro will fail to compile.

I have often found myself creating a non-zero value from a literal that I know cannot be zero, making the unwrap seem to be unnecessary noise. This macro makes that simple case cleaner.

§Examples


use std::num::{NonZeroU16, NonZeroU32, NonZeroI64};
use nzliteral::nzliteral;

// Without nzliteral macro
let a = NonZeroU32::new(17).expect("Hardcoded value cannot be zero");

// Defined just by a typed numeric literal
let b = nzliteral!(17u32);
assert_eq!(a, b);

// Defined by the return type
let c: NonZeroI64 = nzliteral!(9_675_309);
assert_eq!(c.get(), 9_675_309);

// Convert user input into a NonZeroU16, defaulting to 10 if it fails.
let d = NonZeroU16::new(input).unwrap_or(nzliteral!(10u16));

§Description

The type of the NonZero value is determined by the type of the supplied literal (b above) or by the return type (see c above).

Macros§

nzliteral