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
//! This crate offers some tools to deal with static enums. It offers a way to declare a simple
//! enum, which then offers e.g. `values()` which can be used to iterate over the values of the enum.
//! In addition, it offers a type `EnumMap` which is an array-backed map from enum values to some type.
//!
//! It offers a macro `plain_enum_mod` which declares an own module which contains a simple enum
//! and the associated functionality:
//!
//! ```
//! mod examples_not_to_be_used_by_clients {
//!     #[macro_use]
//!     use plain_enum::*;
//!     plain_enum_mod!{example_mod_name, ExampleEnum {
//!         V1,
//!         V2,
//!         SomeOtherValue,
//!         LastValue, // note trailing comma
//!     }}
//!     
//!     fn do_some_stuff() {
//!         let map = ExampleEnum::map_from_fn(|example| // create a map from ExampleEnum to usize
//!             example.to_usize() + 1                   // enum values convertible to usize
//!         );
//!         for ex in ExampleEnum::values() {            // iterating over the enum's values
//!             assert_eq!(map[ex], ex.to_usize() + 1);
//!         }
//!     }
//! }
//! ```
//!
//! Internally, the macro generates a simple enum whose numeric values start counting at 0.

#[macro_use]
mod plain_enum {
    #[macro_export]
    macro_rules! enum_seq_len {
        ($n: expr, $enumval: ident,) => ($n);
        ($n: expr, $enumval: ident, $($enumvals: ident,)*) => (enum_seq_len!(($n + 1), $($enumvals,)*));
    }

    use std::iter;
    use std::ops;

    /// This trait is implemented by enums declared via the `plain_enum_mod` macro.
    /// Do not implement it yourself, but use this macro.
    pub trait TPlainEnum : Sized {
        /// Checks whether `u` is the numerical representation of a valid enum value.
        fn valid_usize(u: usize) -> bool;
        /// Converts `u` to the associated enum value. `assert`s that `u` is a valid value for the enum.
        fn from_usize(u: usize) -> Self;
        /// Converts `u` to the associated enum value. if `u` is a valid value for the enum.
        fn checked_from_usize(u: usize) -> Option<Self>;
        /// Converts `u` to the associated enum value, but wraps `u` it before conversion (i.e. it
        /// applies the modulo operation with a modulus equal to the arity of the enum before converting).
        fn wrapped_from_usize(u: usize) -> Self;
        /// Computes the difference between two enum values, wrapping around if necessary.
        fn wrapped_difference(self, e_other: Self) -> usize;
        /// Converts the enum to its numerical representation.
        fn to_usize(self) -> usize;
        /// Returns the arity, i.e. the smallest `usize` not representable by the enum.
        fn ubound_usize() -> usize;
        /// Returns an iterator over the enum's values.
        fn values() -> iter::Map<ops::Range<usize>, fn(usize) -> Self> {
            (0..Self::ubound_usize())
                .map(Self::from_usize)
        }
        /// Adds a number to the enum, wrapping.
        fn wrapping_add(self, n_offset: usize) -> Self;
    }

    /// Trait used to associated enum with EnumMap.
    pub trait TEnumMapType<T> : TPlainEnum {
        type MapType;
    }

    #[allow(dead_code)]
    // TODO rust: trait bounds are not (yet) enforced in type definitions (rust 1.16, 20170408)
    pub type EnumMap<PlainEnum, T> = <PlainEnum as TEnumMapType<T>>::MapType;

    #[macro_export]
    macro_rules! acc_arr {
        ($func: ident, [$($acc: expr,)*], []) => {
            [$($acc,)*]
        };
        ($func: ident, [$($acc: expr,)*], [$enumval: ident, $($enumvals: ident,)*]) => {
            acc_arr!($func, [$($acc,)* $func($enumval),], [$($enumvals,)*])
        };
    }

    #[macro_export]
    macro_rules! plain_enum_mod {
        ($modname: ident, $enumname: ident {
            $($enumvals: ident,)*
        } ) => {
            mod $modname {
                use plain_enum::*;
                use std::slice;
                #[repr(usize)]
                #[derive(PartialEq, Eq, Debug, Copy, Clone, PartialOrd, Ord, Hash)]
                pub enum $enumname {
                    $($enumvals,)*
                }

                const ENUMSIZE : usize = enum_seq_len!(1, $($enumvals,)*);

                impl TPlainEnum for $enumname {
                    fn ubound_usize() -> usize {
                        ENUMSIZE
                    }
                    fn valid_usize(u: usize) -> bool {
                        u < ENUMSIZE
                    }
                    fn from_usize(u: usize) -> Self {
                        use std::mem;
                        debug_assert!(Self::valid_usize(u));
                        unsafe{mem::transmute(u)}
                    }
                    fn checked_from_usize(u: usize) -> Option<Self> {
                        if Self::valid_usize(u) {
                            Some(Self::from_usize(u))
                        } else {
                            None
                        }
                    }
                    fn wrapped_from_usize(u: usize) -> Self {
                        Self::from_usize(u % ENUMSIZE)
                    }
                    fn wrapped_difference(self, e_other: Self) -> usize {
                        (self.to_usize() + ENUMSIZE - e_other.to_usize()) % ENUMSIZE
                    }
                    fn to_usize(self) -> usize {
                        self as usize
                    }
                    fn wrapping_add(self, n_offset: usize) -> Self {
                        Self::from_usize((self.to_usize() + n_offset) % ENUMSIZE)
                    }
                }

                impl $enumname {
                    #[allow(dead_code)]
                    /// Creates a enum map from enum values to a type, determined by `func`.
                    /// The map will contain the results of applying `func` to each enum value.
                    pub fn map_from_fn<F, T>(mut func: F) -> Map<T>
                        where F: FnMut($enumname) -> T,
                    {
                        use self::$enumname::*;
                        Map::from_raw(acc_arr!(func, [], [$($enumvals,)*]))
                    }
                    /// Creates a enum map from a raw array.
                    #[allow(dead_code)]
                    pub fn map_from_raw<T>(at: [T; ENUMSIZE]) -> Map<T> {
                        Map::from_raw(at)
                    }
                }

                impl<T> TEnumMapType<T> for $enumname {
                    type MapType = Map<T>;
                }

                use std::ops::{Index, IndexMut};
                #[derive(PartialEq, Debug)]
                pub struct Map<T> {
                    m_at : [T; ENUMSIZE],
                }
                impl<T> Index<$enumname> for Map<T> {
                    type Output = T;
                    fn index(&self, e : $enumname) -> &T {
                        &self.m_at[e.to_usize()]
                    }
                }
                impl<T> IndexMut<$enumname> for Map<T> {
                    fn index_mut(&mut self, e : $enumname) -> &mut Self::Output {
                        &mut self.m_at[e.to_usize()]
                    }
                }
                impl<T> Map<T> {
                    #[allow(dead_code)]
                    pub fn iter(&self) -> slice::Iter<T> {
                        self.m_at.iter()
                    }
                    pub fn from_raw(at: [T; ENUMSIZE]) -> Map<T> {
                        Map {
                            m_at : at,
                        }
                    }
                }
            }
            pub use self::$modname::$enumname;
        }
    }
}
pub use plain_enum::TPlainEnum;
pub use plain_enum::TEnumMapType;
pub use plain_enum::EnumMap;

#[cfg(test)]
mod tests {
    use plain_enum::*;
    plain_enum_mod!{test_module, ETest {
        E1, E2, E3,
    }}

    #[test]
    fn test_plain_enum() {
        assert_eq!(3, enum_seq_len!(1, E1, E2, E3,));
        assert_eq!(3, ETest::ubound_usize());
    }

    #[test]
    fn test_values() {
        assert_eq!(vec![ETest::E1, ETest::E2, ETest::E3], ETest::values().collect::<Vec<_>>());
        assert_eq!(ETest::values().count(), 3);
        assert_eq!((3, Some(3)), ETest::values().size_hint());
        assert_eq!(3, ETest::values().len());
        assert!(ETest::values().eq(ETest::values().rev().rev()));
    }

    #[test]
    fn test_enummap() {
        let mut map_test_to_usize = ETest::map_from_fn(|test| test.to_usize());
        for test in ETest::values() {
            assert_eq!(map_test_to_usize[test], test.to_usize());
        }
        for test in ETest::values() {
            map_test_to_usize[test] += 1;
        }
        for test in ETest::values() {
            assert_eq!(map_test_to_usize[test], test.to_usize()+1);
        }
    }
}

pub mod examples_not_to_be_used_by_clients {
    //! A sample module showing the capabilities of this crate. Do not use it or rely on it.
    plain_enum_mod!{example_mod_name, ExampleEnum {
        V1,
        V2,
        SomeOtherValue,
        LastValue, // note trailing comma
    }}
}