any_of 0.10.0

A general optional or integral sum type which can be Neither, Left, Right or Both.
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! # any_of
//!
//! `any_of` is a flexible and lightweight Rust crate designed to handle scenarios
//! where a variable may have one out of several possible values, or none at all.
//! It provides the `AnyOf` enum with variants to represent these possibilities.
//!
//! ## Features
//! - **Enum Variants**:
//!   - `Neither` to represent the absence of values.
//!   - `Either` to represent a single value (`Left` or `Right`).
//!   - `Both` to represent a combination of values (`Left` and `Right`).
//! - **Convenient Methods**: Create, transform, and check the state of `AnyOf` values
//!   easily with utility functions like `new`, `is_neither`, `is_both`, `map_left`, etc.
//! - **Extensible with Type Parameters**: Allows customization of the `Left` and `Right` types.
//!
//! ## Example Usage
//!
//! ```rust
//! use any_of::{AnyOf, either::Either, both::Both};
//!
//! let neither: AnyOf<i32, &str> = AnyOf::Neither;
//! let neither: AnyOf<i32, &str> = AnyOf::new(None, None);
//! let left: AnyOf<i32, &str> = AnyOf::Either(Either::Left(42));
//! let left: AnyOf<i32, &str> = AnyOf::new(Some(42), None);
//! let both: AnyOf<i32, &str> = AnyOf::Both(Both { left: 42, right: "Hello" });
//! let both: AnyOf<i32, &str> = AnyOf::new(Some(42), Some("Hello"));
//!
//! assert!(neither.is_neither());
//! assert!(left.is_left());
//! assert!(both.is_both());
//!
//! assert!(neither.map_right(|r| r).is_neither());
//! assert!(left.map_right(|r| r).is_neither());
//! assert!(left.map_left(|l| l).is_left());
//! assert!(both.map_left(|l| l).is_left());
//! ```
//!
//! ## Crate Features
//! - `std` feature: Enables standard library support for types that require it.
//!
//! ## Use Cases
//! - Representing optional or branching data in a concise manner.
//! - Handling dynamic states with variants like `Neither`, `Either`, and `Both`.
//! - Reducing boilerplate for mapping and transforming multiple optional values.
//!
//! ## Notable methods :
//! - [AnyOf::new]
//! - [AnyOf::combine]
//! - [AnyOf::unwrap_left] and [AnyOf::left]
//! - [AnyOf::unwrap_right] and [AnyOf::right]
//! - [AnyOf::unwrap_both] and [AnyOf::both_or_none]
//!
#![no_std]

/// The `(T, U)` tuple.
pub type Couple<T, U> = (T, U);

/// A shortcut for `Couple<T, T>`.
pub type Pair<T> = Couple<T, T>;

pub mod either;
pub mod both;

use core::ops::Add;

pub use crate::both::Both;
pub use crate::either::Either;

/// Represents a type that can hold one of several variants: `Neither`, `Either` (with `Left` or `Right`),
/// or `Both` (containing both `Left` and `Right` values).
///
/// This enum allows for representing a flexible combination of values, or the absence of any values.
///
/// # Variants
///
/// - `Neither`: Represents the absence of both `Left` and `Right` values.
/// - `Either`: Represents a value that is either `Left` or `Right`.
/// - `Both`: Represents a combination of both `Left` and `Right` values.
///
/// # Type Parameters
///
/// - `L`: The type of the `Left` value.
/// - `R`: The type of the `Right` value. Defaults to the same type as `L` if not specified.
///
/// # Examples
///
/// ```rust
/// use any_of::{AnyOf, either::Either, both::Both};
///
/// let neither: AnyOf<i32, &str> = AnyOf::Neither;
/// let neither: AnyOf<i32, &str> = AnyOf::new(None, None);
/// let left: AnyOf<i32, &str> = AnyOf::Either(Either::Left(42));
/// let left: AnyOf<i32, &str> = AnyOf::new(Some(42), None);
/// let both: AnyOf<i32, &str> = AnyOf::Both(Both { left: 42, right: "Hello" });
/// let both: AnyOf<i32, &str> = AnyOf::new(Some(42), Some("Hello"));
///
/// assert!(neither.is_neither());
/// assert!(left.is_left());
/// assert!(both.is_both());
///
/// assert!(neither.map_right(|r| r).is_neither());
/// assert!(left.map_right(|r| r).is_neither());
/// assert!(left.map_left(|l| l).is_left());
/// assert!(both.map_left(|l| l).is_left());
///
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum AnyOf<L, R = L> {
    Neither,
    Either(Either<L, R>),
    Both(Both<L, R>),
}

impl<L, R> AnyOf<L, R> {
    /// Creates a new `AnyOf` instance based on the presence of `left` and `right` values.
    ///
    /// # Parameters
    ///
    /// - `left`: An `Option` containing the left value of type `L`, or `None` if absent.
    /// - `right`: An `Option` containing the right value of type `R`, or `None` if absent.
    ///
    /// # Returns
    ///
    /// - Returns `AnyOf::Neither` if both `left` and `right` are `None`.
    /// - Returns `AnyOf::Either(Either::Left)` if `left` has a value and `right` is `None`.
    /// - Returns `AnyOf::Either(Either::Right)` if `right` has a value and `left` is `None`.
    /// - Returns `AnyOf::Both` if both `left` and `right` have values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use any_of::{AnyOf, either::Either, both::Both};
    ///
    /// let neither: AnyOf<i32, &str> = AnyOf::new(None, None);
    /// assert!(neither.is_neither());
    ///
    /// let left: AnyOf<i32, &str> = AnyOf::new(Some(42), None);
    /// assert!(left.is_left());
    ///
    /// let right: AnyOf<i32, &str> = AnyOf::new(None, Some("Hello"));
    /// assert!(right.is_right());
    ///
    /// let both: AnyOf<i32, &str> = AnyOf::new(Some(42), Some("Hello"));
    /// assert!(both.is_both());
    /// ```
    pub fn new(left: Option<L>, right: Option<R>) -> Self {
        match (left, right) {
            (None, None) => Self::Neither,
            (Some(l), None) => Self::Either(Either::Left(l)),
            (None, Some(r)) => Self::Either(Either::Right(r)),
            (Some(l), Some(r)) => Self::Both(Both { left: l, right: r }),
        }
    }
    pub fn new_neither() -> Self {
        Self::new(None, None)
    }
    pub fn new_left(left: L) -> Self {
        Self::new(Some(left), None)
    }
    pub fn new_right(right: R) -> Self {
        Self::new(None, Some(right))
    }
    pub fn new_both(l: L, r: R) -> Self {
        Self::new(Some(l), Some(r))
    }
    pub fn into_both(self) -> Both<L, R> {
        match self {
            AnyOf::Both(b) => b,
            _ => panic!("Can only convert Either::Both to Both"),
        }
    }
    pub fn from_both(both: Both<L, R>) -> Self {
        Self::new(Some(both.left), Some(both.right))
    }

    pub fn into_either(self) -> Either<L, R> {
        match self {
            AnyOf::Either(e) => match e {
                Either::Left(l) => Either::Left(l),
                Either::Right(r) => Either::Right(r),
            },
            _ => panic!("Can only convert Either::Either to Either"),
        }
    }

    /// Gets a [Either] pair from an Either.
    ///
    /// * Either::Neither => None, None
    /// * Either::Left(L) => Some(LeftOrRight::Left(L)), None
    /// * Either::Right(R) => None, Some(LeftOrRight::Right(R))
    /// * Either::Both(L, R) => Some(LeftOrRight::Left(L)), Some(LeftOrRight::Right(R))
    pub fn to_either_pair(&self) -> Pair<Option<Either<L, R>>>
    where
        L: Clone,
        R: Clone,
    {
        let both = self.any();
        let left = both.0.map(|l| Either::Left(l.clone()));
        let right = both.1.map(|r| Either::Right(r.clone()));
        (left, right)
    }

    pub fn from_either(either: Either<L, R>) -> Self {
        match either {
            Either::Left(l) => Self::Either(Either::Left(l)),
            Either::Right(r) => Self::Either(Either::Right(r)),
        }
    }

    /// True if [Either::Left] or [AnyOf::Both].
    pub fn has_left(&self) -> bool {
        matches!(self, Self::Either(Either::Left(_)) | Self::Both(_))
    }
    /// True if [Either::Left].
    pub fn is_left(&self) -> bool {
        matches!(self, Self::Either(Either::Left(_)))
    }
    /// True if [Either::Right] or [AnyOf::Both].
    pub fn has_right(&self) -> bool {
        matches!(self, Self::Either(Either::Right(_)) | Self::Both(_))
    }
    /// True if [Either::Right].
    pub fn is_right(&self) -> bool {
        matches!(self, Self::Either(Either::Right(_)))
    }
    /// True if not [AnyOf::Neither].
    pub fn is_any(&self) -> bool {
        matches!(
            self,
            Self::Either(Either::Left(_)) | Self::Either(Either::Right(_)) | Self::Both(_)
        )
    }
    /// True if [AnyOf::Either].
    pub fn is_one(&self) -> bool {
        matches!(
            self,
            Self::Either(_)
        )
    }
    /// True if [AnyOf::Both]
    pub fn is_both(&self) -> bool {
        matches!(self, Self::Both(_))
    }
    /// True if [AnyOf::Neither]
    pub fn is_neither(&self) -> bool {
        matches!(self, Self::Neither)
    }
    /// True if not [AnyOf::Either]
    pub fn is_neither_or_both(&self) -> bool {
        matches!(self, Self::Neither | Self::Both(_))
    }

    /// Returns `Some((&L, &R))` if `self.is_both()` is true, or `None`.
    pub fn both_or_none(&self) -> Option<Couple<&L, &R>> {
        Some((self.left()?, self.right()?))
    }

    /// Returns the left and/or right part(s) of this instance.
    ///
    /// Returns :
    /// * (None, None) if this instance is [Self::Neither],
    /// * (Some(&L), None) if this instance is [Either::Left]
    /// * (None, Some(&R)) if this instance is [Either::Right]
    /// * (Some(&L), Some(&R)) if this instance is [Self::Both]
    pub fn any(&self) -> Couple<Option<&L>, Option<&R>> {
        (self.left(), self.right())
    }

    /// Returns `Some(&L)` if `self.has_left()` is true, or `None`.
    pub fn left(&self) -> Option<&L> {
        match self {
            Self::Neither => None,
            Self::Either(Either::Left(l)) => Some(l),
            Self::Either(Either::Right(_)) => None,
            Self::Both(Both { left: l, .. }) => Some(l),
        }
    }

    /// Returns `Some(&R)` if `self.has_right()` is true, or `None`.
    pub fn right(&self) -> Option<&R> {
        match self {
            Self::Neither => None,
            Self::Either(Either::Left(_)) => None,
            Self::Either(Either::Right(r)) => Some(r),
            Self::Both(Both { right: r, .. }) => Some(r),
        }
    }

    pub fn left_or_else(self, f: impl FnOnce() -> L) -> L {
        match self {
            Self::Neither => f(),
            Self::Either(Either::Left(l)) => l,
            Self::Either(Either::Right(_)) => f(),
            Self::Both(Both { left: l, .. }) => l,
        }
    }
    pub fn right_or_else(self, f: impl FnOnce() -> R) -> R {
        match self {
            Self::Neither => f(),
            Self::Either(Either::Left(_)) => f(),
            Self::Either(Either::Right(r)) => r,
            Self::Both(Both { right: r, .. }) => r,
        }
    }
    pub fn both_or_else(self, f: impl FnOnce() -> Both<L, R>) -> Both<L, R> {
        match self {
            Self::Neither => f(),
            Self::Either(Either::Left(l)) => Both::new(l, f().right),
            Self::Either(Either::Right(r)) => Both::new(f().left, r),
            Self::Both(b) => b,
        }
    }
    pub fn left_or(self, other: L) -> L {
        self.left_or_else(|| other)
    }
    pub fn right_or(self, other: R) -> R {
        self.right_or_else(|| other)
    }
    pub fn both_or(self, other: Both<L, R>) -> Both<L, R> {
        self.both_or_else(|| other)
    }
    pub fn unwrap_left(self) -> L {
        self.left_or_else(|| panic!("Can only unwrap left of Either::Left or Either::Both"))
    }
    pub fn unwrap_right(self) -> R {
        self.right_or_else(|| panic!("Can only unwrap right of Either::Right or Either::Both"))
    }
    pub fn unwrap_both(self) -> Both<L, R> {
        self.both_or_else(|| panic!("Can only unwrap both of Either::Both"))
    }
    pub fn filter_left(self) -> Self {
        match self {
            Self::Neither => Self::Neither,
            Self::Either(Either::Left(l)) => Self::Either(Either::Left(l)),
            Self::Either(Either::Right(_)) => Self::Neither,
            Self::Both(Both { left: l, .. }) => Self::Either(Either::Left(l)),
        }
    }
    pub fn filter_right(self) -> Self {
        match self {
            Self::Neither => Self::Neither,
            Self::Either(Either::Left(_)) => Self::Neither,
            Self::Either(Either::Right(r)) => Self::Either(Either::Right(r)),
            Self::Both(Both { right: r, .. }) => Self::Either(Either::Right(r)),
        }
    }
    pub fn with_right(self, right: R) -> Self {
        match self {
            Self::Neither => Self::Either(Either::Right(right)),
            Self::Either(Either::Left(l)) => Self::Both(Both { left: l, right }),
            Self::Either(Either::Right(_)) => Self::Either(Either::Right(right)),
            Self::Both(Both { left: l, .. }) => Self::Both(Both { left: l, right }),
        }
    }
    pub fn with_left(self, left: L) -> Self {
        match self {
            Self::Neither => Self::Either(Either::Left(left)),
            Self::Either(Either::Left(_)) => Self::Either(Either::Left(left)),
            Self::Either(Either::Right(r)) => Self::Both(Both { left, right: r }),
            Self::Both(Both { right: r, .. }) => Self::Both(Both { left, right: r }),
        }
    }
    pub fn swap(self) -> AnyOf<R, L> {
        match self {
            Self::Neither => AnyOf::<R, L>::Neither,
            Self::Either(Either::Left(l)) => AnyOf::<R, L>::Either(Either::Right(l)),
            Self::Either(Either::Right(r)) => AnyOf::<R, L>::Either(Either::Left(r)),
            Self::Both(Both { left: l, right: r }) => {
                AnyOf::<R, L>::Both(Both { left: r, right: l })
            }
        }
    }
    pub fn map_left<FL, L2>(self, f: FL) -> AnyOf<L2, R>
    where
        FL: FnOnce(L) -> L2,
    {
        self.map(f, |r| r)
    }
    pub fn map_right<FR, R2>(self, f: FR) -> AnyOf<L, R2>
    where
        FR: FnOnce(R) -> R2,
    {
        self.map(|l| l, f)
    }

    pub fn map<FL, FR, L2, R2>(self, fl: FL, fr: FR) -> AnyOf<L2, R2>
    where
        FL: FnOnce(L) -> L2,
        FR: FnOnce(R) -> R2,
    {
        match self {
            Self::Neither => AnyOf::<L2, R2>::Neither,
            Self::Either(Either::Left(l)) => AnyOf::<L2, R2>::Either(Either::Left(fl(l))),
            Self::Either(Either::Right(r)) => AnyOf::<L2, R2>::Either(Either::Right(fr(r))),
            Self::Both(Both { left: l, right: r }) => AnyOf::<L2, R2>::Both(Both {
                left: fl(l),
                right: fr(r),
            }),
        }
    }

    /// Combines (`+` operator) two `Either` values into a single one.
    ///
    /// ## General rules
    ///
    /// * `Neither` is always substituted by the other operand,
    /// * `Both` :
    ///     * as left operand : substitutes the other operand,
    ///     * as right operand : completes the other operand,
    /// * `Left` or `Right` :
    ///     * `L+R` or `R+L` combines to an instance of `Both`,
    ///     * `L+l` or `r+R` selects the operand placed on the correct side of the operator :
    ///         * left**Left** + right**Left** = left**Left**
    ///         * left**Right** + right**Right** = right**Right**
    ///
    /// ## All cases
    ///
    /// * Neither cases :
    ///     * Neither + **other** = other
    ///     * **other** + Neither = other
    /// * Trivial cases :
    ///     * **Left(x)** + Left(y) = Left(x)
    ///     * Right(x) + **Right(y)** = Right(y)
    ///     * **Both(x, y)** + other = Both(x, y)
    /// * Merge cases :
    ///     * Left(x) + Right(y) = Both(x, y)
    ///     * Right(x) + Left(y) = Both(y, x)
    ///     * Left(x) + Both(_, y) = Both(x, y)
    ///     * Right(x) + Both(y, _) = Both(y, x)
    pub fn combine(self, other: Self) -> Self {
        match self {
            Self::Neither => other,
            Self::Either(Either::Left(l)) => match other {
                AnyOf::Neither => Self::Either(Either::Left(l)),
                AnyOf::Either(Either::Left(_)) => Self::Either(Either::Left(l)),
                AnyOf::Either(Either::Right(r)) => Self::Both(Both { left: l, right: r }),
                AnyOf::Both(Both { right: r, .. }) => Self::Both(Both { left: l, right: r }),
            },
            Self::Either(Either::Right(r)) => match other {
                AnyOf::Neither => Self::Either(Either::Right(r)),
                AnyOf::Either(Either::Left(l)) => Self::Both(Both { left: l, right: r }),
                AnyOf::Either(Either::Right(r2)) => Self::Either(Either::Right(r2)),
                AnyOf::Both(Both { left: l, .. }) => Self::Both(Both { left: l, right: r }),
            },
            Self::Both(b) => Self::Both(b),
        }
    }
}

impl<L, R> Add for AnyOf<L, R> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        self.combine(rhs)
    }
}

pub mod any_of_n;