|
| 1 | +// `bi_tuple` creates a tuple of two items. |
| 2 | +// |
| 3 | +// Example: `bi_tuple!(Person(name: String, age: int))` |
| 4 | +// |
| 5 | +// It implements the `From` trait to break apart the tuple into the members |
| 6 | +// or take references to them. |
| 7 | +// |
| 8 | +// It does not implement `AsRef` (or any other trait) per item type, as it might be that the two types are the same. |
1 | 9 | macro_rules! bi_tuple { |
2 | | - ($(#[$($attrss:tt)*])* $name: ident($left: ty, $right: ty)) => { |
| 10 | + ($(#[$($attrss:tt)*])* $name: ident($left_name: tt: $left_type: ty, $right_name: tt: $right_type: ty)) => { |
3 | 11 | $(#[$($attrss)*])* |
4 | 12 | #[derive(Clone, Debug, PartialEq)] |
5 | | - pub struct $name($left, $right); |
| 13 | + pub struct $name($left_type, $right_type); |
6 | 14 |
|
7 | 15 | impl $name { |
8 | | - pub fn new(left: $left, right: $right) -> Self { |
9 | | - Self(left, right) |
| 16 | + /// Creates a new instance of [$name]. |
| 17 | + pub fn new($left_name: $left_type, $right_name: $right_type) -> Self { |
| 18 | + Self($left_name, $right_name) |
10 | 19 | } |
11 | 20 |
|
| 21 | + /// Tries to map the right side of the tuple with the given function. |
12 | 22 | pub fn try_map_right<F, E>(self, f: F) -> Result<Self, E> |
13 | | - where F : FnOnce($right) -> Result<$right, E> |
| 23 | + where F : FnOnce($right_type) -> Result<$right_type, E> |
14 | 24 | { |
15 | | - let (left, right) = self.into(); |
16 | | - f(right).map(|new_right| Self::new(left, new_right)) |
| 25 | + let ($left_name, $right_name) = self.into(); |
| 26 | + f($right_name).map(|new_right| Self::new($left_name, new_right)) |
17 | 27 | } |
18 | 28 |
|
19 | | - pub fn left(&self) -> &$left { |
| 29 | + /// Gets a reference to the left side member of the tuple. |
| 30 | + pub fn $left_name(&self) -> &$left_type { |
20 | 31 | &self.0 |
21 | 32 | } |
22 | 33 |
|
23 | | - pub fn right(&self) -> &$right { |
| 34 | + /// Gets a reference to the right side member of the tuple. |
| 35 | + pub fn $right_name(&self) -> &$right_type { |
24 | 36 | &self.1 |
25 | 37 | } |
26 | 38 | } |
27 | 39 |
|
28 | | - impl From<$name> for ($left, $right) { |
| 40 | + // Break apart the tuple |
| 41 | + |
| 42 | + impl From<$name> for ($left_type, $right_type) { |
29 | 43 | fn from(value: $name) -> Self { |
30 | 44 | (value.0, value.1) |
31 | 45 | } |
32 | 46 | } |
33 | 47 |
|
34 | | - impl<'a> From<&'a $name> for (&'a $left, &'a $right) { |
| 48 | + // Get references to both members of the tuple |
| 49 | + |
| 50 | + impl<'a> From<&'a $name> for (&'a $left_type, &'a $right_type) { |
35 | 51 | fn from(value: &'a $name) -> Self { |
36 | 52 | (&value.0, &value.1) |
37 | 53 | } |
|
0 commit comments