1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//! Types used by documentation examples.

use core::ops::{Index, IndexMut};

use crate::TS;

macro_rules! impl_index_indexmut {
    (
        impl $impl_params:tt $self:ty {
            $($fields:tt)*
        }
    ) => (
        $(
            impl_index_indexmut!{
                @inner
                impl $impl_params $self { $fields }
            }
        )*
    );
    (@inner
        impl[$($impl:tt)*] $self:ty {
            ($field_name:ident : $type:ty)
        }
    ) => {
        const _: () = {
            type $field_name = TS!($field_name);

            impl<$($impl)*> Index<$field_name> for $self {
                type Output = $type;

                fn index(&self, _: $field_name) -> &$type {
                    &self.$field_name
                }
            }

            impl<$($impl)*> IndexMut<$field_name> for $self {
                fn index_mut(&mut self, _: $field_name) -> &mut $type {
                    &mut self.$field_name
                }
            }
        };
    };
}

/// For examples
#[derive(Debug)]
pub struct Foo {
    bar: u32,
    baz: u64,
    qux: &'static str,
}

impl Foo {
    /// A simple contructor
    pub fn new(bar: u32, baz: u64, qux: &'static str) -> Self {
        Self { bar, baz, qux }
    }
}

impl_index_indexmut! {
    impl[] Foo {
        (bar: u32)
        (baz: u64)
        (qux: &'static str)
    }
}

/// For examples
#[derive(Debug)]
pub struct Bar {
    bar: u32,
    baz: bool,
    boom: Option<char>,
}

impl Bar {
    /// A simple contructor
    pub fn new(bar: u32, baz: bool, boom: Option<char>) -> Self {
        Self { bar, baz, boom }
    }
}

impl_index_indexmut! {
    impl[] Bar {
        (bar: u32)
        (baz: bool)
        (boom: Option<char>)
    }
}