#literals #non-zero #macro

nzliteral

Macro simplifying use of NonZero literals

2 releases

0.5.1 Jan 31, 2025
0.5.0 Jan 28, 2025

#874 in Rust patterns

Download history 213/week @ 2025-01-27 26/week @ 2025-02-03

239 downloads per month

Artistic-2.0

8KB
100 lines

nzliteral

The NonZero<T> types are really useful for defining variables that cannot be zero. The one annoying issue I keep running into is creating values from literals that I know cannot be 0, and still having to unwrap() or expect() to get the resulting NonZero<T> value.

This crate provides the nzliteral macro that fails to compile if it is supplied a 0. If called with a non-zero literal, the macro creates the NonZero<T> value and automatically unwrap()s it.


lib.rs:

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

No runtime deps