Macro def_usize_addr

Source
macro_rules! def_usize_addr {
    (
        $(#[$meta:meta])*
        $vis:vis type $name:ident;

        $($tt:tt)*
    ) => { ... };
    () => { ... };
}
Expand description

Creates a new address type by wrapping an usize.

For each $vis type $name;, this macro generates the following items:

  • Definition of the new address type $name, which contains a single private unnamed field of type usize.
  • Default implementations (i.e. derived implementations) for the following traits:
    • Copy, Clone,
    • Default,
    • Ord, PartialOrd, Eq, and PartialEq.
  • Implementations for the following traits:
    • From<usize>, Into<usize> (by implementing From<$name> for usize),
    • Add<usize>, AddAssign<usize>, Sub<usize>, SubAssign<usize>, and
    • Sub<$name>.
  • Two const methods to convert between the address type and usize:
    • from_usize, which converts an usize to the address type, and
    • as_usize, which converts the address type to an usize.

ยงExample

use memory_addr::{def_usize_addr, MemoryAddr};

def_usize_addr! {
    /// A example address type.
    #[derive(Debug)]
    pub type ExampleAddr;
}

const EXAMPLE: ExampleAddr = ExampleAddr::from_usize(0x1234);
const EXAMPLE_USIZE: usize = EXAMPLE.as_usize();
assert_eq!(EXAMPLE_USIZE, 0x1234);
assert_eq!(EXAMPLE.align_down(0x10usize), ExampleAddr::from_usize(0x1230));
assert_eq!(EXAMPLE.align_up_4k(), ExampleAddr::from_usize(0x2000));