among/
lib.rs

1// This code is inspired and modified based on [`rayon-rs/either`](https://github.com/rayon-rs/either).
2
3#![doc = include_str!("../README.md")]
4#![no_std]
5#![cfg_attr(docsrs, feature(doc_cfg))]
6#![cfg_attr(docsrs, allow(unused_attributes))]
7
8#[cfg(any(test, feature = "std"))]
9extern crate std;
10
11#[cfg(feature = "serde")]
12pub mod serde_untagged;
13
14#[cfg(feature = "serde")]
15pub mod serde_untagged_optional;
16
17#[cfg(feature = "either")]
18mod either_impl;
19#[cfg(feature = "either")]
20#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
21pub use either_impl::*;
22
23#[cfg(all(feature = "futures-io", feature = "std"))]
24mod futures_impl;
25
26#[cfg(feature = "tokio")]
27mod tokio_impl;
28
29mod result_ext;
30pub use result_ext::*;
31
32use core::convert::{AsMut, AsRef};
33use core::fmt;
34use core::future::Future;
35use core::ops::Deref;
36use core::ops::DerefMut;
37use core::pin::Pin;
38
39#[cfg(any(test, feature = "std"))]
40use std::error::Error;
41#[cfg(any(test, feature = "std"))]
42use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
43
44pub use crate::Among::{Left, Middle, Right};
45
46/// The enum `Among` with variants `Left`, `Middle` and `Right` is a general purpose
47/// sum type with three cases.
48///
49/// The `Among` type is symmetric and treats its variants the same way, without
50/// preference.
51/// (For representing success or error, use the regular `Result` enum instead.)
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
54pub enum Among<L, M, R> {
55  /// A value of type `L`.
56  Left(L),
57  /// A value of type `M`.
58  Middle(M),
59  /// A value of type `R`.
60  Right(R),
61}
62
63/// Evaluate the provided expression for both [`Among::Left`] and [`Among::Right`].
64///
65/// This macro is useful in cases where both sides of [`Among`] can be interacted with
66/// in the same way even though the don't share the same type.
67///
68/// Syntax: `among::for_all!(` *expression* `,` *pattern* `=>` *expression* `)`
69///
70/// # Example
71///
72/// ```
73/// use among::Among;
74/// use std::borrow::Cow;
75///
76/// fn length(owned_or_borrowed: Among<String, Cow<'static, str>, &'static str>) -> usize {
77///     among::for_all!(owned_or_borrowed, s => s.len())
78/// }
79///
80/// fn main() {
81///     let borrowed = Among::Right("Hello world!");
82///     let owned = Among::Left("Hello world!".to_owned());
83///     let mixed = Among::Middle(Cow::Borrowed("Hello world!"));
84///
85///     assert_eq!(length(borrowed), 12);
86///     assert_eq!(length(mixed), 12);
87///     assert_eq!(length(owned), 12);
88/// }
89/// ```
90#[macro_export]
91macro_rules! for_all {
92  ($value:expr, $pattern:pat => $result:expr) => {
93    match $value {
94      $crate::Among::Middle($pattern) => $result,
95      $crate::Among::Left($pattern) => $result,
96      $crate::Among::Right($pattern) => $result,
97    }
98  };
99}
100
101macro_rules! map_among {
102  ($value:expr, $pattern:pat => $result:expr) => {
103    match $value {
104      Left($pattern) => Left($result),
105      Middle($pattern) => Middle($result),
106      Right($pattern) => Right($result),
107    }
108  };
109}
110
111mod iterator;
112pub use self::iterator::IterAmong;
113
114mod into_among;
115pub use self::into_among::IntoAmong;
116
117impl<L: Clone, M: Clone, R: Clone> Clone for Among<L, M, R> {
118  fn clone(&self) -> Self {
119    match self {
120      Left(inner) => Left(inner.clone()),
121      Middle(inner) => Middle(inner.clone()),
122      Right(inner) => Right(inner.clone()),
123    }
124  }
125
126  fn clone_from(&mut self, source: &Self) {
127    match (self, source) {
128      (Left(dest), Left(source)) => dest.clone_from(source),
129      (Right(dest), Right(source)) => dest.clone_from(source),
130      (dest, source) => *dest = source.clone(),
131    }
132  }
133}
134
135impl<L, M, R> Among<L, M, R> {
136  /// Return true if the value is the `Left` variant.
137  ///
138  /// ```
139  /// use among::*;
140  ///
141  /// let values = [Left(1), Middle(b"the middle value"), Right("the right value")];
142  /// assert_eq!(values[0].is_left(), true);
143  /// assert_eq!(values[1].is_left(), false);
144  /// assert_eq!(values[2].is_left(), false);
145  /// ```
146  pub fn is_left(&self) -> bool {
147    match *self {
148      Left(_) => true,
149      _ => false,
150    }
151  }
152
153  /// Return true if the value is the `Right` variant.
154  ///
155  /// ```
156  /// use among::*;
157  ///
158  /// let values = [Left(1), Middle(b"the middle value"), Right("the right value")];
159  /// assert_eq!(values[0].is_right(), false);
160  /// assert_eq!(values[1].is_right(), false);
161  /// assert_eq!(values[2].is_right(), true);
162  /// ```
163  pub fn is_right(&self) -> bool {
164    match *self {
165      Right(_) => true,
166      _ => false,
167    }
168  }
169
170  /// Return true if the value is the `Right` variant.
171  ///
172  /// ```
173  /// use among::*;
174  ///
175  /// let values = [Left(1), Middle(b"the middle value"), Right("the right value")];
176  /// assert_eq!(values[0].is_middle(), false);
177  /// assert_eq!(values[1].is_middle(), true);
178  /// assert_eq!(values[2].is_middle(), false);
179  /// ```
180  pub fn is_middle(&self) -> bool {
181    match *self {
182      Middle(_) => true,
183      _ => false,
184    }
185  }
186
187  /// Convert the left side of `Among<L, M, R>` to an `Option<L>`.
188  ///
189  /// ```
190  /// use among::*;
191  ///
192  /// let left: Among<_, i64, ()> = Left("some value");
193  /// assert_eq!(left.left(),  Some("some value"));
194  ///
195  /// let right: Among<(), i64, _> = Right(321);
196  /// assert_eq!(right.left(), None);
197  ///
198  /// let middle: Among<(), i64, ()> = Middle(-321);
199  /// assert_eq!(middle.left(), None);
200  /// ```
201  pub fn left(self) -> Option<L> {
202    match self {
203      Left(l) => Some(l),
204      _ => None,
205    }
206  }
207
208  /// Convert the middle of `Among<L, M, R>` to an `Option<M>`.
209  ///
210  /// ```
211  /// use among::*;
212  ///
213  /// let left: Among<_, i64, ()> = Left("some value");
214  /// assert_eq!(left.middle(),  None);
215  ///
216  /// let right: Among<(), i64, _> = Right(321);
217  /// assert_eq!(right.middle(), None);
218  ///
219  /// let middle: Among<(), i64, ()> = Middle(-321);
220  /// assert_eq!(middle.middle(), Some(-321));
221  /// ```
222  pub fn middle(self) -> Option<M> {
223    match self {
224      Middle(m) => Some(m),
225      _ => None,
226    }
227  }
228
229  /// Convert the right side of `Among<L, M, R>` to an `Option<R>`.
230  ///
231  /// ```
232  /// use among::*;
233  ///
234  /// let left: Among<_, i64, ()> = Left("some value");
235  /// assert_eq!(left.right(),  None);
236  ///
237  /// let middle: Among<(), i64, ()> = Middle(-321);
238  /// assert_eq!(middle.right(), None);
239  ///
240  /// let right: Among<(), i64, _> = Right(321);
241  /// assert_eq!(right.right(), Some(321));
242  /// ```
243  pub fn right(self) -> Option<R> {
244    match self {
245      Right(r) => Some(r),
246      _ => None,
247    }
248  }
249
250  /// Convert `&Among<L, M, R>` to `Among<&L, &M, &R>`.
251  ///
252  /// ```
253  /// use among::*;
254  ///
255  /// let left: Among<_, i64, ()> = Left("some value");
256  /// assert_eq!(left.as_ref(), Left(&"some value"));
257  ///
258  /// let right: Among<(), i64, _> = Right("some value");
259  /// assert_eq!(right.as_ref(), Right(&"some value"));
260  ///
261  /// let middle: Among<(), _, ()> = Middle(-321);
262  /// assert_eq!(middle.as_ref(), Middle(&-321));
263  /// ```
264  pub fn as_ref(&self) -> Among<&L, &M, &R> {
265    match *self {
266      Left(ref inner) => Left(inner),
267      Middle(ref inner) => Middle(inner),
268      Right(ref inner) => Right(inner),
269    }
270  }
271
272  /// Convert `&mut Among<L, M, R>` to `Among<&mut L, &mut M, &mut R>`.
273  ///
274  /// ```
275  /// use among::*;
276  ///
277  /// fn mutate_left(value: &mut Among<u32, u32, u32>) {
278  ///     if let Some(l) = value.as_mut().left() {
279  ///         *l = 999;
280  ///     }
281  /// }
282  ///
283  /// let mut left = Left(123);
284  /// let mut middle = Middle(123);
285  /// let mut right = Right(123);
286  ///
287  /// mutate_left(&mut left);
288  /// mutate_left(&mut right);
289  /// mutate_left(&mut middle);
290  /// assert_eq!(left, Left(999));
291  /// assert_eq!(right, Right(123));
292  /// assert_eq!(middle, Middle(123));
293  /// ```
294  pub fn as_mut(&mut self) -> Among<&mut L, &mut M, &mut R> {
295    match *self {
296      Left(ref mut inner) => Left(inner),
297      Middle(ref mut inner) => Middle(inner),
298      Right(ref mut inner) => Right(inner),
299    }
300  }
301
302  /// Convert `Pin<&Among<L, M, R>>` to `Among<Pin<&L>, Pin<&M>, Pin<&R>>`,
303  /// pinned projections of the inner variants.
304  pub fn as_pin_ref(self: Pin<&Self>) -> Among<Pin<&L>, Pin<&M>, Pin<&R>> {
305    // SAFETY: We can use `new_unchecked` because the `inner` parts are
306    // guaranteed to be pinned, as they come from `self` which is pinned.
307    unsafe {
308      match *Pin::get_ref(self) {
309        Left(ref inner) => Left(Pin::new_unchecked(inner)),
310        Middle(ref inner) => Middle(Pin::new_unchecked(inner)),
311        Right(ref inner) => Right(Pin::new_unchecked(inner)),
312      }
313    }
314  }
315
316  /// Convert `Pin<&mut Among<L, M, R>>` to `Among<Pin<&mut L>, Pin<&mut M>, Pin<&mut R>>`,
317  /// pinned projections of the inner variants.
318  pub fn as_pin_mut(self: Pin<&mut Self>) -> Among<Pin<&mut L>, Pin<&mut M>, Pin<&mut R>> {
319    // SAFETY: `get_unchecked_mut` is fine because we don't move anything.
320    // We can use `new_unchecked` because the `inner` parts are guaranteed
321    // to be pinned, as they come from `self` which is pinned, and we never
322    // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We
323    // also don't have an implementation of `Drop`, nor manual `Unpin`.
324    unsafe {
325      match *Pin::get_unchecked_mut(self) {
326        Left(ref mut inner) => Left(Pin::new_unchecked(inner)),
327        Middle(ref mut inner) => Middle(Pin::new_unchecked(inner)),
328        Right(ref mut inner) => Right(Pin::new_unchecked(inner)),
329      }
330    }
331  }
332
333  /// Convert `Among<L, M, R>` to `Among<R, M, L>`.
334  ///
335  /// ```
336  /// use among::*;
337  ///
338  /// let left: Among<_, i64, ()> = Left(123);
339  /// assert_eq!(left.flip(), Right(123));
340  ///
341  /// let right: Among<(), i64, _> = Right("some value");
342  /// assert_eq!(right.flip(), Left("some value"));
343  /// ```
344  pub fn flip(self) -> Among<R, M, L> {
345    match self {
346      Left(l) => Right(l),
347      Right(r) => Left(r),
348      Middle(m) => Middle(m),
349    }
350  }
351
352  /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the
353  /// result in `Left`.
354  ///
355  /// ```
356  /// use among::*;
357  ///
358  /// let left: Among<_, u32, u32> = Left(123);
359  /// assert_eq!(left.map_left(|x| x * 2), Left(246));
360  ///
361  /// let right: Among<u32, u32,  _> = Right(123);
362  /// assert_eq!(right.map_left(|x| x * 2), Right(123));
363  ///
364  /// let middle: Among<u32, _, u32> = Middle(123);
365  /// assert_eq!(middle.map_left(|x| x * 3), Middle(123));
366  /// ```
367  pub fn map_left<F, N>(self, f: F) -> Among<N, M, R>
368  where
369    F: FnOnce(L) -> N,
370  {
371    match self {
372      Left(l) => Left(f(l)),
373      Middle(m) => Middle(m),
374      Right(r) => Right(r),
375    }
376  }
377
378  /// Apply the function `f` on the value in the `Middle` variant if it is present rewrapping the
379  /// result in `Middle`.
380  ///
381  /// ```
382  /// use among::*;
383  ///
384  /// let left: Among<_, u32, u32> = Left(123);
385  /// assert_eq!(left.map_middle(|x| x * 2), Left(123));
386  ///
387  /// let right: Among<u32, u32,  _> = Right(123);
388  /// assert_eq!(right.map_middle(|x| x * 2), Right(123));
389  ///
390  /// let middle: Among<u32, _, u32> = Middle(123);
391  /// assert_eq!(middle.map_middle(|x| x * 3), Middle(369));
392  /// ```
393  pub fn map_middle<F, N>(self, f: F) -> Among<L, N, R>
394  where
395    F: FnOnce(M) -> N,
396  {
397    match self {
398      Left(l) => Left(l),
399      Middle(m) => Middle(f(m)),
400      Right(r) => Right(r),
401    }
402  }
403
404  /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the
405  /// result in `Right`.
406  ///
407  /// ```
408  /// use among::*;
409  ///
410  /// let left: Among<_, u32, u32> = Left(123);
411  /// assert_eq!(left.map_right(|x| x * 2), Left(123));
412  ///
413  /// let right: Among<u32, u32, _> = Right(123);
414  /// assert_eq!(right.map_right(|x| x * 2), Right(246));
415  ///
416  /// let middle: Among<u32, _, u32> = Middle(123);
417  /// assert_eq!(middle.map_right(|x| x * 3), Middle(123));
418  /// ```
419  pub fn map_right<F, S>(self, f: F) -> Among<L, M, S>
420  where
421    F: FnOnce(R) -> S,
422  {
423    match self {
424      Left(l) => Left(l),
425      Middle(m) => Middle(m),
426      Right(r) => Right(f(r)),
427    }
428  }
429
430  /// Apply the functions `f` and `g` to the `Left` and `Right` variants
431  /// respectively. This is equivalent to
432  /// [bimap](https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html)
433  /// in functional programming.
434  ///
435  /// ```
436  /// use among::*;
437  ///
438  /// let f = |s: String| s.len();
439  /// let h = |t: u8| t.to_string();
440  /// let g = |u: usize| u * 2;
441  ///
442  /// let left: Among<String, usize, u8> = Left("loopy".into());
443  /// assert_eq!(left.map_among(f, g, h), Left(5));
444  ///
445  /// let right: Among<String, usize, u8> = Right(42);
446  /// assert_eq!(right.map_among(f, g, h), Right("42".into()));
447  /// ```
448  pub fn map_among<F, G, H, S, T, U>(self, f: F, g: G, h: H) -> Among<S, T, U>
449  where
450    F: FnOnce(L) -> S,
451    G: FnOnce(M) -> T,
452    H: FnOnce(R) -> U,
453  {
454    match self {
455      Left(l) => Left(f(l)),
456      Middle(m) => Middle(g(m)),
457      Right(r) => Right(h(r)),
458    }
459  }
460
461  /// Similar to [`map_among`][Self::map_among], with an added context `ctx` accessible to
462  /// both functions.
463  ///
464  /// ```
465  /// use among::*;
466  ///
467  /// let mut sum = 0;
468  ///
469  /// // Both closures want to update the same value, so pass it as context.
470  /// let mut f = |sum: &mut usize, s: String| { *sum += s.len(); s.to_uppercase() };
471  /// let mut g = |sum: &mut usize, i: i32| { *sum += i as usize; i.to_string() };
472  /// let mut h = |sum: &mut usize, u: usize| { *sum += u; u.to_string() };
473  ///
474  /// let left: Among<String, i32, usize> = Left("loopy".into());
475  /// assert_eq!(left.map_among_with(&mut sum, &mut f, &mut g, &mut h), Left("LOOPY".into()));
476  ///
477  /// let right: Among<String, i32, usize> = Right(42);
478  /// assert_eq!(right.map_among_with(&mut sum, &mut f, &mut g, &mut h), Right("42".into()));
479  ///
480  /// let middle: Among<String, i32, usize> = Middle(3);
481  /// assert_eq!(middle.map_among_with(&mut sum, &mut f, &mut g, &mut h), Middle("3".into()));
482  ///
483  /// assert_eq!(sum, 50);
484  /// ```
485  pub fn map_among_with<Ctx, F, G, H, S, T, U>(self, ctx: Ctx, f: F, g: G, h: H) -> Among<S, T, U>
486  where
487    F: FnOnce(Ctx, L) -> S,
488    G: FnOnce(Ctx, M) -> T,
489    H: FnOnce(Ctx, R) -> U,
490  {
491    match self {
492      Left(l) => Left(f(ctx, l)),
493      Middle(m) => Middle(g(ctx, m)),
494      Right(r) => Right(h(ctx, r)),
495    }
496  }
497
498  /// Apply one of three functions depending on contents, unifying their result. If the value is
499  /// `Left(L)` then the first function `f` is applied; if it is `Middle(M)` then the second function `g` is applied;
500  /// if it is `Right(R)` then the third function `h` is applied.
501  ///
502  /// ```
503  /// use among::*;
504  ///
505  /// fn square(n: u32) -> i32 { (n * n) as i32 }
506  /// fn negate(n: i32) -> i32 { -n }
507  /// fn cube(n: u64) -> i32 { (n * n * n) as i32 }
508  ///
509  /// let left: Among<u32, u64, i32> = Left(4);
510  /// assert_eq!(left.among(square, cube, negate), 16);
511  ///
512  /// let right: Among<u32, u64, i32> = Right(-4);
513  /// assert_eq!(right.among(square, cube, negate), 4);
514  ///
515  /// let middle: Among<u32, u64, i32> = Middle(3);
516  /// assert_eq!(middle.among(square, cube, negate), 27);
517  /// ```
518  pub fn among<F, G, H, T>(self, f: F, g: G, h: H) -> T
519  where
520    F: FnOnce(L) -> T,
521    G: FnOnce(M) -> T,
522    H: FnOnce(R) -> T,
523  {
524    match self {
525      Left(l) => f(l),
526      Middle(m) => g(m),
527      Right(r) => h(r),
528    }
529  }
530
531  /// Like [`among`][Self::among], but provide some context to whichever of the
532  /// functions ends up being called.
533  ///
534  /// ```
535  /// // In this example, the context is a mutable reference
536  /// use among::*;
537  ///
538  /// let mut result = Vec::new();
539  ///
540  /// let values = vec![Left(2), Middle(-3), Right(2.7)];
541  ///
542  /// for value in values {
543  ///     value.among_with(&mut result,
544  ///                       |ctx, integer| ctx.push(integer),
545  ///                       |ctx, neg| ctx.push(neg),
546  ///                       |ctx, real| ctx.push(f64::round(real) as i32));
547  /// }
548  ///
549  /// assert_eq!(result, vec![2, -3, 3]);
550  /// ```
551  pub fn among_with<Ctx, F, G, H, T>(self, ctx: Ctx, f: F, g: G, h: H) -> T
552  where
553    F: FnOnce(Ctx, L) -> T,
554    G: FnOnce(Ctx, M) -> T,
555    H: FnOnce(Ctx, R) -> T,
556  {
557    match self {
558      Left(l) => f(ctx, l),
559      Middle(m) => g(ctx, m),
560      Right(r) => h(ctx, r),
561    }
562  }
563
564  /// Apply the function `f` on the value in the `Left` variant if it is present.
565  ///
566  /// ```
567  /// use among::*;
568  ///
569  /// let left: Among<_, u32, u32> = Left(123);
570  /// assert_eq!(left.left_and_then::<_, ()>(|x| Right(x * 2)), Right(246));
571  ///
572  /// let right: Among<u32, u32, _> = Right(123);
573  /// assert_eq!(right.left_and_then(|x| Right::<(), _, _>(x * 2)), Right(123));
574  /// ```
575  pub fn left_and_then<F, S>(self, f: F) -> Among<S, M, R>
576  where
577    F: FnOnce(L) -> Among<S, M, R>,
578  {
579    match self {
580      Left(l) => f(l),
581      Middle(m) => Middle(m),
582      Right(r) => Right(r),
583    }
584  }
585
586  /// Apply the function `f` on the value in the `Middle` variant if it is present.
587  ///
588  /// ```
589  /// use among::*;
590  ///
591  /// let middle: Among<u32, _, u32> = Middle(123);
592  /// assert_eq!(middle.middle_and_then::<_, ()>(|x| Right(x * 2)), Right(246));
593  ///
594  /// let right: Among<u32, u32, _> = Right(123);
595  /// assert_eq!(right.middle_and_then(|x| Right::<_, (), _>(x * 2)), Right(123));
596  /// ```
597  pub fn middle_and_then<F, S>(self, f: F) -> Among<L, S, R>
598  where
599    F: FnOnce(M) -> Among<L, S, R>,
600  {
601    match self {
602      Left(l) => Left(l),
603      Middle(m) => f(m),
604      Right(r) => Right(r),
605    }
606  }
607
608  /// Apply the function `f` on the value in the `Right` variant if it is present.
609  ///
610  /// ```
611  /// use among::*;
612  ///
613  /// let left: Among<_, u32, u32> = Left(123);
614  /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123));
615  ///
616  /// let right: Among<u32, u32, _> = Right(123);
617  /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246));
618  /// ```
619  pub fn right_and_then<F, S>(self, f: F) -> Among<L, M, S>
620  where
621    F: FnOnce(R) -> Among<L, M, S>,
622  {
623    match self {
624      Left(l) => Left(l),
625      Middle(m) => Middle(m),
626      Right(r) => f(r),
627    }
628  }
629
630  /// Convert the inner value to an iterator.
631  ///
632  /// This requires the `Left`, `Middle` and `Right` iterators to have the same item type.
633  /// See [`factor_into_iter`][Among::factor_into_iter] to iterate different types.
634  ///
635  /// ```
636  /// use among::*;
637  ///
638  /// let left: Among<Vec<u32>, Vec<u32>, Vec<u32>> = Left(vec![1, 2, 3, 4, 5]);
639  /// let mut right: Among<Vec<u32>, Vec<u32>, Vec<u32>> = Right(vec![]);
640  /// right.extend(left.into_iter());
641  /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5]));
642  /// ```
643  #[allow(clippy::should_implement_trait)]
644  pub fn into_iter(self) -> Among<L::IntoIter, M::IntoIter, R::IntoIter>
645  where
646    L: IntoIterator,
647    M: IntoIterator<Item = L::Item>,
648    R: IntoIterator<Item = L::Item>,
649  {
650    map_among!(self, inner => inner.into_iter())
651  }
652
653  /// Borrow the inner value as an iterator.
654  ///
655  /// This requires the `Left`, `Middle` and `Right` iterators to have the same item type.
656  /// See [`factor_iter`][Among::factor_iter] to iterate different types.
657  ///
658  /// ```
659  /// use among::*;
660  ///
661  /// let left: Among<_, &[u32], &[u32]> = Left(vec![2, 3]);
662  /// let mut right: Among<Vec<u32>, &[u32], _> = Right(&[4, 5][..]);
663  /// let mut all = vec![1];
664  /// all.extend(left.iter());
665  /// all.extend(right.iter());
666  /// assert_eq!(all, vec![1, 2, 3, 4, 5]);
667  /// ```
668  pub fn iter(
669    &self,
670  ) -> Among<
671    <&L as IntoIterator>::IntoIter,
672    <&M as IntoIterator>::IntoIter,
673    <&R as IntoIterator>::IntoIter,
674  >
675  where
676    for<'a> &'a L: IntoIterator,
677    for<'a> &'a M: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
678    for<'a> &'a R: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
679  {
680    map_among!(self, inner => inner.into_iter())
681  }
682
683  /// Mutably borrow the inner value as an iterator.
684  ///
685  /// This requires the `Left`, `Middle` and `Right` iterators to have the same item type.
686  /// See [`factor_iter_mut`][Among::factor_iter_mut] to iterate different types.
687  ///
688  /// ```
689  /// use among::*;
690  ///
691  /// let mut left: Among<_, Vec<u32>, &mut [u32]> = Left(vec![2, 3]);
692  /// for l in left.iter_mut() {
693  ///     *l *= *l
694  /// }
695  /// assert_eq!(left, Left(vec![4, 9]));
696  ///
697  /// let mut inner = [4, 5];
698  /// let mut right: Among<Vec<u32>, Vec<u32>, _> = Right(&mut inner[..]);
699  /// for r in right.iter_mut() {
700  ///     *r *= *r
701  /// }
702  /// assert_eq!(inner, [16, 25]);
703  ///
704  /// let mut inner = [6, 7];
705  /// let mut middle: Among<Vec<u32>, _, Vec<u32>> = Middle(&mut inner[..]);
706  /// for r in middle.iter_mut() {
707  ///     *r *= *r
708  /// }
709  /// assert_eq!(inner, [36, 49]);
710  /// ```
711  pub fn iter_mut(
712    &mut self,
713  ) -> Among<
714    <&mut L as IntoIterator>::IntoIter,
715    <&mut M as IntoIterator>::IntoIter,
716    <&mut R as IntoIterator>::IntoIter,
717  >
718  where
719    for<'a> &'a mut L: IntoIterator,
720    for<'a> &'a mut M: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
721    for<'a> &'a mut R: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
722  {
723    map_among!(self, inner => inner.into_iter())
724  }
725
726  /// Converts an `Among` of `Iterator`s to be an `Iterator` of `Among`s
727  ///
728  /// Unlike [`into_iter`][Among::into_iter], this does not require the
729  /// `Left` and `Right` iterators to have the same item type.
730  ///
731  /// ```
732  /// use among::*;
733  /// let left: Among<_, Box<[u8]>, Vec<u8>> = Left(&["hello"]);
734  /// assert_eq!(left.factor_into_iter().next(), Some(Left(&"hello")));
735  ///
736  /// let right: Among<&[&str], Box<[u8]>, _> = Right(vec![0, 1]);
737  /// assert_eq!(right.factor_into_iter().collect::<Vec<_>>(), vec![Right(0), Right(1)]);
738  ///
739  /// ```
740  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
741  // #[doc(alias = "transpose")]
742  pub fn factor_into_iter(self) -> IterAmong<L::IntoIter, M::IntoIter, R::IntoIter>
743  where
744    L: IntoIterator,
745    M: IntoIterator,
746    R: IntoIterator,
747  {
748    IterAmong::new(map_among!(self, inner => inner.into_iter()))
749  }
750
751  /// Borrows an `Among` of `Iterator`s to be an `Iterator` of `Among`s
752  ///
753  /// Unlike [`iter`][Among::iter], this does not require the
754  /// `Left`, `Middle` and `Right` iterators to have the same item type.
755  ///
756  /// ```
757  /// use among::*;
758  /// let left: Among<_, Box<[u8]>, Vec<u8>> = Left(["hello"]);
759  /// assert_eq!(left.factor_iter().next(), Some(Left(&"hello")));
760  ///
761  /// let right: Among<[&str; 2], Box<[u8]>, _> = Right(vec![0, 1]);
762  /// assert_eq!(right.factor_iter().collect::<Vec<_>>(), vec![Right(&0), Right(&1)]);
763  ///
764  /// ```
765  pub fn factor_iter(
766    &self,
767  ) -> IterAmong<
768    <&L as IntoIterator>::IntoIter,
769    <&M as IntoIterator>::IntoIter,
770    <&R as IntoIterator>::IntoIter,
771  >
772  where
773    for<'a> &'a L: IntoIterator,
774    for<'a> &'a M: IntoIterator,
775    for<'a> &'a R: IntoIterator,
776  {
777    IterAmong::new(map_among!(self, inner => inner.into_iter()))
778  }
779
780  /// Mutably borrows an `Among` of `Iterator`s to be an `Iterator` of `Among`s
781  ///
782  /// Unlike [`iter_mut`][Among::iter_mut], this does not require the
783  /// `Left`, `Middle` and `Right` iterators to have the same item type.
784  ///
785  /// ```
786  /// use among::*;
787  /// let mut left: Among<_, Box<[u8]>, Vec<u8>> = Left(["hello"]);
788  /// left.factor_iter_mut().for_each(|x| *x.unwrap_left() = "goodbye");
789  /// assert_eq!(left, Left(["goodbye"]));
790  ///
791  /// let mut right: Among<[&str; 2], Box<[u8]>, _> = Right(vec![0, 1, 2]);
792  /// right.factor_iter_mut().for_each(|x| if let Right(r) = x { *r = -*r; });
793  /// assert_eq!(right, Right(vec![0, -1, -2]));
794  ///
795  /// ```
796  pub fn factor_iter_mut(
797    &mut self,
798  ) -> IterAmong<
799    <&mut L as IntoIterator>::IntoIter,
800    <&mut M as IntoIterator>::IntoIter,
801    <&mut R as IntoIterator>::IntoIter,
802  >
803  where
804    for<'a> &'a mut L: IntoIterator,
805    for<'a> &'a mut M: IntoIterator,
806    for<'a> &'a mut R: IntoIterator,
807  {
808    IterAmong::new(map_among!(self, inner => inner.into_iter()))
809  }
810
811  /// Return left value or given value
812  ///
813  /// Arguments passed to `left_or` are eagerly evaluated; if you are passing
814  /// the result of a function call, it is recommended to use
815  /// [`left_or_else`][Self::left_or_else], which is lazily evaluated.
816  ///
817  /// ## Examples
818  ///
819  /// ```
820  /// # use among::*;
821  /// let left: Among<&str, &str, &str> = Left("left");
822  /// assert_eq!(left.left_or("foo"), "left");
823  ///
824  /// let right: Among<&str, &str, &str> = Right("right");
825  /// assert_eq!(right.left_or("left"), "left");
826  ///
827  /// let middle: Among<&str, &str, &str> = Middle("middle");
828  /// assert_eq!(middle.left_or("left"), "left");
829  /// ```
830  pub fn left_or(self, other: L) -> L {
831    match self {
832      Among::Left(l) => l,
833      Among::Right(_) => other,
834      Among::Middle(_) => other,
835    }
836  }
837
838  /// Return left or a default
839  ///
840  /// ## Examples
841  ///
842  /// ```
843  /// # use among::*;
844  /// let left: Among<String, i32, u32> = Left("left".to_string());
845  /// assert_eq!(left.left_or_default(), "left");
846  ///
847  /// let right: Among<String, i32, u32> = Right(42);
848  /// assert_eq!(right.left_or_default(), String::default());
849  ///
850  /// let middle: Among<String, i32, u32> = Middle(-42);
851  /// assert_eq!(middle.left_or_default(), String::default());
852  /// ```
853  pub fn left_or_default(self) -> L
854  where
855    L: Default,
856  {
857    match self {
858      Among::Left(l) => l,
859      Among::Right(_) => L::default(),
860      Among::Middle(_) => L::default(),
861    }
862  }
863
864  /// Returns left value or computes it from a closure
865  ///
866  /// ## Examples
867  ///
868  /// ```
869  /// # use among::*;
870  /// let left: Among<String, i32, u32> = Left("3".to_string());
871  /// assert_eq!(left.left_or_else(|_| unreachable!(), |_| unreachable!()), "3");
872  ///
873  /// let right: Among<String, i32, u32> = Right(3);
874  /// assert_eq!(right.left_or_else(|x| x.to_string(), |x| x.to_string()), "3");
875  ///
876  /// let middle: Among<String, i32, u32> = Middle(3);
877  /// assert_eq!(middle.left_or_else(|x| x.to_string(), |x| x.to_string()), "3");
878  /// ```
879  pub fn left_or_else<F, G>(self, f: F, g: G) -> L
880  where
881    F: FnOnce(R) -> L,
882    G: FnOnce(M) -> L,
883  {
884    match self {
885      Among::Left(l) => l,
886      Among::Right(r) => f(r),
887      Among::Middle(m) => g(m),
888    }
889  }
890
891  /// Return middle value or given value
892  ///
893  /// Arguments passed to `middle_or` are eagerly evaluated; if you are passing
894  /// the result of a function call, it is recommended to use
895  /// [`middle_or_else`][Self::middle_or_else], which is lazily evaluated.
896  ///
897  /// ## Examples
898  ///
899  /// ```
900  /// # use among::*;
901  /// let right: Among<&str, &str, &str> = Right("right");
902  /// assert_eq!(right.middle_or("middle"), "middle");
903  ///
904  /// let left: Among<&str, &str, &str> = Left("left");
905  /// assert_eq!(left.middle_or("middle"), "middle");
906  ///
907  /// let middle: Among<&str, &str, &str> = Middle("middle");
908  /// assert_eq!(middle.middle_or("foo"), "middle");
909  /// ```
910  pub fn middle_or(self, other: M) -> M {
911    match self {
912      Among::Middle(m) => m,
913      _ => other,
914    }
915  }
916
917  /// Return middle or a default
918  ///
919  /// ## Examples
920  ///
921  /// ```
922  /// # use among::*;
923  /// let left: Among<String, i32, u32> = Left("left".to_string());
924  /// assert_eq!(left.middle_or_default(), i32::default());
925  ///
926  /// let right: Among<String, i32, u32> = Right(42);
927  /// assert_eq!(right.middle_or_default(), i32::default());
928  ///
929  /// let middle: Among<String, i32, u32> = Middle(-42);
930  /// assert_eq!(middle.middle_or_default(), -42);
931  /// ```
932  pub fn middle_or_default(self) -> M
933  where
934    M: Default,
935  {
936    match self {
937      Among::Middle(m) => m,
938      _ => M::default(),
939    }
940  }
941
942  /// Returns middle value or computes it from a closure
943  ///
944  /// ## Examples
945  ///
946  /// ```
947  /// # use among::*;
948  /// let left: Among<String, i32, String> = Left("3".to_string());
949  /// assert_eq!(left.middle_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
950  ///
951  /// let right: Among<String, i32, String> = Right("3".to_string());
952  /// assert_eq!(right.middle_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
953  ///
954  /// let middle: Among<String, i32, String> = Middle(-3);
955  /// assert_eq!(middle.middle_or_else(|_| unreachable!(), |_| unreachable!()), -3);
956  /// ```
957  pub fn middle_or_else<F, G>(self, f: F, g: G) -> M
958  where
959    F: FnOnce(L) -> M,
960    G: FnOnce(R) -> M,
961  {
962    match self {
963      Among::Left(l) => f(l),
964      Among::Middle(m) => m,
965      Among::Right(r) => g(r),
966    }
967  }
968
969  /// Return right value or given value
970  ///
971  /// Arguments passed to `right_or` are eagerly evaluated; if you are passing
972  /// the result of a function call, it is recommended to use
973  /// [`right_or_else`][Self::right_or_else], which is lazily evaluated.
974  ///
975  /// ## Examples
976  ///
977  /// ```
978  /// # use among::*;
979  /// let right: Among<&str, &str, &str> = Right("right");
980  /// assert_eq!(right.right_or("foo"), "right");
981  ///
982  /// let left: Among<&str, &str, &str> = Left("left");
983  /// assert_eq!(left.right_or("right"), "right");
984  ///
985  /// let middle: Among<&str, &str, &str> = Middle("middle");
986  /// assert_eq!(middle.right_or("right"), "right");
987  /// ```
988  pub fn right_or(self, other: R) -> R {
989    match self {
990      Among::Left(_) => other,
991      Among::Middle(_) => other,
992      Among::Right(r) => r,
993    }
994  }
995
996  /// Return right or a default
997  ///
998  /// ## Examples
999  ///
1000  /// ```
1001  /// # use among::*;
1002  /// let left: Among<String, i32, u32> = Left("left".to_string());
1003  /// assert_eq!(left.right_or_default(), u32::default());
1004  ///
1005  /// let right: Among<String, i32, u32> = Right(42);
1006  /// assert_eq!(right.right_or_default(), 42);
1007  ///
1008  /// let middle: Among<String, i32, u32> = Middle(-42);
1009  /// assert_eq!(middle.right_or_default(), u32::default());
1010  /// ```
1011  pub fn right_or_default(self) -> R
1012  where
1013    R: Default,
1014  {
1015    match self {
1016      Among::Left(_) => R::default(),
1017      Among::Middle(_) => R::default(),
1018      Among::Right(r) => r,
1019    }
1020  }
1021
1022  /// Returns right value or computes it from a closure
1023  ///
1024  /// ## Examples
1025  ///
1026  /// ```
1027  /// # use among::*;
1028  /// let left: Among<String, &str, u32> = Left("3".to_string());
1029  /// assert_eq!(left.right_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
1030  ///
1031  /// let right: Among<String, &str, u32> = Right(3);
1032  /// assert_eq!(right.right_or_else(|_| unreachable!(), |_| unreachable!()), 3);
1033  ///
1034  /// let middle: Among<String, &str, u32> = Middle("3");
1035  /// assert_eq!(middle.right_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
1036  /// ```
1037  pub fn right_or_else<F, G>(self, f: F, g: G) -> R
1038  where
1039    F: FnOnce(L) -> R,
1040    G: FnOnce(M) -> R,
1041  {
1042    match self {
1043      Among::Left(l) => f(l),
1044      Among::Middle(m) => g(m),
1045      Among::Right(r) => r,
1046    }
1047  }
1048
1049  /// Returns the left value
1050  ///
1051  /// ## Examples
1052  ///
1053  /// ```
1054  /// # use among::*;
1055  /// let left: Among<_, (), ()> = Left(3);
1056  /// assert_eq!(left.unwrap_left(), 3);
1057  /// ```
1058  ///
1059  /// # Panics
1060  ///
1061  /// When `Among` is a `Right` value
1062  ///
1063  /// ```should_panic
1064  /// # use among::*;
1065  /// let right: Among<(), (), _> = Right(3);
1066  /// right.unwrap_left();
1067  /// ```
1068  ///
1069  /// ```should_panic
1070  /// # use among::*;
1071  /// let middle: Among<(), _, ()> = Middle(3);
1072  /// middle.unwrap_left();
1073  /// ```
1074  pub fn unwrap_left(self) -> L
1075  where
1076    M: core::fmt::Debug,
1077    R: core::fmt::Debug,
1078  {
1079    match self {
1080      Among::Left(l) => l,
1081      Among::Middle(m) => {
1082        panic!(
1083          "called `Among::unwrap_middle()` on a `Middle` value: {:?}",
1084          m
1085        )
1086      }
1087      Among::Right(r) => {
1088        panic!("called `Among::unwrap_left()` on a `Right` value: {:?}", r)
1089      }
1090    }
1091  }
1092
1093  /// Returns the middle value
1094  ///
1095  /// ## Examples
1096  ///
1097  /// ```
1098  /// # use among::*;
1099  /// let middle: Among<(), _, ()> = Middle(3);
1100  /// assert_eq!(middle.unwrap_middle(), 3);
1101  /// ```
1102  ///
1103  /// # Panics
1104  ///
1105  /// When `Among` is a `Right` value
1106  ///
1107  /// ```should_panic
1108  /// # use among::*;
1109  /// let right: Among<(), (), _> = Right(3);
1110  /// right.unwrap_middle();
1111  /// ```
1112  ///
1113  /// ```should_panic
1114  /// # use among::*;
1115  /// let left: Among<_, (), ()> = Left(3);
1116  /// left.unwrap_middle();
1117  /// ```
1118  pub fn unwrap_middle(self) -> M
1119  where
1120    L: core::fmt::Debug,
1121    R: core::fmt::Debug,
1122  {
1123    match self {
1124      Among::Left(l) => {
1125        panic!("called `Among::unwrap_middle()` on a `Left` value: {:?}", l)
1126      }
1127      Among::Middle(m) => m,
1128      Among::Right(r) => {
1129        panic!(
1130          "called `Among::unwrap_middle()` on a `Right` value: {:?}",
1131          r
1132        )
1133      }
1134    }
1135  }
1136
1137  /// Returns the right value
1138  ///
1139  /// ## Examples
1140  ///
1141  /// ```
1142  /// # use among::*;
1143  /// let right: Among<(), (), _> = Right(3);
1144  /// assert_eq!(right.unwrap_right(), 3);
1145  /// ```
1146  ///
1147  /// # Panics
1148  ///
1149  /// When `Among` is a `Left` value
1150  ///
1151  /// ```should_panic
1152  /// # use among::*;
1153  /// let left: Among<_, (), ()> = Left(3);
1154  /// left.unwrap_right();
1155  /// ```
1156  ///
1157  /// ```should_panic
1158  /// # use among::*;
1159  /// let middle: Among<(), _, ()> = Middle(3);
1160  /// middle.unwrap_right();
1161  /// ```
1162  pub fn unwrap_right(self) -> R
1163  where
1164    L: core::fmt::Debug,
1165    M: core::fmt::Debug,
1166  {
1167    match self {
1168      Among::Right(r) => r,
1169      Among::Middle(m) => panic!(
1170        "called `Among::unwrap_middle()` on a `Middle` value: {:?}",
1171        m
1172      ),
1173      Among::Left(l) => panic!("called `Among::unwrap_right()` on a `Left` value: {:?}", l),
1174    }
1175  }
1176
1177  /// Returns the left value
1178  ///
1179  /// ## Examples
1180  ///
1181  /// ```
1182  /// # use among::*;
1183  /// let left: Among<_, (), ()> = Left(3);
1184  /// assert_eq!(left.expect_left("value was not Left"), 3);
1185  /// ```
1186  ///
1187  /// # Panics
1188  ///
1189  /// When `Among` is a `Right` value
1190  ///
1191  /// ```should_panic
1192  /// # use among::*;
1193  /// let right: Among<(), (), _> = Right(3);
1194  /// right.expect_left("value was not Left");
1195  /// ```
1196  ///
1197  /// When `Among` is a `Middle` value
1198  ///
1199  /// ```should_panic
1200  /// # use among::*;
1201  /// let middle: Among<(), _, ()> = Middle(3);
1202  /// middle.expect_left("value was not Left");
1203  /// ```
1204  pub fn expect_left(self, msg: &str) -> L
1205  where
1206    M: core::fmt::Debug,
1207    R: core::fmt::Debug,
1208  {
1209    match self {
1210      Among::Left(l) => l,
1211      Among::Middle(m) => panic!("{}: {:?}", msg, m),
1212      Among::Right(r) => panic!("{}: {:?}", msg, r),
1213    }
1214  }
1215
1216  /// Returns the left value
1217  ///
1218  /// ## Examples
1219  ///
1220  /// ```
1221  /// # use among::*;
1222  /// let middle: Among<(), _, ()> = Middle(3);
1223  /// assert_eq!(middle.expect_middle("value was Middle"), 3);
1224  /// ```
1225  ///
1226  /// # Panics
1227  ///
1228  /// When `Among` is a `Right` value
1229  ///
1230  /// ```should_panic
1231  /// # use among::*;
1232  /// let right: Among<(), (), _> = Right(3);
1233  /// right.expect_middle("value was not Middle");
1234  /// ```
1235  ///
1236  /// When `Among` is a `Left` value
1237  ///
1238  /// ```should_panic
1239  /// # use among::*;
1240  /// let left: Among<_, (), ()> = Left(3);
1241  /// left.expect_middle("value was not Middle");
1242  /// ```
1243  pub fn expect_middle(self, msg: &str) -> M
1244  where
1245    L: core::fmt::Debug,
1246    R: core::fmt::Debug,
1247  {
1248    match self {
1249      Among::Left(l) => panic!("{}: {:?}", msg, l),
1250      Among::Middle(m) => m,
1251      Among::Right(r) => panic!("{}: {:?}", msg, r),
1252    }
1253  }
1254
1255  /// Returns the right value
1256  ///
1257  /// ## Examples
1258  ///
1259  /// ```
1260  /// # use among::*;
1261  /// let right: Among<(), (), _> = Right(3);
1262  /// assert_eq!(right.expect_right("value was not Right"), 3);
1263  /// ```
1264  ///
1265  /// # Panics
1266  ///
1267  /// When `Among` is a `Left` value
1268  ///
1269  /// ```should_panic
1270  /// # use among::*;
1271  /// let left: Among<_, (), ()> = Left(3);
1272  /// left.expect_right("value was not Right");
1273  /// ```
1274  ///
1275  /// When `Among` is a `Middle` value
1276  ///
1277  /// ```should_panic
1278  /// # use among::*;
1279  /// let middle: Among<(), _, ()> = Middle(3);
1280  /// middle.expect_right("value was not Right");
1281  /// ```
1282  pub fn expect_right(self, msg: &str) -> R
1283  where
1284    L: core::fmt::Debug,
1285    M: core::fmt::Debug,
1286  {
1287    match self {
1288      Among::Right(r) => r,
1289      Among::Middle(m) => panic!("{}: {:?}", msg, m),
1290      Among::Left(l) => panic!("{}: {:?}", msg, l),
1291    }
1292  }
1293
1294  /// Convert the contained value into `T`
1295  ///
1296  /// ## Examples
1297  ///
1298  /// ```
1299  /// # use among::*;
1300  /// // Both u16 and u32 can be converted to u64.
1301  /// let left: Among<u16, u32, u64> = Left(3u16);
1302  /// assert_eq!(left.among_into::<u64>(), 3u64);
1303  /// let middle: Among<u16, u32, u64> = Middle(3u32);
1304  /// assert_eq!(middle.among_into::<u64>(), 3u64);
1305  /// let right: Among<u16, u32, u64> = Right(7u64);
1306  /// assert_eq!(right.among_into::<u64>(), 7u64);
1307  /// ```
1308  pub fn among_into<T>(self) -> T
1309  where
1310    L: Into<T>,
1311    M: Into<T>,
1312    R: Into<T>,
1313  {
1314    match self {
1315      Among::Left(l) => l.into(),
1316      Among::Middle(m) => m.into(),
1317      Among::Right(r) => r.into(),
1318    }
1319  }
1320}
1321
1322impl<L, M, R> Among<Option<L>, Option<M>, Option<R>> {
1323  /// Factors out `None` from an `Among` of [`Option`].
1324  ///
1325  /// ```
1326  /// use among::*;
1327  /// let left: Among<_, Option<u32>, Option<String>> = Left(Some(vec![0]));
1328  /// assert_eq!(left.factor_none(), Some(Left(vec![0])));
1329  ///
1330  /// let right: Among<Option<Vec<u8>>, Option<u32>, _> = Right(Some(String::new()));
1331  /// assert_eq!(right.factor_none(), Some(Right(String::new())));
1332  ///
1333  /// let middle: Among<Option<Vec<u8>>, _, Option<String>> = Middle(Some(123));
1334  /// assert_eq!(middle.factor_none(), Some(Middle(123)));
1335  /// ```
1336  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1337  // #[doc(alias = "transpose")]
1338  pub fn factor_none(self) -> Option<Among<L, M, R>> {
1339    match self {
1340      Left(l) => l.map(Among::Left),
1341      Middle(m) => m.map(Among::Middle),
1342      Right(r) => r.map(Among::Right),
1343    }
1344  }
1345}
1346
1347impl<L, M, R, E> Among<Result<L, E>, Result<M, E>, Result<R, E>> {
1348  /// Factors out a homogenous type from an `Among` of [`Result`].
1349  ///
1350  /// Here, the homogeneous type is the `Err` type of the [`Result`].
1351  ///
1352  /// ```
1353  /// use among::*;
1354  /// let left: Among<_, Result<u32, u32>, Result<String, u32>> = Left(Ok(vec![0]));
1355  /// assert_eq!(left.factor_err(), Ok(Left(vec![0])));
1356  ///
1357  /// let right: Among<Result<Vec<u8>, u32>, Result<u32, u32>, _> = Right(Ok(String::new()));
1358  /// assert_eq!(right.factor_err(), Ok(Right(String::new())));
1359  ///
1360  /// let middle: Among<Result<Vec<u8>, u32>, _, Result<String, u32>> = Middle(Ok(123));
1361  /// assert_eq!(middle.factor_err(), Ok(Middle(123)));
1362  /// ```
1363  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1364  // #[doc(alias = "transpose")]
1365  pub fn factor_err(self) -> Result<Among<L, M, R>, E> {
1366    match self {
1367      Left(l) => l.map(Among::Left),
1368      Middle(m) => m.map(Among::Middle),
1369      Right(r) => r.map(Among::Right),
1370    }
1371  }
1372}
1373
1374impl<T, L, M, R> Among<Result<T, L>, Result<T, M>, Result<T, R>> {
1375  /// Factors out a homogenous type from an `Among` of [`Result`].
1376  ///
1377  /// Here, the homogeneous type is the `Ok` type of the [`Result`].
1378  ///
1379  /// ```
1380  /// use among::*;
1381  /// let left: Among<_, Result<u32, i64>, Result<u32, String>> = Left(Err(vec![0]));
1382  /// assert_eq!(left.factor_ok(), Err(Left(vec![0])));
1383  ///
1384  /// let right: Among<Result<u32, Vec<u8>>, Result<u32, i64>, _> = Right(Err(String::new()));
1385  /// assert_eq!(right.factor_ok(), Err(Right(String::new())));
1386  ///
1387  /// let middle: Among<Result<u32, Vec<u8>>, _, Result<u32, String>> = Middle(Err(-123));
1388  /// assert_eq!(middle.factor_ok(), Err(Middle(-123)));
1389  /// ```
1390  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1391  // #[doc(alias = "transpose")]
1392  pub fn factor_ok(self) -> Result<T, Among<L, M, R>> {
1393    match self {
1394      Left(l) => l.map_err(Among::Left),
1395      Middle(m) => m.map_err(Among::Middle),
1396      Right(r) => r.map_err(Among::Right),
1397    }
1398  }
1399}
1400
1401impl<T, L, M, R> Among<(T, L), (T, M), (T, R)> {
1402  /// Factor out a homogeneous type from an among of pairs.
1403  ///
1404  /// Here, the homogeneous type is the first element of the pairs.
1405  ///
1406  /// ```
1407  /// use among::*;
1408  /// let left: Among<_, (u32, i64), (u32, String)> = Left((123, vec![0]));
1409  /// assert_eq!(left.factor_first().0, 123);
1410  ///
1411  /// let right: Among<(u32, Vec<u8>), (u32, i64), _> = Right((123, String::new()));
1412  /// assert_eq!(right.factor_first().0, 123);
1413  ///
1414  /// let middle: Among<(u32, Vec<u8>), _, (u32, String)> = Middle((123, vec![0]));
1415  /// assert_eq!(middle.factor_first().0, 123);
1416  /// ```
1417  pub fn factor_first(self) -> (T, Among<L, M, R>) {
1418    match self {
1419      Left((t, l)) => (t, Left(l)),
1420      Middle((t, m)) => (t, Middle(m)),
1421      Right((t, r)) => (t, Right(r)),
1422    }
1423  }
1424}
1425
1426impl<T, L, M, R> Among<(L, T), (M, T), (R, T)> {
1427  /// Factor out a homogeneous type from an among of pairs.
1428  ///
1429  /// Here, the homogeneous type is the second element of the pairs.
1430  ///
1431  /// ```
1432  /// use among::*;
1433  /// let left: Among<_, (i64, u32), (String, u32)> = Left((vec![0], 123));
1434  /// assert_eq!(left.factor_second().1, 123);
1435  ///
1436  /// let right: Among<(Vec<u8>, u32), (i64, u32), _> = Right((String::new(), 123));
1437  /// assert_eq!(right.factor_second().1, 123);
1438  ///
1439  /// let middle: Among<(Vec<u8>, u32), _, (String, u32)> = Middle((-1, 123));
1440  /// assert_eq!(middle.factor_second().1, 123);
1441  /// ```
1442  pub fn factor_second(self) -> (Among<L, M, R>, T) {
1443    match self {
1444      Left((l, t)) => (Left(l), t),
1445      Middle((m, t)) => (Middle(m), t),
1446      Right((r, t)) => (Right(r), t),
1447    }
1448  }
1449}
1450
1451impl<T> Among<T, T, T> {
1452  /// Extract the value of an among over two equivalent types.
1453  ///
1454  /// ```
1455  /// use among::*;
1456  ///
1457  /// let left: Among<_, _, u32> = Left(123);
1458  /// assert_eq!(left.into_inner(), 123);
1459  ///
1460  /// let right: Among<u32, _, _> = Right(123);
1461  /// assert_eq!(right.into_inner(), 123);
1462  ///
1463  /// let middle: Among<_, u32, _> = Middle(123);
1464  /// assert_eq!(middle.into_inner(), 123);
1465  /// ```
1466  pub fn into_inner(self) -> T {
1467    for_all!(self, inner => inner)
1468  }
1469
1470  /// Map `f` over the contained value and return the result in the
1471  /// corresponding variant.
1472  ///
1473  /// ```
1474  /// use among::*;
1475  ///
1476  /// let value: Among<_, _, i32> = Right(42);
1477  ///
1478  /// let other = value.map(|x| x * 2);
1479  /// assert_eq!(other, Right(84));
1480  /// ```
1481  pub fn map<F, M>(self, f: F) -> Among<M, M, M>
1482  where
1483    F: FnOnce(T) -> M,
1484  {
1485    match self {
1486      Left(l) => Left(f(l)),
1487      Middle(m) => Middle(f(m)),
1488      Right(r) => Right(f(r)),
1489    }
1490  }
1491}
1492
1493impl<L, M, R> Among<&L, &M, &R> {
1494  /// Maps an `Among<&L, &M, &R>` to an `Among<L, M, R>` by cloning the contents of
1495  /// among branch.
1496  pub fn cloned(self) -> Among<L, M, R>
1497  where
1498    L: Clone,
1499    M: Clone,
1500    R: Clone,
1501  {
1502    match self {
1503      Self::Left(l) => Among::Left(l.clone()),
1504      Self::Middle(m) => Among::Middle(m.clone()),
1505      Self::Right(r) => Among::Right(r.clone()),
1506    }
1507  }
1508
1509  /// Maps an `Among<&L, &M, &R>` to an `Among<L, M, R>` by copying the contents of
1510  /// among branch.
1511  pub fn copied(self) -> Among<L, M, R>
1512  where
1513    L: Copy,
1514    M: Copy,
1515    R: Copy,
1516  {
1517    match self {
1518      Self::Left(l) => Among::Left(*l),
1519      Self::Middle(m) => Among::Middle(*m),
1520      Self::Right(r) => Among::Right(*r),
1521    }
1522  }
1523}
1524
1525impl<L, M, R> Among<&mut L, &mut M, &mut R> {
1526  /// Maps an `Among<&mut L, &mut M, &mut R>` to an `Among<L, M, R>` by cloning the contents of
1527  /// among branch.
1528  pub fn cloned(self) -> Among<L, M, R>
1529  where
1530    L: Clone,
1531    M: Clone,
1532    R: Clone,
1533  {
1534    match self {
1535      Self::Left(l) => Among::Left(l.clone()),
1536      Self::Middle(m) => Among::Middle(m.clone()),
1537      Self::Right(r) => Among::Right(r.clone()),
1538    }
1539  }
1540
1541  /// Maps an `Among<&mut L, &mut M, &mut R>` to an `Among<L, M, R>` by copying the contents of
1542  /// among branch.
1543  pub fn copied(self) -> Among<L, M, R>
1544  where
1545    L: Copy,
1546    M: Copy,
1547    R: Copy,
1548  {
1549    match self {
1550      Self::Left(l) => Among::Left(*l),
1551      Self::Middle(m) => Among::Middle(*m),
1552      Self::Right(r) => Among::Right(*r),
1553    }
1554  }
1555}
1556
1557/// `Among<L, M, R>` is a future if both `L`, `M` and `R` are futures.
1558impl<L, M, R> Future for Among<L, M, R>
1559where
1560  L: Future,
1561  M: Future,
1562  R: Future,
1563{
1564  type Output = Among<L::Output, M::Output, R::Output>;
1565
1566  fn poll(
1567    self: Pin<&mut Self>,
1568    cx: &mut core::task::Context<'_>,
1569  ) -> core::task::Poll<Self::Output> {
1570    match self.as_pin_mut() {
1571      Left(l) => l.poll(cx).map(Left),
1572      Middle(m) => m.poll(cx).map(Middle),
1573      Right(r) => r.poll(cx).map(Right),
1574    }
1575  }
1576}
1577
1578#[cfg(any(test, feature = "std"))]
1579/// `Among<L, M, R>` implements `Read` if both `L` and `R` do.
1580///
1581/// Requires crate feature `"std"`
1582impl<L, M, R> Read for Among<L, M, R>
1583where
1584  L: Read,
1585  M: Read,
1586  R: Read,
1587{
1588  fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1589    for_all!(*self, ref mut inner => inner.read(buf))
1590  }
1591
1592  fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
1593    for_all!(*self, ref mut inner => inner.read_exact(buf))
1594  }
1595
1596  fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
1597    for_all!(*self, ref mut inner => inner.read_to_end(buf))
1598  }
1599
1600  fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
1601    for_all!(*self, ref mut inner => inner.read_to_string(buf))
1602  }
1603}
1604
1605#[cfg(any(test, feature = "std"))]
1606/// `Among<L, M, R>` implements `Seek` if both `L` and `R` do.
1607///
1608/// Requires crate feature `"std"`
1609impl<L, M, R> Seek for Among<L, M, R>
1610where
1611  L: Seek,
1612  M: Seek,
1613  R: Seek,
1614{
1615  fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1616    for_all!(*self, ref mut inner => inner.seek(pos))
1617  }
1618}
1619
1620#[cfg(any(test, feature = "std"))]
1621/// Requires crate feature `"std"`
1622impl<L, M, R> BufRead for Among<L, M, R>
1623where
1624  L: BufRead,
1625  M: BufRead,
1626  R: BufRead,
1627{
1628  fn fill_buf(&mut self) -> io::Result<&[u8]> {
1629    for_all!(*self, ref mut inner => inner.fill_buf())
1630  }
1631
1632  fn consume(&mut self, amt: usize) {
1633    for_all!(*self, ref mut inner => inner.consume(amt))
1634  }
1635
1636  fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
1637    for_all!(*self, ref mut inner => inner.read_until(byte, buf))
1638  }
1639
1640  fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
1641    for_all!(*self, ref mut inner => inner.read_line(buf))
1642  }
1643}
1644
1645#[cfg(any(test, feature = "std"))]
1646/// `Among<L, M, R>` implements `Write` if all of `L`, `M` and `R` do.
1647///
1648/// Requires crate feature `"std"`
1649impl<L, M, R> Write for Among<L, M, R>
1650where
1651  L: Write,
1652  M: Write,
1653  R: Write,
1654{
1655  fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1656    for_all!(*self, ref mut inner => inner.write(buf))
1657  }
1658
1659  fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1660    for_all!(*self, ref mut inner => inner.write_all(buf))
1661  }
1662
1663  fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
1664    for_all!(*self, ref mut inner => inner.write_fmt(fmt))
1665  }
1666
1667  fn flush(&mut self) -> io::Result<()> {
1668    for_all!(*self, ref mut inner => inner.flush())
1669  }
1670}
1671
1672impl<L, M, R, Target> AsRef<Target> for Among<L, M, R>
1673where
1674  L: AsRef<Target>,
1675  M: AsRef<Target>,
1676  R: AsRef<Target>,
1677{
1678  fn as_ref(&self) -> &Target {
1679    for_all!(*self, ref inner => inner.as_ref())
1680  }
1681}
1682
1683macro_rules! impl_specific_ref_and_mut {
1684    ($t:ty, $($attr:meta),* ) => {
1685        $(#[$attr])*
1686        impl<L, M, R> AsRef<$t> for Among<L, M, R>
1687            where L: AsRef<$t>, M: AsRef<$t>, R: AsRef<$t>,
1688        {
1689            fn as_ref(&self) -> &$t {
1690                for_all!(*self, ref inner => inner.as_ref())
1691            }
1692        }
1693
1694        $(#[$attr])*
1695        impl<L, M, R> AsMut<$t> for Among<L, M, R>
1696            where L: AsMut<$t>, M: AsMut<$t>, R: AsMut<$t>,
1697        {
1698            fn as_mut(&mut self) -> &mut $t {
1699                for_all!(*self, ref mut inner => inner.as_mut())
1700            }
1701        }
1702    };
1703}
1704
1705impl_specific_ref_and_mut!(str,);
1706impl_specific_ref_and_mut!(
1707  ::std::path::Path,
1708  cfg(feature = "std"),
1709  doc = "Requires crate feature `std`."
1710);
1711impl_specific_ref_and_mut!(
1712  ::std::ffi::OsStr,
1713  cfg(feature = "std"),
1714  doc = "Requires crate feature `std`."
1715);
1716impl_specific_ref_and_mut!(
1717  ::std::ffi::CStr,
1718  cfg(feature = "std"),
1719  doc = "Requires crate feature `std`."
1720);
1721
1722impl<L, M, R, Target> AsRef<[Target]> for Among<L, M, R>
1723where
1724  L: AsRef<[Target]>,
1725  M: AsRef<[Target]>,
1726  R: AsRef<[Target]>,
1727{
1728  fn as_ref(&self) -> &[Target] {
1729    for_all!(*self, ref inner => inner.as_ref())
1730  }
1731}
1732
1733impl<L, M, R, Target> AsMut<Target> for Among<L, M, R>
1734where
1735  L: AsMut<Target>,
1736  M: AsMut<Target>,
1737  R: AsMut<Target>,
1738{
1739  fn as_mut(&mut self) -> &mut Target {
1740    for_all!(*self, ref mut inner => inner.as_mut())
1741  }
1742}
1743
1744impl<L, M, R, Target> AsMut<[Target]> for Among<L, M, R>
1745where
1746  L: AsMut<[Target]>,
1747  M: AsMut<[Target]>,
1748  R: AsMut<[Target]>,
1749{
1750  fn as_mut(&mut self) -> &mut [Target] {
1751    for_all!(*self, ref mut inner => inner.as_mut())
1752  }
1753}
1754
1755impl<L, M, R> Deref for Among<L, M, R>
1756where
1757  L: Deref,
1758  M: Deref<Target = L::Target>,
1759  R: Deref<Target = L::Target>,
1760{
1761  type Target = L::Target;
1762
1763  fn deref(&self) -> &Self::Target {
1764    for_all!(*self, ref inner => &**inner)
1765  }
1766}
1767
1768impl<L, M, R> DerefMut for Among<L, M, R>
1769where
1770  L: DerefMut,
1771  M: DerefMut<Target = L::Target>,
1772  R: DerefMut<Target = L::Target>,
1773{
1774  fn deref_mut(&mut self) -> &mut Self::Target {
1775    for_all!(*self, ref mut inner => &mut *inner)
1776  }
1777}
1778
1779#[cfg(any(test, feature = "std"))]
1780/// `Among` implements `Error` if *all* of `L`, `M` and `R` implement it.
1781///
1782/// Requires crate feature `"std"`
1783impl<L, M, R> Error for Among<L, M, R>
1784where
1785  L: Error,
1786  M: Error,
1787  R: Error,
1788{
1789  fn source(&self) -> Option<&(dyn Error + 'static)> {
1790    for_all!(*self, ref inner => inner.source())
1791  }
1792
1793  #[allow(deprecated)]
1794  fn description(&self) -> &str {
1795    for_all!(*self, ref inner => inner.description())
1796  }
1797
1798  #[allow(deprecated)]
1799  fn cause(&self) -> Option<&dyn Error> {
1800    for_all!(*self, ref inner => inner.cause())
1801  }
1802}
1803
1804impl<L, M, R> fmt::Display for Among<L, M, R>
1805where
1806  L: fmt::Display,
1807  M: fmt::Display,
1808  R: fmt::Display,
1809{
1810  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1811    for_all!(*self, ref inner => inner.fmt(f))
1812  }
1813}
1814
1815#[test]
1816fn basic() {
1817  let mut e = Left(2);
1818  let m = Middle(2);
1819  let r = Right(2);
1820  assert_eq!(e, Left(2));
1821  e = r;
1822  assert_eq!(e, Right(2));
1823  assert_eq!(e.left(), None);
1824  assert_eq!(e.middle(), None);
1825  assert_eq!(e.right(), Some(2));
1826  assert_eq!(e.as_ref().right(), Some(&2));
1827  assert_eq!(e.as_mut().right(), Some(&mut 2));
1828  e = m;
1829  assert_eq!(e, Middle(2));
1830  assert_eq!(e.left(), None);
1831  assert_eq!(e.right(), None);
1832  assert_eq!(e.middle(), Some(2));
1833  assert_eq!(e.as_ref().middle(), Some(&2));
1834  assert_eq!(e.as_mut().middle(), Some(&mut 2));
1835}
1836
1837#[test]
1838fn deref() {
1839  use std::{borrow::Cow, string::String};
1840
1841  fn is_str(_: &str) {}
1842  let value: Among<String, Cow<'_, str>, &str> = Left(String::from("test"));
1843  is_str(&value);
1844}
1845
1846#[test]
1847fn iter() {
1848  let x = 3;
1849  let mut iter = match x {
1850    3 => Left(0..10),
1851    6 => Middle(11..17),
1852    _ => Right(17..),
1853  };
1854
1855  assert_eq!(iter.next(), Some(0));
1856  assert_eq!(iter.count(), 9);
1857}
1858
1859#[test]
1860fn seek() {
1861  use std::{io, vec};
1862
1863  let use_empty = 1;
1864  let mut mockdata = [0x00; 256];
1865  let mut mockvec = vec![];
1866  for (i, elem) in mockdata.iter_mut().enumerate() {
1867    mockvec.push(i as u8);
1868    *elem = i as u8;
1869  }
1870
1871  let mut reader = if use_empty == 0 {
1872    // Empty didn't impl Seek until Rust 1.51
1873    Left(io::Cursor::new([]))
1874  } else if use_empty == 1 {
1875    Right(io::Cursor::new(&mockdata[..]))
1876  } else {
1877    Middle(io::Cursor::new(&mockvec[..]))
1878  };
1879
1880  let mut buf = [0u8; 16];
1881  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1882  assert_eq!(buf, mockdata[..buf.len()]);
1883
1884  // the first read should advance the cursor and return the next 16 bytes thus the `ne`
1885  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1886  assert_ne!(buf, mockdata[..buf.len()]);
1887
1888  // if the seek operation fails it should read 16..31 instead of 0..15
1889  reader.seek(io::SeekFrom::Start(0)).unwrap();
1890  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1891  assert_eq!(buf, mockdata[..buf.len()]);
1892}
1893
1894#[test]
1895fn read_write() {
1896  use std::{io, vec};
1897
1898  let io = 1;
1899  let mockdata = [0xff; 256];
1900  let mut mockvec = io::Cursor::new(vec![]);
1901
1902  let mut reader = if io == 0 {
1903    Left(io::stdin())
1904  } else if io == 1 {
1905    Right(&mockdata[..])
1906  } else {
1907    Middle(&mut mockvec)
1908  };
1909
1910  let mut buf = [0u8; 16];
1911  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1912  assert_eq!(&buf, &mockdata[..buf.len()]);
1913
1914  let mut mockbuf = [0u8; 256];
1915  let mut writer = if io == 0 {
1916    Left(io::stdout())
1917  } else if io == 1 {
1918    Right(&mut mockbuf[..])
1919  } else {
1920    Middle(&mut mockvec)
1921  };
1922
1923  let buf = [1u8; 16];
1924  assert_eq!(writer.write(&buf).unwrap(), buf.len());
1925}
1926
1927/// A helper macro to check if AsRef and AsMut are implemented for a given type.
1928macro_rules! check_t {
1929  ($t:ty) => {{
1930    fn check_ref<T: AsRef<$t>>() {}
1931    fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>, T3: AsRef<$t>>() {
1932      check_ref::<Among<T1, T2, T3>>()
1933    }
1934    fn check_mut<T: AsMut<$t>>() {}
1935    fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>, T3: AsMut<$t>>() {
1936      check_mut::<Among<T1, T2, T3>>()
1937    }
1938  }};
1939}
1940
1941// This "unused" method is here to ensure that compilation doesn't fail on given types.
1942fn _unsized_ref_propagation() {
1943  check_t!(str);
1944
1945  fn check_array_ref<T: AsRef<[Item]>, Item>() {}
1946  fn check_array_mut<T: AsMut<[Item]>, Item>() {}
1947
1948  fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, T3: AsRef<[Item]>, Item>() {
1949    check_array_ref::<Among<T1, T2, T3>, _>()
1950  }
1951
1952  fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, T3: AsMut<[Item]>, Item>() {
1953    check_array_mut::<Among<T1, T2, T3>, _>()
1954  }
1955}
1956
1957// This "unused" method is here to ensure that compilation doesn't fail on given types.
1958#[cfg(feature = "std")]
1959fn _unsized_std_propagation() {
1960  check_t!(::std::path::Path);
1961  check_t!(::std::ffi::OsStr);
1962  check_t!(::std::ffi::CStr);
1963}