Skip to main content

bcd

Macro bcd 

Source
macro_rules! bcd {
    ($v:expr) => { ... };
}
Expand description

Constructs a Bcd from an unsigned integer expression, panicking on overflow.

The value is cast to u128 and then dispatched at runtime to the smallest try_from_* method capable of holding it. This keeps the double-dabble loop short for small values without requiring the caller to pick the right method.

This macro is const-usable, so it can construct Bcd values in const items and other const contexts.

§Signed values

This macro accepts any expression that can be cast to u128. Passing a negative value is a logic error: the value is reinterpreted as an unsigned integer via the as cast, which will almost always overflow the target Bcd<BYTES> and panic. Use one of the try_from_* methods directly if you need explicit control over the source type.

§Panics

Panics if the value overflows the Bcd<BYTES> that type inference selects.

§Examples

use const_bcd::{Bcd, bcd};

let n: Bcd<2> = bcd!(1234u16);
assert_eq!(n.to_string(), "1234");

// Works with expressions, not just literals
let x = 56u8;
let n: Bcd<1> = bcd!(x);
assert_eq!(n.to_string(), "56");

// Works in const context
const M: Bcd<4> = bcd!(12345678u32);
assert_eq!(M.to_string(), "12345678");

// Works with u128-range values
let n: Bcd<20> = bcd!(u128::MAX);
assert_eq!(n.to_string(), u128::MAX.to_string());