[][src]Macro bounded_integer_macro::bounded_integer

bounded_integer!() { /* proc-macro */ }

Generate a bounded integer type.

It takes in single struct or enum, with the content being any range expression, which can be inclusive or not. The attributes and visibility (e.g. pub) of the type are forwarded directly to the output type. It also implements:

  • Debug, Display, Binary, LowerExp, LowerHex, Octal, UpperExp and UpperHex
  • Hash
  • Clone and Copy
  • PartialEq and Eq
  • PartialOrd and Ord
  • If the serde feature is enabled, Serialize and Deserialize

The item must have a repr attribute to specify how it will be represented in memory, and it must be a u* or i* type.

Examples

With a struct:

bounded_integer! {
    #[repr(i8)]
    pub struct S { -3..2 }
}

The generated item should look like this:

#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct S(i8);

And the methods will ensure that -3 <= S.0 < 2.

With an enum:

bounded_integer! {
    #[repr(i8)]
    pub enum S { 5..=7 }
}

The generated item should look like this:

#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(i8)]
pub enum S {
    P5 = 5, P6, P7
}

Custom path to bounded integer

If your are using the serde feature and have bounded_integer at a path other than ::bounded_integer, then you will need to tell bounded_integer the correct path. For example if bounded_integer is instead located at path::to::bounded_integer:

bounded_integer! {
    #[repr(i8)]
    #[bounded_integer = path::to::bounded_integer]
    pub struct S { 5..7 }
}

Limitations

  • Both bounds of enum ranges must be closed and be a simple const expression involving only literals and the following operators:
    • Negation (-x)
    • Addition (x+y), subtraction (x-y), multiplication (x*y), division (x/y) and remainder (x%y).
    • Bitwise not (!x), XOR (x^y), AND (x&y) and OR (x|y).
  • The above limitations do not apply to struct ranges.