Attribute Macro auto_trait::auto_trait[][src]

#[auto_trait]
Expand description

Generates trait implementation for specified type, relying on Deref or Into depending on whether self is reference or owned

Note that this crate is only needed due to lack of specialization that would allow to have generic implementation over T: Deref<Target=O>

Example

use auto_trait::auto_trait;
pub struct Wrapper(u32);

impl Into<u32> for Wrapper {
    fn into(self) -> u32 {
        self.0
    }
}

impl core::ops::Deref for Wrapper {
    type Target = u32;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl core::ops::DerefMut for Wrapper {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[auto_trait(Wrapper)]
pub trait Lolka3 {
}

impl Lolka3 for u32 {}

#[auto_trait(Box<T: Lolka2>)]
#[auto_trait(Wrapper)]
pub trait Lolka2 {
   fn lolka2_ref(&self) -> u32;
   fn lolka2_mut(&mut self) -> u32;
}

impl Lolka2 for u32 {
   fn lolka2_ref(&self) -> u32 {
       10
   }
   fn lolka2_mut(&mut self) -> u32 {
       11
   }
}

#[auto_trait(Box<T: Lolka + From<Box<T>>>)]
pub trait Lolka {
   fn lolka() -> u32;

   fn lolka_ref(&self) -> u32;

   fn lolka_mut(&mut self) -> u32;

   fn lolka_self(self) -> u32;
}

impl Lolka for u32 {
   fn lolka() -> u32 {
       1
   }

   fn lolka_ref(&self) -> u32 {
       2
   }

   fn lolka_mut(&mut self) -> u32 {
       3
   }

   fn lolka_self(self) -> u32 {
       4
   }

}

let mut lolka = 0u32;
let mut wrapped = Box::new(lolka);

assert_eq!(lolka.lolka_ref(), wrapped.lolka_ref());
assert_eq!(lolka.lolka_mut(), wrapped.lolka_mut());
assert_eq!(lolka.lolka_self(), wrapped.lolka_self());

assert_eq!(lolka.lolka2_ref(), wrapped.lolka2_ref());
assert_eq!(lolka.lolka2_mut(), wrapped.lolka2_mut());