Struct PaddedNumber

Source
pub struct PaddedNumber<const A: u8 = 1, const B: u8 = { u8::MAX }> { /* private fields */ }
Expand description

Newtype encapsulating the padded number invariants

Consists only of an u8 and an u64 which keep track of the leading zeros count and the remaining number value respectively.

Check out the crate-level documentation for an introduction.

PaddedNumber uses const generic parameters for setting lower (inclusive) and upper (inclusive) length bounds. These parameters are by default set to 1 and 255 (u8::MAX) respectively.

  • MIN < MAX allows for variable digit length.
  • MIN == MAX requires the digit to be exactly of length MIN/MAX.
  • MIN == 0 results in empty values (“”) being allowed as valid numbers.
  • MIN > MAX, where MIN, MAX > 0 is technically declarable, but any attempts at constructing such a padded number will fail.

Implementations§

Source§

impl<const A: u8, const B: u8> PaddedNumber<A, B>

Source

pub const fn try_new(str: &str) -> Result<Self, ParsePaddedNumberError>

Create a new PaddedNumber

Source

pub const fn len(&self) -> u8

Calculate the length of the padded number, including any leading zeros

assert_eq!(2, padded_number!("01").len());
assert_eq!(3, padded_number!("123").len());
Source

pub const fn is_empty(&self) -> bool

Check if the number if empty, e.g. if and only if it is "".

assert!(bound_padded_number!(0, 1, "").is_empty());
assert!(!padded_number!("01").is_empty());
Source§

impl<const A: u8, const B: u8> PaddedNumber<A, B>

Source

pub fn wrapping_add(self, rhs: u64) -> Self

Wrapping addition with u64 as right-hand side

Used within the impl Add<u64> for PaddedNumber implementation.

assert_eq!(padded_number!("0") + 1, padded_number!("0").wrapping_add(1));

// Within bounds
assert_eq!(padded_number!("9") + 1, padded_number!("00"));
assert_eq!(padded_number!("80") + 11, padded_number!("91"));

// Wrapped
assert_eq!(
    bound_padded_number!(2, 3, "999") + 2,
    bound_padded_number!(2, 3, "01")
);
Source

pub fn saturating_add(self, rhs: u64) -> Self

Saturating addition with u64 as right-hand side

assert_eq!(
    bound_padded_number!(2, 3, "990").saturating_add(1000),
    bound_padded_number!(2, 3, "999") // saturated
);

Addition within bounds behaves the same as in Self::wrapping_add.

Source

pub fn wrapping_sub(self, rhs: u64) -> Self

Wrapping subtraction with u64 as right-hand side

Used within the impl Sub<u64> for PaddedNumber implementation.

assert_eq!(padded_number!("9") - 1, padded_number!("9").wrapping_sub(1));

// Within bounds
assert_eq!(padded_number!("9") + 1, padded_number!("00"));
assert_eq!(padded_number!("80") + 11, padded_number!("91"));

// Wrapped
assert_eq!(
    bound_padded_number!(2, 3, "999") + 2,
    bound_padded_number!(2, 3, "01")
);
Source

pub fn saturating_sub(self, rhs: u64) -> Self

Saturating subtraction with u64 as right-hand side

assert_eq!(
    bound_padded_number!(1, 2, "99").saturating_sub(1000),
    bound_padded_number!(1, 2, "0") // saturated
);

Subtraction within bounds behaves the same as in Self::wrapping_sub.

Source§

impl<const MIN_LENGTH: u8, const MAX_LENGTH: u8> PaddedNumber<MIN_LENGTH, MAX_LENGTH>

Source

pub fn section<const START_INDEX: u8, const END_INDEX: u8>( &self, ) -> Option<PaddedNumber<{ _ }, { _ }>>
where [(); { _ }]:,

Get a section of a padded number

First generic parameter is the start index, inclusive. Second parameter denotes the end index, exclusive. Remaining bound checks are enforced by the type system. E.g. end >= start and end <= max length.

Returns None if the end index overflowed for a padded whose length is is not equal to it’s max length.

§Examples
#![feature(generic_const_exprs)]

let section = padded_number!("00123")
    .section::<2, 5>()
    .expect("section should not have overflowed");

assert_eq!(section, bound_padded_number!(3, 3, "123"));

let section = bound_padded_number!(1, 3, "0").section::<1, 3>();
// overflowed, missing two digits after "0"
assert!(section.is_none());
#![feature(generic_const_exprs)]

let section = bound_padded_number!(3, 3, "123");
section.section::<0, 4>(); // <-- END_INDEX '4' > MAX_LENGTH '3'
#![feature(generic_const_exprs)]

let section = bound_padded_number!(3, 3, "123");
section.section::<2, 1>(); // <-- END_INDEX '1' < START_INDEX '2'
Source

pub fn expected_section<const START_INDEX: u8, const END_INDEX: u8>( &self, ) -> PaddedNumber<{ _ }, { _ }>
where [(); { _ }]:,

Get a section from the minimum length of a padded number

Unlike PaddedNumber::section, this does not need to return an option. Type system ensures that END_INDEX <= MIN_LENGTH.

§Examples
#![feature(generic_const_exprs)]

let section = bound_padded_number!(3, 5, "00123").expected_section::<0, 3>();
assert_eq!(section, bound_padded_number!(3, 3, "001"));
#![feature(generic_const_exprs)]

let section = bound_padded_number!(3, 5, "00123");
section.expected_section::<0, 4>(); // <-- END_INDEX '4' > MIN_LENGTH '3'

Trait Implementations§

Source§

impl<const A: u8, const B: u8> Add<u64> for PaddedNumber<A, B>

Source§

type Output = PaddedNumber<A, B>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: u64) -> Self::Output

Performs the + operation. Read more
Source§

impl<const A: u8, const B: u8> Clone for PaddedNumber<A, B>

Source§

fn clone(&self) -> PaddedNumber<A, B>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const A: u8, const B: u8> Debug for PaddedNumber<A, B>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, const A: u8, const B: u8> Deserialize<'de> for PaddedNumber<A, B>

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<const A: u8, const B: u8> Display for PaddedNumber<A, B>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<const A: u8, const B: u8> FromStr for PaddedNumber<A, B>

Source§

type Err = ParsePaddedNumberError

The associated error which can be returned from parsing.
Source§

fn from_str(str: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl<const A: u8, const B: u8> Hash for PaddedNumber<A, B>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<const A: u8, const B: u8> Ord for PaddedNumber<A, B>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<const A: u8, const B: u8> PartialEq for PaddedNumber<A, B>

Source§

fn eq(&self, other: &PaddedNumber<A, B>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<const A: u8, const B: u8> PartialOrd for PaddedNumber<A, B>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<const A_0: u8, const B_0: u8, const A_1: u8, const B_1: u8> ResizePaddedNumber<A_1, B_1> for PaddedNumber<A_0, B_0>
where [(); { _ }]:,

Source§

fn resize(&self) -> PaddedNumber<A_1, B_1>

Resize a padded number Read more
Source§

impl<const A: u8, const B: u8> Serialize for PaddedNumber<A, B>

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<const A: u8, const B: u8> Sub<u64> for PaddedNumber<A, B>

Source§

type Output = PaddedNumber<A, B>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: u64) -> Self::Output

Performs the - operation. Read more
Source§

impl<const A: u8, const B: u8> Copy for PaddedNumber<A, B>

Source§

impl<const A: u8, const B: u8> Eq for PaddedNumber<A, B>

Source§

impl<const A: u8, const B: u8> StructuralPartialEq for PaddedNumber<A, B>

Auto Trait Implementations§

§

impl<const A: u8, const B: u8> Freeze for PaddedNumber<A, B>

§

impl<const A: u8, const B: u8> RefUnwindSafe for PaddedNumber<A, B>

§

impl<const A: u8, const B: u8> Send for PaddedNumber<A, B>

§

impl<const A: u8, const B: u8> Sync for PaddedNumber<A, B>

§

impl<const A: u8, const B: u8> Unpin for PaddedNumber<A, B>

§

impl<const A: u8, const B: u8> UnwindSafe for PaddedNumber<A, B>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,