transparent_newtype

Macro transparent_newtype 

Source
macro_rules! transparent_newtype {
    (
        $(#[$($struct_attr:tt)*])*
        $vis:vis struct $newtype:tt$(<$gen:ident $(= $default:ty)?>)?($($fields:tt)+) $(where $($where_ty:ty: $bound:path),* $(,)?)?;

        impl$(<$gen2:tt>)? $newtype2:ident$(<$gen3:tt>)? {
            $(
                $(#[$($fn_attr:tt)*])*
                $fn_vis:vis $(const)? fn $fn:ident($fn_arg_name:ident: $($fn_arg_ty:tt)+) -> $fn_ret_ty:ty;
            )*
        }
    ) => { ... };
}
Expand description

Constructs a transparent wrapper around an inner type and soundly implements reference casts.

This macro takes care of several issues related to newtypes that need to allow casting their inner types to themselves:

  • It makes sure to put repr(transparent) on the type
  • It optionally implements conversions from &, &mut, Box, Rc, Arc
  • It makes sure to put #[inline] on all of these conversions since they are trivial
  • It makes sure the reference cast is const
  • It makes sure the Arc conversion is conditioned on target_has_atomic = "ptr"

Usage: just type the struct inside the macro as you would implementing it manually except leave #[repr(transparent)] out. Then add an impl block for the just-defined type containing function declarations that take a reference/smart pointer to _ (use literal underscore; e.g. &_ for shared references) and return Self behind the appropriate “pointer” type. Do not write the body, just semicolon.

The alloc types MUST NOT have import paths and don’t need imports.