has/
lib.rs

1//! Introduce 'has a' relationship as a trait to Rust.
2//!
3//! This crate offers an alternative for a missing feature of the Rust Programming Language. That
4//! is, the possibility of traits holding state.
5//!
6//! ## Simple example
7//!
8//! ```rust
9//! #[macro_use]
10//! extern crate has;
11//!
12//! use has::*;
13//!
14//! struct Apple;
15//!
16//! trait ApplesContainer: HasMut<Vec<Apple>> {
17//!     fn take_apple(&mut self) -> Option<Apple> {
18//!         self.get_mut().pop()
19//!     }
20//!
21//!     fn put_apple(&mut self, apple: Apple) {
22//!         self.get_mut().push(apple);
23//!     }
24//! }
25//!
26//! #[derive(Default)]
27//! struct Basket {
28//!     pub apples: Vec<Apple>,
29//! }
30//!
31//! impl ApplesContainer for Basket {}
32//! impl_has!(Basket, Vec<Apple>, apples);
33//!
34//! fn main() {
35//!     let mut basket = Basket::default();
36//!
37//!     basket.put_apple(Apple);
38//!     basket.put_apple(Apple);
39//!     basket.put_apple(Apple);
40//!
41//!     basket.take_apple();
42//!
43//!     assert_eq!(basket.apples.len(), 2);
44//! }
45//! ```
46//!
47
48/// Trait to model a "has a" relationship between implementing structs and the generic parameter
49/// provided. This trait provides only a function to retrieve a non-mutable reference to the
50/// contained object. If a mutable reference is desired instead, use `HasMut`.
51///
52pub trait Has<T> {
53    fn get_ref(&self) -> &T;
54}
55
56/// Trait to model a "has a" relationship between implementing structs and the generic parameter
57/// provided. This trait provides methods to retrieve either a mutable or immutable reference to
58/// the contained object.
59///
60pub trait HasMut<T>: Has<T> {
61    fn get_mut(&mut self) -> &mut T;
62}
63
64impl<'a, T, H: Has<T>> Has<T> for &'a H {
65    fn get_ref(&self) -> &T {
66        Has::<T>::get_ref(*self)
67    }
68}
69
70impl<'a, T, H: Has<T>> Has<T> for &'a mut H {
71    fn get_ref(&self) -> &T {
72        Has::<T>::get_ref(*self)
73    }
74}
75
76impl<'a, T, H: HasMut<T>> HasMut<T> for &'a mut H {
77    fn get_mut(&mut self) -> &mut T {
78        HasMut::<T>::get_mut(*self)
79    }
80}
81
82/// Macro to consisely implement `HasMut` for a struct. The macro takes as argument the struct
83/// name, the type of the contained object and the identifier, within the struct, of the contained
84/// object; in that order.
85///
86#[macro_export] macro_rules! impl_has {
87    ( $implementer:ty, $typ:ty, $identifier:ident ) => {
88        impl $crate::Has<$typ> for $implementer {
89            fn get_ref(&self) -> &$typ {
90                &self.$identifier
91            }
92        }
93
94        impl $crate::HasMut<$typ> for $implementer {
95            fn get_mut(&mut self) -> &mut $typ {
96                &mut self.$identifier
97            }
98        }
99    }
100}