cgt/has.rs
1//! `Has` trait and utils
2
3/// Types that implement `Has<T>` claim to contain `T` in their structure and can give access to it
4///
5/// It is useful when different parts need to operate of a concrete part of abstract datatype.
6/// e.g. a graph vertex may have color and position, game only cares about color but layout
7/// algorithm cares only about position
8pub trait Has<T> {
9 #[allow(missing_docs)]
10 fn get_inner(&self) -> &T;
11
12 #[allow(missing_docs)]
13 fn get_inner_mut(&mut self) -> &mut T;
14}
15
16impl<T> Has<T> for T {
17 #[inline(always)]
18 fn get_inner(&self) -> &T {
19 self
20 }
21
22 #[inline(always)]
23 fn get_inner_mut(&mut self) -> &mut T {
24 self
25 }
26}
27
28/// Generate boilerplate for Has trait
29///
30/// # Examples
31/// ```rust
32/// # use cgt::impl_has;
33/// struct Foo;
34/// struct Bar {
35/// foo: Foo,
36/// bar: u32,
37/// }
38///
39/// impl_has!(Bar -> foo -> Foo);
40/// ```
41#[macro_export]
42macro_rules! impl_has {
43 ($ty:ident -> $getter:ident -> $res:ty) => {
44 impl $crate::has::Has<$res> for $ty {
45 fn get_inner(&self) -> &$res {
46 &self.$getter
47 }
48
49 fn get_inner_mut(&mut self) -> &mut $res {
50 &mut self.$getter
51 }
52 }
53 };
54}