Skip to content
/ nz Public

Collection of 100% safe macros for creating non-zero integers more easily.

License

MIT, Zlib licenses found

Licenses found

MIT
LICENSE-MIT.md
Zlib
LICENSE-ZLIB.md
Notifications You must be signed in to change notification settings

noelhorvath/nz

Repository files navigation

nz

github crates.io docs.rs rust-ci msrv unsafety license

The nz crate provides a collection of macros that simplify the creation of non-zero integers implemented in core::num. With these macros, you can easily generate constants of all the NonZero- prefixed types using literals, constant values or expressions at compile time.

Changelog

All changes to nz crate are documented in changelog.md.

Features

  • No unsafe code
  • No dependencies
  • no_std compatible
  • Supports all non-zero types in core::num
  • Compile-time evaluation

Macros

Type Macro
NonZeroI8 nz::i8!
NonZeroI16 nz::i16!
NonZeroI32 nz::i32!
NonZeroI64 nz::i64!
NonZeroI128 nz::i128!
NonZeroIsize nz::isize!
NonZeroU8 nz::u8!
NonZeroU16 nz::u16!
NonZeroU32 nz::u32!
NonZeroU64 nz::u64!
NonZeroU128 nz::u128!
NonZeroUsize nz::usize!

Usage

use core::num::NonZeroU8;

// A `NonZero*` type can be constructed by different types of
// arguments when using the matching `nz` macro.
// Such argument can be an integer literal,
const NZ_MIN: NonZeroU8 = nz::u8!(1);
let nz_two = nz::u8!(2);
// a constant value,
const NZ_MAX: NonZeroU8 = nz::u8!(u8::MAX);
const SIX: u8 = 6;
let six = nz::u8!(SIX);
// or even a constant expression.
const RES: NonZeroU8 = nz::u8!({ 3 + 7 } - NZ_MIN.get());
let res = nz::u8!((NZ_MIN.get() & NZ_MAX.get()) + 7);
let five = nz::u8!({ const FIVE: u8 = 5; FIVE });
// However, a non-constant expression results in a compile-time error.
// const __ERR: NonZeroU8 = nz::u8!({ 3 + 7 } - nz_two.get());

Limitations

Declarative macro hygiene

Declarative macro is not hygienic when it comes to items. As a result, if the outermost constant item _NZ_INTERNAL_NUM_VALUE_1_ is referenced in the macro argument, a cyclic dependency error occurs as shown in the below examples.

Non-expanded

const __ERR: NonZeroI8 = nz::i8!(_NZ_INTERNAL_NUM_VALUE_1_ + 0x2C);

Expanded

const _ERR: NonZeroI8 = {
    const _NZ_INTERNAL_NUM_VALUE_1_: i8 = _NZ_INTERNAL_NUM_VALUE_1_ + 0x2C;
    {
        /* rest of the expanded code */
    }
};

License

This library is distributed under the terms of either of the following licenses at your option:

About

Collection of 100% safe macros for creating non-zero integers more easily.

Topics

Resources

License

MIT, Zlib licenses found

Licenses found

MIT
LICENSE-MIT.md
Zlib
LICENSE-ZLIB.md

Stars

Watchers

Forks

Languages