Macro bounded_integer::bounded_integer
source · [−]macro_rules! bounded_integer {
($($tt:tt)*) => { ... };
}macro only.Expand description
Generate a bounded integer type.
It takes in single struct or enum, with the content being a bounded range expression, whose
upper bound can be inclusive (x..=y) or exclusive (x..y). The attributes and visibility
(e.g. pub) of the type are forwarded directly to the output type.
See the examples module for examples of what this macro generates.
Examples
With a struct:
bounded_integer! {
pub struct S { -3..2 }
}The generated item should look like this (i8 is chosen as it is the smallest repr):
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct S(i8);And the methods will ensure that -3 <= S.0 < 2.
With an enum:
bounded_integer! {
pub enum S { 5..=7 }
}The generated item should look like this (u8 is chosen as it is the smallest repr):
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum S {
P5 = 5, P6, P7
}Custom repr
The item can have a repr attribute to specify how it will be represented in memory, which can
be a u* or i* type. In this example we override the repr to be a u16, when it would
have normally been a u8.
bounded_integer! {
#[repr(u16)]
pub struct S { 2..5 }
}The generated item should look like this:
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct S(u16);Limitations
- Both bounds of ranges must be closed and 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).
- Negation (