Derive Macro amplify::Wrapper

source · []
#[derive(Wrapper)]
{
    // Attributes available to this derive:
    #[wrap]
    #[wrapper]
    #[amplify_crate]
}
Expand description

Creates rust new type wrapping existing type. Can be used in sturctures containing multiple named or unnamed fields; in this case the field you’d like to wrap should be marked with #[wrap] attribute; otherwise the first field is assumed to be the wrapped one.

NB: You have to use derive(From) in order foe Wrapper to work properly. Also, in case of multiple fields, each non-wrapped field type must implement Default trait.

Supports automatic implementation of the following traits:

You can implement additonal derives, it they are implemented for the wrapped type, using #[wrapper()] proc macro:

Other traits, such as PartialEq, Eq, PartialOrd, Ord, Hash can be implemented using standard #[derive] attribute in the same manner as Default, Debug and From

Example

Simple wrapper:

use amplify::Wrapper;

#[derive(
    Wrapper, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, From, Debug, Display,
)]
#[display(inner)]
#[wrapper(LowerHex, UpperHex, Octal)]
#[wrapper(Neg, Add, Sub, Div, Mul, Rem)]
#[wrapper(AddAssign, SubAssign, DivAssign, MulAssign, RemAssign)]
#[wrapper(Not, Shl, Shr, BitAnd, BitOr, BitXor)]
#[wrapper(ShlAssign, ShrAssign, BitAndAssign, BitOrAssign, BitXorAssign)]
struct Int64(i64);

More complex wrapper with multiple unnamed fields:

use std::marker::PhantomData;
use amplify::Wrapper;

#[derive(Clone, Wrapper, Default, From)]
#[wrapper(Debug)]
struct Wrapped<T, U>(
    #[wrap]
    #[from]
    HashMap<usize, Vec<U>>,
    PhantomData<T>,
)
where
    U: Sized + Clone + Debug;

let w = Wrapped::<(), u8>::default();
assert_eq!(w.into_inner(), HashMap::<usize, Vec<u8>>::default());

Wrappers for indexable types

use amplify::Wrapper;

#[derive(Wrapper, From)]
#[wrapper(Index, IndexRange, IndexFrom, IndexTo, IndexInclusive, IndexFull)]
struct VecNewtype(Vec<u8>);