Skip to main content

n

Macro n 

Source
macro_rules! n {
    ($literal_str: literal) => { ... };
    ($ty: ident) => { ... };
    ($($_: tt)*) => { ... };
}
Expand description

Create constant Integer values from native integer literals.

n! converts integer literals to Integer values at compile time. It supports literals in base 2, 8, 10 and 16:

  • The prefix 0b indicates a binary literal (base 2).
  • The prefix 0o indicates an octal literal (base 8).
  • The prefix 0x indicates a hexadecimal literal (base 16).
  • Literals are treated as decimal literals (base 10) if no prefix is specified.

n! accepts two forms of integer literal as input:

  1. Suffix-free, e.g. n!(0xABCDEF). In this case, the const-generic parameters of the created Integer are left unspecified, so this must be used in a context where type inference can determine the parameters. For example: let a: Integer<false, 16> = n!(0xABCDEF); would be valid, but let b = n!(0xABCDEF); would trigger a compile error (unless b was subsequently used in a context which allowed for type inference).
  2. With a suffix, e.g. n!(0xabcdefU128w). The suffix may be any valid argument to the t! macro. The suffix is referred to as a type descriptor, as it specifies the values of the const-generic parameters of the created Integer. For more information about valid type descriptors, see the documentation of the t! macro.

Invoking n! with invalid arguments will also trigger a compile error. This can happen if:

  • The literal is out of range for the target type (works for inferred types and types specified by a suffix). Note that this will always cause a compile error, regardless of the overflow mode of the type.
  • The literal contains an invalid digit.
  • A - sign appears at the start of the literal when the type is unsigned, e.g. n!(-123U256).
  • The suffix is an invalid type descriptor.

§Examples

use bnum::prelude::*; // n! and t! are re-exported in the prelude
 
let a: t!(U256) = n!(0xABCDEF); // type inferred from context
use bnum::prelude::*;
 
let b = n!(123456_I511s); // type specified by the suffix
// suffix specifies signed 511-bit integer with saturating overflow behaviour
// note that we don't need to define a type alias I511s here

The following example will fail to compile, since the compiler is unable to infer the type of the integer:

use bnum::prelude::*;
 
let a = n!(0o7654321);

The following example will fail to compile, since the literal is out of range for the specified type:

use bnum::prelude::*;
 
let c = n!(0x1000000U24);

The following example will fail to compile, since the literal contains an invalid digit for the specified base:

use bnum::prelude::*;
use bnum::types::I256;
 
let d: I256 = n!(1234A);

The following example will fail to compile, since the given type descriptor is invalid:

use bnum::prelude::*;
 
let e = n!(12345U1024x);