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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! A crate that exports one macro (`union`) to create types that are enums with checks in debug
//! mode, but unions in release mode. In debug mode, invalid access will panic, while in release
//! **they will not.**  It is therefore unsafe. Fields should be treated as fields of unions (i.e
//! no non-`Copy` types allowed, etc). **Please test all code generated with `blair_mountain` in
//! both release and debug modes.**

#[doc(hidden)]
pub use paste::item as paste_item;

/// Define a union. Variants must have trailing commas. Variants must be `Copy`
/// (without [this feature gate](https://github.com/rust-lang/rust/issues/55149)).
/// `Hash`, `Default`, `Debug` (and some other traits) can't be derived for unions either, so do not
/// add `#[derive]` invocations of those above a union.
///
/// This macro creates a struct with the name given and the following methods per variant:
/// - `new_<variant>(val)` - creates a new union with the given variant
/// - `get_<variant>` - gets the union's value as the given variant. Unsound if the union is not
///   of that variant.
/// - `get_<variant>_mut` - gets the union's value as the given variant mutable. For soundness, refer
///   to [this page](https://doc.rust-lang.org/reference/items/unions.html)
/// - `set_<variant>(val)` - sets the union to the given value. The previous variant should be
///   dropped if need be (`ManuallyDrop`)
/// - `into_<variant>` - moves the variant out of the union, consuming the union. Unsound if the
///   union is not of that variant.
///
/// **Note: fields must be `Copy`.**
///
/// # Example
///
/// ```rust,ignore
/// use blair_mountain::union;
///
/// union! {
///     pub union Example {
///         pub one: &'static str,
///         pub two: u32,
///         private: f32,
///     }
///
///     pub union GenericExample<T: Copy, U>
///        where U: Copy + Clone
///     {
///        pub one: T,
///        pub two: U,
///    }
/// }
/// ```
#[macro_export]
macro_rules! union {
    {
        $(
            $(#[$union_meta:meta])*
            $union_vis:vis union $name:ident$(<$($generic:ident $(: $generic_trait:ty)?$(,)?)*>)?
            $(
                where $($where_generic:ident: $($where_bound:ty)+)*
            )?
            {
                $($member_vis:vis $member:ident: $member_type:ty,)*
            }
        )*
    } => {
        $(
            #[cfg(debug_assertions)]
            $crate::paste_item! {
                #[allow(non_camel_case_types)]
                enum [<$name Inner>]$(<$($generic,)*>)?
                $(
                    where $($where_generic: $($where_bound)*)*
                )?
                {
                    $(
                        $member($member_type),
                    )*
                }

                #[allow(dead_code)]
                impl$(<$($generic$(: $generic_trait)?,)*>)? $name$(<$($generic,)*>)?
                $(
                    where $($where_generic: $($where_bound)*)*
                )?
                {
                    $(
                        $member_vis fn [<new_ $member>](val: $member_type) -> Self {
                            Self([<$name Inner>]::$member(val))
                        }

                        $member_vis unsafe fn [<get_ $member>](&self) -> &$member_type {
                            match &self.0 {
                                [<$name Inner>]::$member(val) => val,
                                _ => panic!("unexpected union member")
                            }
                        }

                        $member_vis unsafe fn [<get_ $member _mut>](&mut self) -> &mut $member_type {
                            match &mut self.0 {
                                [<$name Inner>]::$member(val) => val,
                                _ => panic!("unexpected union member")
                            }
                        }

                        $member_vis unsafe fn [<set_ $member>](&mut self, new: $member_type) {
                            self.0 = [<$name Inner>]::$member(new);
                        }

                        $member_vis unsafe fn [<into_ $member>](self) -> $member_type {
                            match self.0 {
                                [<$name Inner>]::$member(val) => val,
                                _ => panic!("unexpected union member")
                            }
                        }
                    )*
                }
            }

            #[cfg(not(debug_assertions))]
            $crate::paste_item! {
                union [<$name Inner>]$(<$($generic$(: $generic_trait)?,)*>)?
                $(
                    where $($where_generic: $($where_bound)*)*
                )?
                {
                    $($member: $member_type,)*
                }

                #[allow(dead_code)]
                impl$(<$($generic$(: $generic_trait)?,)*>)? $name$(<$($generic,)*>)?
                $(
                    where $($where_generic: $($where_bound)*)*
                )?
                {
                    $(
                        $member_vis fn [<new_ $member>](val: $member_type) -> Self {
                            Self([<$name Inner>] {
                                $member: val,
                            })
                        }

                        $member_vis unsafe fn [<get_ $member>](&self) -> &$member_type {
                            &(self.0).$member
                        }

                        $member_vis unsafe fn [<get_ $member _mut>](&mut self) -> &mut $member_type {
                            &mut (self.0).$member
                        }

                        $member_vis unsafe fn [<set_ $member>](&mut self, new: $member_type) {
                            (self.0).$member = new;
                        }

                        $member_vis unsafe fn [<into_ $member>](self) -> $member_type {
                            (self.0).$member
                        }
                    )*
                }
            }

            $crate::paste_item! {
                #[repr(transparent)]
                $(#[$union_meta])*
                $union_vis struct $name$(<$($generic$(: $generic_trait)?,)*>)?(
                        [<$name Inner>]$(<$($generic,)*>)?
                )
                $(
                    where $($where_generic: $($where_bound)*)*
                )?;
            }
        )*
    };
}

/// An example union.
pub mod example {
    union! {
        /// An example union.
        pub union Example {
            pub one: &'static str,
            pub two: u32,
            private: f32,
        }

        /// An example union with generics
        pub union GenericExample<T: Copy, U>
            where U: Copy + Clone
        {
            pub one: T,
            pub two: U,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::example::{GenericExample, Example};

    #[test]
    fn accessors_simple() {
        let mut eg_1 = Example::new_one("asdfs");
        unsafe {
            assert_eq!(*eg_1.get_one(), "asdfs");

            eg_1.set_two(10);
            assert_eq!(*eg_1.get_two(), 10);
        }

        let mut eg_2 = Example::new_two(1234);

        unsafe {
            assert_eq!(*eg_2.get_two(), 1234);

            eg_2.set_two(102);
            assert_eq!(*eg_2.get_two(), 102);

            *eg_2.get_two_mut() = 101;
            assert_eq!(*eg_2.get_two(), 101);

            assert_eq!(eg_2.into_two(), 101);
        }
    }

    #[test]
    fn accessors_generics() {
        let mut eg_1: GenericExample<&'static str, u32> = GenericExample::new_one("asdfs");
        unsafe {
            assert_eq!(*eg_1.get_one(), "asdfs");

            eg_1.set_two(10);
            assert_eq!(*eg_1.get_two(), 10);
        }

        let mut eg_2: GenericExample<&'static str, u32> = GenericExample::new_two(1234);

        unsafe {
            assert_eq!(*eg_2.get_two(), 1234);

            eg_2.set_two(102);
            assert_eq!(*eg_2.get_two(), 102);

            *eg_2.get_two_mut() = 101;
            assert_eq!(*eg_2.get_two(), 101);

            assert_eq!(eg_2.into_two(), 101);
        }
    }

    #[test]
    #[should_panic(expected = "unexpected union member")]
    fn invalid_accessor_get() {
        let eg = Example::new_one("asdfs");
        unsafe { eg.get_two(); }
    }

    #[test]
    #[should_panic(expected = "unexpected union member")]
    fn invalid_accessor_get_mut() {
        let mut eg = Example::new_one("asdfs");
        unsafe { eg.get_two_mut(); }
    }

    #[test]
    #[should_panic(expected = "unexpected union member")]
    fn invalid_accessor_into() {
        let eg = Example::new_one("asdfs");
        unsafe { eg.into_two(); }
    }
}