any_of 2.1.1

A general optional sum of product 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
459
460
461
462
463
464
465
//! This module defines utility types and traits for working with dual-variant data structures,
//! such as "product types" (tuples) and "sum types" (LeftOrRight) that can hold one of two possible variants.
//!
//! It includes definitions for `Couple`, `Pair`, and the `LeftOrRight` trait,
//! providing type-safe methods for ergonomic and efficient access to such data.

use core::ops::Not;

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

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

/// A shortcut for `(Option<T>, Option<U>)`.
///
/// It is a valid representation of a [crate::AnyOf].
pub type Any<T, U> = Couple<Option<T>, Option<U>>;

/// The `LeftOrRight` trait provides utility methods for working with types that
/// can represent one of two possible variants: a "left" variant (`L`) or a
/// "right" variant (`R`) (or possibly both).
///
/// ## Provided Methods
///
/// - **`is_left`**: Checks if the value is the `L` (left) variant.
/// - **`is_right`**: Checks if the value is the `R` (right) variant.
/// - **`any`**: Returns both left and right values wrapped in `Option`s as a tuple.
/// - **`left`**: Returns a reference to the left variant if present.
/// - **`right`**: Returns a reference to the right variant if present.
///
/// This trait is useful for types implementing a "sum type"-like behavior, where
/// values may contain one of two possible forms, and you need utilities for
/// type-safe and ergonomic access to their internals.
pub trait LeftOrRight<L, R> {
    /// Returns a reference to the left value if it exists.
    ///
    /// ## Returns
    ///
    /// An `Option` containing a reference to the left value if the variant is `L`,
    /// otherwise `None`.
    fn left(&self) -> Option<&L>;

    /// Returns a reference to the right value if it exists.
    ///
    /// ## Returns
    ///
    /// An `Option` containing a reference to the right value if the variant is `R`,
    /// otherwise `None`.
    fn right(&self) -> Option<&R>;

    /// Checks if the `LeftOrRight<L, R>` value is the `L` variant.
    ///
    /// ## Returns
    ///
    /// `true` if the value is `L`, otherwise `false`.
    fn is_left(&self) -> bool {
        self.left().is_some()
    }

    /// Checks if the `LeftOrRight<L, R>` value is the `R` variant.
    ///
    /// ## Returns
    ///
    /// `true` if the value is `R`, otherwise `false`.
    fn is_right(&self) -> bool {
        self.right().is_some()
    }

    /// Returns references to the `L` or `R` values as a tuple of `Option`.
    ///
    /// ## Returns
    ///
    /// A tuple containing an `Option` reference to the left value and an `Option`
    /// reference to the right value.
    fn any(&self) -> Couple<Option<&L>, Option<&R>> {
        (self.left(), self.right())
    }
}

/// The `Swap` trait extends the `LeftOrRight` trait to include the ability to swap
/// the "left" and "right" variants of a type.
///
/// This can be particularly useful when working with dual-variant data structures,
/// where you need to reverse their roles in a type-safe manner.
///
/// ## Associated Type
/// - **`Output`**: The resulting type after swapping the `left` and `right` variants.
///
/// ## Provided Method
/// - **`swap`**: Produces a new instance with the `left` and `right` values swapped.
///
/// # Examples
/// ```rust
/// use any_of::BothOf;
/// use any_of::Swap;
///
/// let both = BothOf::new(42, "example");
/// let swapped = both.swap();
///
/// assert_eq!(swapped.left, "example");
/// assert_eq!(swapped.right, 42);
/// ```
pub trait Swap<L, R>: LeftOrRight<L, R> + Not<Output = <Self as Swap<L, R>>::Output> {
    type Output: LeftOrRight<R, L>;

    /// Swaps the `left` and `right` values of this `dyn LeftOrRight` instance.
    ///
    /// # Returns
    /// A new `dyn LeftOrRight` instance where the `left` and `right` values are swapped.
    ///
    /// # Examples
    /// ```rust
    /// use any_of::BothOf;
    /// use any_of::Swap;
    ///
    /// let both = BothOf::new(42, "example");
    /// let swapped = both.swap();
    ///
    /// assert_eq!(swapped.left, "example");
    /// assert_eq!(swapped.right, 42);
    /// ```
    fn swap(self) -> <Self as Swap<L, R>>::Output
    where
        Self: Sized,
    {
        self.not()
    }
}

/// The `Map` trait provides utilities for transforming the `left` or `right` variants
/// of a dual-variant type (`LeftOrRight`).
///
/// This allows for ergonomic and type-safe transformations of either side of the data structure.
///
/// ## Provided Methods
///
/// - **`map_left`**: Applies a transformation to the `left` value while leaving the
///   `right` value unchanged.
/// - **`map_right`**: Applies a transformation to the `right` value while leaving the
///   `left` value unchanged.
/// - **`map`**: Applies separate transformations to the `left` and `right` values
///   based on the variant.
pub trait Map<L, R>: LeftOrRight<L, R> {
    type Output<L2, R2>: LeftOrRight<L2, R2>;

    /// Transforms the `L` value using a provided function.
    ///
    /// ## Arguments
    ///
    /// * `f` - A function to transform the left value.
    ///
    /// ## Returns
    ///
    /// An `LeftOrRight` where the `L` value has been transformed to an `L2`. The `R` value,
    /// if present, remains unchanged.
    fn map_left<FL, L2>(self, f: FL) -> Self::Output<L2, R>
    where
        Self: Sized,
        FL: FnOnce(L) -> L2,
    {
        self.map(f, |r| r)
    }

    /// Transforms the `R` value using a provided function.
    ///
    /// ## Arguments
    ///
    /// * `f` - A function to transform the right value.
    ///
    /// ## Returns
    ///
    /// An `LeftOrRight` where the `R` value has been transformed to an `R2`. The `L` value,
    /// if present, remains unchanged.
    fn map_right<FR, R2>(self, f: FR) -> Self::Output<L, R2>
    where
        Self: Sized,
        FR: FnOnce(R) -> R2,
    {
        self.map(|l| l, f)
    }

    /// Transforms the `L` or `R` value using separate functions, depending
    /// on the variant.
    ///
    /// ## Arguments
    ///
    /// * `fl` - A function to transform the left value.
    /// * `fr` - A function to transform the right value.
    ///
    /// ## Returns
    ///
    /// An `LeftOrRight` where the `Left` or `Right` value has been transformed
    /// by the corresponding function.
    fn map<FL, FR, L2, R2>(self, fl: FL, fr: FR) -> Self::Output<L2, R2>
    where
        FL: FnOnce(L) -> L2,
        FR: FnOnce(R) -> R2;
}

/// The `Unwrap` trait provides utilities for safely extracting values from
/// a dual-variant type (`LeftOrRight`).
///
/// It allows ergonomic operations that retrieve either the left or right value,
/// with fallbacks when the expected variant is not present.
///
/// ## Usage
///
/// The `Unwrap` trait simplifies the handling of `LeftOrRight` types by providing
/// convenient methods to extract values transparently or substitute a value when
/// the expected variant does not exist.
///
/// ## Examples
///
/// ```rust
/// use any_of::{EitherOf, Unwrap, Left, Right};
///
/// let left: EitherOf<i32, &str> = Left(42);
/// let right: EitherOf<i32, &str> = Right("example");
///
/// // Retrieve the left value, or default to 0
/// assert_eq!(left.left_or_default(), 42);
/// assert_eq!(right.left_or_default(), 0);
///
/// // Use closures to provide alternate values
/// assert_eq!(right.left_or_else(|| 100), 100);
/// assert_eq!(left.right_or_else(|| "default"), "default");
///
/// // Use custom default values
/// assert_eq!(left.left_or(99), 42);
/// assert_eq!(right.right_or("new default"), "example");
/// ```
///
/// This trait is especially useful in scenarios where fallbacks or default
/// values need to be derived dynamically or when working with optional or
/// fallible data structures.
pub trait Unwrap<L, R>: LeftOrRight<L, R> {
    /// Returns the left value or computes a default using the provided closure.
    ///
    /// ## Arguments
    ///
    /// * `f` - A closure that generates a default value if the variant is `R`.
    ///
    /// ## Returns
    ///
    /// The left value if the variant is `L`, otherwise the default value generated
    /// by the closure.
    fn left_or_else(self, f: impl FnOnce() -> L) -> L;

    /// Returns the right value or computes a default using the provided closure.
    ///
    /// ## Arguments
    ///
    /// * `f` - A closure that generates a default value if the variant is `L`.
    ///
    /// ## Returns
    ///
    /// The right value if the variant is `R`, otherwise the default value generated
    /// by the closure.
    fn right_or_else(self, f: impl FnOnce() -> R) -> R;

    /// Returns the left value or a provided default.
    ///
    /// ## Arguments
    ///
    /// * `other` - The default value to use if the variant is `Right`.
    ///
    /// ## Returns
    ///
    /// The left value if the variant is `Left`, otherwise the provided default value.
    fn left_or(self, l: L) -> L
    where
        Self: Sized,
    {
        self.left_or_else(|| l)
    }

    /// Returns the right value or a provided default.
    ///
    /// ## Arguments
    ///
    /// * `other` - The default value to use if the variant is `Left`.
    ///
    /// ## Returns
    ///
    /// The right value if the variant is `Right`, otherwise the provided default value.
    fn right_or(self, r: R) -> R
    where
        Self: Sized,
    {
        self.right_or_else(|| r)
    }

    /// Returns the left value or a default value.
    ///
    /// If the variant is `Left`, this method returns the `left` value.
    /// Otherwise, it returns the default value of the `L` type.
    ///
    /// ## Returns
    ///
    /// * `L` - The left value if it exists, or the default value of `L` otherwise.
    ///
    /// ## Requirements
    ///
    /// * The `L` type must implement the `Default` trait.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use any_of::{EitherOf, Unwrap, Left, Right};
    ///
    /// let left: EitherOf<i32, &str> = Left(42);
    /// let right: EitherOf<i32, &str> = Right("example");
    ///
    /// // Returns the left value as it exists.
    /// assert_eq!(left.left_or_default(), 42);
    ///
    /// // Returns the default value for i32 (0) because the variant is `Right`.
    /// assert_eq!(right.left_or_default(), 0);
    /// ```
    fn left_or_default(self) -> L
    where
        Self: Sized,
        L: Default,
    {
        self.left_or(L::default())
    }

    /// Returns the right value or a default value.
    ///
    /// If the variant is `Right`, this method returns the `right` value.
    /// Otherwise, it returns the default value of the `R` type.
    ///
    /// ## Returns
    ///
    /// * `R` - The right value if it exists, or the default value of `R` otherwise.
    ///
    /// ## Requirements
    ///
    /// * The `R` type must implement the `Default` trait.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use any_of::{EitherOf, Unwrap, Left, Right};
    ///
    /// let left: EitherOf<i32, &str> = Left(42);
    /// let right: EitherOf<i32, &str> = Right("example");
    ///
    /// // Returns the default value for &str ("") because the variant is `Left`.
    /// assert_eq!(left.right_or_default(), "");
    ///
    /// // Returns the right value as it exists.
    /// assert_eq!(right.right_or_default(), "example");
    /// ```
    fn right_or_default(self) -> R
    where
        Self: Sized,
        R: Default,
    {
        self.right_or(R::default())
    }

    /// Extracts the left value, panicking with the provided message if the variant is `Right`.
    ///
    /// ## Arguments
    ///
    /// * `msg` - The panic message to display if the variant is `Right`.
    ///
    /// ## Panics
    ///
    /// Panics if the variant is `Right`.
    ///
    /// ## Returns
    ///
    /// The left value if the variant is `Left`.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use any_of::{EitherOf, Unwrap, Left, Right};
    ///
    /// let left: EitherOf<i32, &str> = Left(42);
    /// let right: EitherOf<i32, &str> = Right("example");
    ///
    /// // Successfully extracts the left value.
    /// assert_eq!(left.expect_left("Expected left value"), 42);
    ///
    /// // Panics with the provided message.
    /// // right.expect_left("Expected left value");
    /// ```
    fn expect_left(self, msg: &str) -> L
    where
        Self: Sized,
    {
        self.left_or_else(|| panic!("{}", msg))
    }

    /// Extracts the right value, panicking with the provided message if the variant is `Left`.
    ///
    /// ## Arguments
    ///
    /// * `msg` - The panic message to display if the variant is `Left`.
    ///
    /// ## Panics
    ///
    /// Panics if the variant is `Left`.
    ///
    /// ## Returns
    ///
    /// The right value if the variant is `Right`.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use any_of::{EitherOf, Unwrap, Left, Right};
    ///
    /// let left: EitherOf<i32, &str> = Left(42);
    /// let right: EitherOf<i32, &str> = Right("example");
    ///
    /// // Successfully extracts the right value.
    /// assert_eq!(right.expect_right("Expected right value"), "example");
    ///
    /// // Panics with the provided message.
    /// // left.expect_right("Expected right value");
    /// ```
    fn expect_right(self, msg: &str) -> R
    where
        Self: Sized,
    {
        self.right_or_else(|| panic!("{}", msg))
    }

    /// Extracts the left value, panicking if the variant is `Right`.
    ///
    /// ## Panics
    ///
    /// Panics if the variant is `Right`.
    ///
    /// ## Returns
    ///
    /// The left value if the variant is `Left`.
    fn unwrap_left(self) -> L
    where
        Self: Sized,
    {
        self.expect_left("called `unwrap_left` on `LeftOrRight` value that is `Right`")
    }

    /// Extracts the right value, panicking if the variant is `Left`.
    ///
    /// ## Panics
    ///
    /// Panics if the variant is `Left`.
    ///
    /// ## Returns
    ///
    /// The right value if the variant is `Right`.
    fn unwrap_right(self) -> R
    where
        Self: Sized,
    {
        self.expect_right("called `unwrap_right` on `LeftOrRight` value that is `Left`")
    }
}