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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Rust has a built in tuple `(A, B, C, ...)` to represent a "product" or "intersection" of types.
//! The language lacks a generic syntax for the converse: a choice among multiple types, also known
//! as a union type `A + B + C ...` in [other programming
//! languages](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html) (which
//! are also related to "sum types" and "coproducts"). `enum`s serve a similar role but must be
//! named, which also makes trait implementation more cumbersome when you want a trait to be
//! applicable to N different variants.
//!
//! `Choice` provides a pattern and some syntactic sugar to bridge this gap.
//!
//! The pattern may be a bit counterintuitive the first time you see it. The first step is to use
//! [`Choice::new`] to build a base variant on top of [`Never`]:
//!
//! ```rust
//! use choice::{Choice, Never};
//! let no_real_choice: Choice<u64, Never> = Choice::new(42);
//! ```
//!
//! The `Never` type is uninhabitable and only serves to seed the pattern, so effectively we have a
//! "choice" between N=1 types in the example above, only `u64`. Calling [`Choice::or`] extends a
//! type to offer one more choice, inductively enabling a choice between N+1 types.
//!
//! ```rust
//! # use choice::{Choice, Never};
//! let two_types_option_1: Choice<&'static str, Choice<u64, Never>> =
//!     Choice::new(42).or();
//! ```
//!
//! You can build an instance of the same `Choice` type that holds the other inner type by simply
//! calling `Choice::new`:
//!
//! ```rust
//! # use choice::{Choice, Never};
//! let two_types_option2: Choice<&'static str, Choice<u64, Never>> =
//!     Choice::new("Forty two");
//! ````
//!
//! The above two examples share a type, so you can embed them in a collection:
//!
//! ```rust
//! # use choice::{Choice, Never};
//! let u64_or_string_vec: Vec<Choice<&'static str, Choice<u64, Never>>> = vec![
//!     Choice::new(42).or(),
//!     Choice::new("Forty two"),
//!     Choice::new(24).or(),
//!     Choice::new("Twenty four"),
//! ];
//! ```
//!
//! This pattern composes to allow additional choices:
//!
//! ```rust
//! # use choice::{Choice, Never};
//! let many: Vec<Choice<&'static str, Choice<i8, Choice<char, Never>>>> = vec![
//!     Choice::new("-INFINITY"),
//!     Choice::new(-1         ).or(),
//!     Choice::new('0'        ).or().or(),
//!     Choice::new(1          ).or(),
//!     Choice::new("INFINITY" ),
//! ];
//! ```
//!
//! # Macros
//!
//! The [`choice!`] macro provides syntactic sugar for a type representing the above pattern, which
//! is particularly useful when there are many choices:
//!
//! ```rust
//! # use choice::{choice, Choice, Never};
//! let x1: choice![u64, &'static str, char, String, i8] =
//!     Choice::new('x').or().or();
//! let x2: Choice<u64, Choice<&'static str, Choice<char, Choice<String, Choice<i8, Never>>>>> =
//!     Choice::new('x').or().or();
//! assert_eq!(x1, x2);
//! ```
//!
//! The [`choice_at!`] macro provides syntactic sugar for pattern matching on a choice. Rust is
//! unable to determine that the base case `Never` in uninhabited, so there is also a
//! [`choice_unreachable!`] macro to appease the [exhaustiveness
//! checker](https://rustc-dev-guide.rust-lang.org/pat-exhaustive-checking.html).
//!
//! ```rust
//! # use choice::{Choice, choice, choice_at, choice_unreachable};
//! let c: choice![u8, char] = Choice::new('2').or();
//! match c {
//!     choice_at!(0, v) => {
//!         panic!("Unexpected match: {}", v);
//!     }
//!     choice_at!(1, v) => {
//!         assert_eq!(v, '2');
//!     }
//!     choice_unreachable!(2) => {
//!         unreachable!();
//!     }
//! }
//! ```

use std::fmt::{Display, Debug, Formatter};

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// Represents a choice between two types, which you can compose to represent a choice between more
/// types -- `Choice<C, Choice<A, B>>` for instance.
///
/// See the [top-level crate docs](crate) for more details.
pub enum Choice<L, R> {
    /// The "left" case.
    L(L),
    /// The "right" case.
    R(R),
}

impl<A, B> Choice<A, B> {
    /// Constructs a [`Choice`] between two types, where the "decision" is of the first type.
    pub fn new(choice: A) -> Self {
        Choice::L(choice)
    }

    /// Wraps an existing [`Choice`] with an additional chooseable type.
    pub fn or<L>(self) -> Choice<L, Choice<A, B>> {
        Choice::R(self)
    }
}

impl<A> Choice<A, Never> {
    /// Returns the "left" value, as the right value is provably uninhabited.
    pub fn get(&self) -> &A {
        match self {
            Choice::L(l) => l,
            Choice::R(_) => unreachable!(),
        }
    }
}

/// Represents an uninhabited type. This is a placeholder until the built-in
/// [never](https://doc.rust-lang.org/std/primitive.never.html) type is stabilized.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Never { }

impl Display for Never {
    fn fmt(&self, _f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        unreachable!()
    }
}

/// Syntactic sugar for a type representing a [`Choice`] between multiple types.
///
/// # Example
///
/// ```rust
/// use choice::{Choice, choice};
/// let c: choice![u64, &'static str, char, String, i8] =
///     Choice::new('c').or().or();
/// ```
#[macro_export]
macro_rules! choice {
    [$t:ty] => ($crate::Choice<$t, $crate::Never>);
    [$t1:ty, $($t2:ty),+] => ($crate::Choice<$t1, choice![$($t2),+]>);
}

/// Syntactic sugar for destructuring a [`Choice`] between multiple types.
///
/// See also [`choice_unreachable`].
///
/// # Example
///
/// ```rust
/// use choice::{Choice, choice, choice_at, choice_unreachable};
/// let c: choice![u8, char] = Choice::new('2').or();
/// match c {
///     choice_at!(0, v) => {
///         panic!("Unexpected match: {}", v);
///     }
///     choice_at!(1, v) => {
///         assert_eq!(v, '2');
///     }
///     choice_unreachable!(2) => {
///         unreachable!();
///     }
/// }
/// ```
#[macro_export]
macro_rules! choice_at {
    (0, $v:ident) => ($crate::Choice::L($v));
    (1, $v:ident) => ($crate::Choice::R(choice_at!(0, $v)));
    (2, $v:ident) => ($crate::Choice::R(choice_at!(1, $v)));
    (3, $v:ident) => ($crate::Choice::R(choice_at!(2, $v)));
    (4, $v:ident) => ($crate::Choice::R(choice_at!(3, $v)));
    (5, $v:ident) => ($crate::Choice::R(choice_at!(4, $v)));
    (6, $v:ident) => ($crate::Choice::R(choice_at!(5, $v)));
    (7, $v:ident) => ($crate::Choice::R(choice_at!(6, $v)));
    (8, $v:ident) => ($crate::Choice::R(choice_at!(7, $v)));
    (9, $v:ident) => ($crate::Choice::R(choice_at!(8, $v)));
}

/// Syntactic sugar for an unreachable [`Choice`], which is only needed because the Rust
/// exhaustiveness checker is unable to infer that [`Never`] is uninhabited.
///
/// See also [`choice_at`].
///
/// This macro will no longer be necessary once
/// [`exhaustive_patterns`](https://doc.rust-lang.org/stable/unstable-book/language-features/exhaustive-patterns.html)
/// stabilizes.
///
/// # Example
///
/// ```rust
/// use choice::{Choice, choice, choice_at, choice_unreachable};
/// let c: choice![u8, char] = Choice::new('2').or();
/// match c {
///     choice_at!(0, v) => {
///         panic!("Unexpected match: {}", v);
///     }
///     choice_at!(1, v) => {
///         assert_eq!(v, '2');
///     }
///     choice_unreachable!(2) => {
///         unreachable!();
///     }
/// }
/// ```
#[macro_export]
macro_rules! choice_unreachable {
    (1) => ($crate::Choice::R(_));
    (2) => ($crate::Choice::R(choice_unreachable!(1)));
    (3) => ($crate::Choice::R(choice_unreachable!(2)));
    (4) => ($crate::Choice::R(choice_unreachable!(3)));
    (5) => ($crate::Choice::R(choice_unreachable!(4)));
    (6) => ($crate::Choice::R(choice_unreachable!(5)));
    (7) => ($crate::Choice::R(choice_unreachable!(6)));
    (8) => ($crate::Choice::R(choice_unreachable!(7)));
    (9) => ($crate::Choice::R(choice_unreachable!(8)));
}

impl<A, B> Display for Choice<A, B> where A: Display, B: Display {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Choice::L(v) => v.fmt(f),
            Choice::R(v) => v.fmt(f),
        }
    }
}
impl<A, B> Debug for Choice<A, B> where A: Debug, B: Debug {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Choice::L(v) => v.fmt(f),
            Choice::R(v) => v.fmt(f),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn can_compare() {
        let c1: choice![u8, char] = Choice::new(1);
        let c2: choice![u8, char] = Choice::new(2);
        let c3: choice![u8, char] = Choice::new('1').or();
        let c4: choice![u8, char] = Choice::new('2').or();

        assert!(c1 < c2);
        assert!(c2 < c3); // leftmost element is considered smallest
        assert!(c3 < c4);

        assert_eq!(c1, Choice::new(1));
        assert_eq!(c2, Choice::new(2));
        assert_eq!(c3, Choice::new('1').or());
        assert_eq!(c4, Choice::new('2').or());

        // Elements with unmatched positions are never equal, even if the values are equal.
        let c1: choice![u8, u8] = Choice::new(1);
        let c2: choice![u8, u8] = Choice::new(1).or();
        assert_ne!(c1, c2);
    }

    #[test]
    fn can_debug() {
        let c1: choice![u8, char] = Choice::new(1);
        let c2: choice![u8, char] = Choice::new('2').or();
        assert_eq!(format!("{:?}", c1), "1");
        assert_eq!(format!("{:?}", c2), "'2'");
    }

    #[test]
    fn can_display() {
        let c1: choice![u8, char] = Choice::new(1);
        let c2: choice![u8, char] = Choice::new('2').or();
        assert_eq!(format!("{}", c1), "1");
        assert_eq!(format!("{}", c2), "2");
    }

    #[test]
    fn can_destructure() {
        let c1: choice![u8, char] = Choice::new(1);
        if let choice_at!(0, v) = c1 {
            assert_eq!(v, 1);
        } else {
            panic!("Expected match.");
        }
        if let choice_at!(1, _v) = c1 {
            panic!("Unexpected match.");
        }

        let c2: choice![u8, char] = Choice::new('2').or();
        match c2 {
            choice_at!(0, _v) => {
                panic!("Unexpected match.");
            }
            choice_at!(1, v) => {
                assert_eq!(v, '2');
            }
            choice_unreachable!(2) => {
                unreachable!();
            }
        }
    }

    #[test]
    fn smoke_test() {
        let choices: Vec<choice![u8, char, &'static str, String]> = vec![
            Choice::new(1),
            Choice::new('2').or(),
            Choice::new("3").or().or(),
            Choice::new("4".to_string()).or().or().or(),
        ];
        assert_eq!(
            format!("{:?}", choices),
            r#"[1, '2', "3", "4"]"#);
        assert_eq!(choices, vec![
            Choice::new(1),
            Choice::new('2').or(),
            Choice::new("3").or().or(),
            Choice::new("4".to_string()).or().or().or(),
        ]);
        assert_ne!(choices, vec![
            Choice::new(1),
            Choice::new('2').or(),
            Choice::new("three").or().or(),
            Choice::new("4".to_string()).or().or().or(),
        ]);
    }
}