Skip to main content

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::{
33  convert::{AsMut, AsRef, TryInto},
34  fmt,
35  future::Future,
36  ops::{Deref, DerefMut},
37  pin::Pin,
38};
39
40#[cfg(any(test, feature = "std"))]
41use std::error::Error;
42#[cfg(any(test, feature = "std"))]
43use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
44
45pub use crate::Among::{Left, Middle, Right};
46
47/// The enum `Among` with variants `Left`, `Middle` and `Right` is a general purpose
48/// sum type with three cases.
49///
50/// The `Among` type is symmetric and treats its variants the same way, without
51/// preference.
52/// (For representing success or error, use the regular `Result` enum instead.)
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
55pub enum Among<L, M, R> {
56  /// A value of type `L`.
57  Left(L),
58  /// A value of type `M`.
59  Middle(M),
60  /// A value of type `R`.
61  Right(R),
62}
63
64/// Evaluate the provided expression for both [`Among::Left`] and [`Among::Right`].
65///
66/// This macro is useful in cases where both sides of [`Among`] can be interacted with
67/// in the same way even though the don't share the same type.
68///
69/// Syntax: `among::for_all!(` *expression* `,` *pattern* `=>` *expression* `)`
70///
71/// # Example
72///
73/// ```
74/// use among::Among;
75/// use std::borrow::Cow;
76///
77/// fn length(owned_or_borrowed: Among<String, Cow<'static, str>, &'static str>) -> usize {
78///     among::for_all!(owned_or_borrowed, s => s.len())
79/// }
80///
81/// fn main() {
82///     let borrowed = Among::Right("Hello world!");
83///     let owned = Among::Left("Hello world!".to_owned());
84///     let mixed = Among::Middle(Cow::Borrowed("Hello world!"));
85///
86///     assert_eq!(length(borrowed), 12);
87///     assert_eq!(length(mixed), 12);
88///     assert_eq!(length(owned), 12);
89/// }
90/// ```
91#[macro_export]
92macro_rules! for_all {
93  ($value:expr, $pattern:pat => $result:expr) => {
94    match $value {
95      $crate::Among::Middle($pattern) => $result,
96      $crate::Among::Left($pattern) => $result,
97      $crate::Among::Right($pattern) => $result,
98    }
99  };
100}
101
102macro_rules! map_among {
103  ($value:expr, $pattern:pat => $result:expr) => {
104    match $value {
105      Left($pattern) => Left($result),
106      Middle($pattern) => Middle($result),
107      Right($pattern) => Right($result),
108    }
109  };
110}
111
112mod iterator;
113pub use self::iterator::IterAmong;
114
115mod into_among;
116pub use self::into_among::IntoAmong;
117
118impl<L: Clone, M: Clone, R: Clone> Clone for Among<L, M, R> {
119  fn clone(&self) -> Self {
120    match self {
121      Left(inner) => Left(inner.clone()),
122      Middle(inner) => Middle(inner.clone()),
123      Right(inner) => Right(inner.clone()),
124    }
125  }
126
127  fn clone_from(&mut self, source: &Self) {
128    match (self, source) {
129      (Left(dest), Left(source)) => dest.clone_from(source),
130      (Middle(dest), Middle(source)) => dest.clone_from(source),
131      (Right(dest), Right(source)) => dest.clone_from(source),
132      (dest, source) => *dest = source.clone(),
133    }
134  }
135}
136
137impl<L, M, R> Among<L, M, R> {
138  /// Return true if the value is the `Left` variant.
139  ///
140  /// ```
141  /// use among::*;
142  ///
143  /// let values = [Left(1), Middle(b"the middle value"), Right("the right value")];
144  /// assert_eq!(values[0].is_left(), true);
145  /// assert_eq!(values[1].is_left(), false);
146  /// assert_eq!(values[2].is_left(), false);
147  /// ```
148  pub const fn is_left(&self) -> bool {
149    matches!(*self, Left(_))
150  }
151
152  /// Return true if the value is the `Right` variant.
153  ///
154  /// ```
155  /// use among::*;
156  ///
157  /// let values = [Left(1), Middle(b"the middle value"), Right("the right value")];
158  /// assert_eq!(values[0].is_right(), false);
159  /// assert_eq!(values[1].is_right(), false);
160  /// assert_eq!(values[2].is_right(), true);
161  /// ```
162  pub const fn is_right(&self) -> bool {
163    matches!(*self, Right(_))
164  }
165
166  /// Return true if the value is the `Middle` variant.
167  ///
168  /// ```
169  /// use among::*;
170  ///
171  /// let values = [Left(1), Middle(b"the middle value"), Right("the right value")];
172  /// assert_eq!(values[0].is_middle(), false);
173  /// assert_eq!(values[1].is_middle(), true);
174  /// assert_eq!(values[2].is_middle(), false);
175  /// ```
176  pub const fn is_middle(&self) -> bool {
177    matches!(*self, Middle(_))
178  }
179
180  /// Returns `true` if the value is a `Left` variant and the contained
181  /// value matches the predicate.
182  ///
183  /// ```
184  /// use among::*;
185  ///
186  /// let left: Among<u32, u32, u32> = Left(2);
187  /// assert!(left.is_left_and(|x| *x == 2));
188  /// assert!(!left.is_left_and(|x| *x == 3));
189  ///
190  /// let middle: Among<u32, u32, u32> = Middle(2);
191  /// assert!(!middle.is_left_and(|_| true));
192  /// ```
193  pub fn is_left_and<F>(&self, f: F) -> bool
194  where
195    F: FnOnce(&L) -> bool,
196  {
197    match self {
198      Left(l) => f(l),
199      _ => false,
200    }
201  }
202
203  /// Returns `true` if the value is a `Middle` variant and the contained
204  /// value matches the predicate.
205  ///
206  /// ```
207  /// use among::*;
208  ///
209  /// let middle: Among<u32, u32, u32> = Middle(2);
210  /// assert!(middle.is_middle_and(|x| *x == 2));
211  /// assert!(!middle.is_middle_and(|x| *x == 3));
212  ///
213  /// let left: Among<u32, u32, u32> = Left(2);
214  /// assert!(!left.is_middle_and(|_| true));
215  /// ```
216  pub fn is_middle_and<F>(&self, f: F) -> bool
217  where
218    F: FnOnce(&M) -> bool,
219  {
220    match self {
221      Middle(m) => f(m),
222      _ => false,
223    }
224  }
225
226  /// Returns `true` if the value is a `Right` variant and the contained
227  /// value matches the predicate.
228  ///
229  /// ```
230  /// use among::*;
231  ///
232  /// let right: Among<u32, u32, u32> = Right(2);
233  /// assert!(right.is_right_and(|x| *x == 2));
234  /// assert!(!right.is_right_and(|x| *x == 3));
235  ///
236  /// let left: Among<u32, u32, u32> = Left(2);
237  /// assert!(!left.is_right_and(|_| true));
238  /// ```
239  pub fn is_right_and<F>(&self, f: F) -> bool
240  where
241    F: FnOnce(&R) -> bool,
242  {
243    match self {
244      Right(r) => f(r),
245      _ => false,
246    }
247  }
248
249  /// Borrow the `Left` variant as `Option<&L>`; a shorthand for `self.as_ref().left()`.
250  ///
251  /// ```
252  /// use among::*;
253  ///
254  /// let left: Among<u32, (), ()> = Left(1);
255  /// assert_eq!(left.left_ref(), Some(&1));
256  ///
257  /// let middle: Among<u32, u32, ()> = Middle(2);
258  /// assert_eq!(middle.left_ref(), None);
259  /// ```
260  pub const fn left_ref(&self) -> Option<&L> {
261    match self {
262      Left(l) => Some(l),
263      _ => None,
264    }
265  }
266
267  /// Borrow the `Middle` variant as `Option<&M>`; a shorthand for `self.as_ref().middle()`.
268  ///
269  /// ```
270  /// use among::*;
271  ///
272  /// let middle: Among<(), u32, ()> = Middle(2);
273  /// assert_eq!(middle.middle_ref(), Some(&2));
274  ///
275  /// let left: Among<u32, u32, ()> = Left(1);
276  /// assert_eq!(left.middle_ref(), None);
277  /// ```
278  pub const fn middle_ref(&self) -> Option<&M> {
279    match self {
280      Middle(m) => Some(m),
281      _ => None,
282    }
283  }
284
285  /// Borrow the `Right` variant as `Option<&R>`; a shorthand for `self.as_ref().right()`.
286  ///
287  /// ```
288  /// use among::*;
289  ///
290  /// let right: Among<(), (), u32> = Right(3);
291  /// assert_eq!(right.right_ref(), Some(&3));
292  ///
293  /// let left: Among<u32, (), u32> = Left(1);
294  /// assert_eq!(left.right_ref(), None);
295  /// ```
296  pub const fn right_ref(&self) -> Option<&R> {
297    match self {
298      Right(r) => Some(r),
299      _ => None,
300    }
301  }
302
303  /// Mutably borrow the `Left` variant as `Option<&mut L>`.
304  ///
305  /// ```
306  /// use among::*;
307  ///
308  /// let mut left: Among<u32, (), ()> = Left(1);
309  /// if let Some(l) = left.left_mut() { *l = 10; }
310  /// assert_eq!(left, Left(10));
311  ///
312  /// let mut middle: Among<u32, u32, ()> = Middle(2);
313  /// assert!(middle.left_mut().is_none());
314  /// ```
315  pub const fn left_mut(&mut self) -> Option<&mut L> {
316    match self {
317      Left(l) => Some(l),
318      _ => None,
319    }
320  }
321
322  /// Mutably borrow the `Middle` variant as `Option<&mut M>`.
323  ///
324  /// ```
325  /// use among::*;
326  ///
327  /// let mut middle: Among<(), u32, ()> = Middle(2);
328  /// if let Some(m) = middle.middle_mut() { *m = 20; }
329  /// assert_eq!(middle, Middle(20));
330  ///
331  /// let mut left: Among<u32, u32, ()> = Left(1);
332  /// assert!(left.middle_mut().is_none());
333  /// ```
334  pub const fn middle_mut(&mut self) -> Option<&mut M> {
335    match self {
336      Middle(m) => Some(m),
337      _ => None,
338    }
339  }
340
341  /// Mutably borrow the `Right` variant as `Option<&mut R>`.
342  ///
343  /// ```
344  /// use among::*;
345  ///
346  /// let mut right: Among<(), (), u32> = Right(3);
347  /// if let Some(r) = right.right_mut() { *r = 30; }
348  /// assert_eq!(right, Right(30));
349  ///
350  /// let mut left: Among<u32, (), u32> = Left(1);
351  /// assert!(left.right_mut().is_none());
352  /// ```
353  pub const fn right_mut(&mut self) -> Option<&mut R> {
354    match self {
355      Right(r) => Some(r),
356      _ => None,
357    }
358  }
359
360  /// Convert the left side of `Among<L, M, R>` to an `Option<L>`.
361  ///
362  /// ```
363  /// use among::*;
364  ///
365  /// let left: Among<_, i64, ()> = Left("some value");
366  /// assert_eq!(left.left(),  Some("some value"));
367  ///
368  /// let right: Among<(), i64, _> = Right(321);
369  /// assert_eq!(right.left(), None);
370  ///
371  /// let middle: Among<(), i64, ()> = Middle(-321);
372  /// assert_eq!(middle.left(), None);
373  /// ```
374  pub fn left(self) -> Option<L> {
375    match self {
376      Left(l) => Some(l),
377      _ => None,
378    }
379  }
380
381  /// Convert the middle of `Among<L, M, R>` to an `Option<M>`.
382  ///
383  /// ```
384  /// use among::*;
385  ///
386  /// let left: Among<_, i64, ()> = Left("some value");
387  /// assert_eq!(left.middle(),  None);
388  ///
389  /// let right: Among<(), i64, _> = Right(321);
390  /// assert_eq!(right.middle(), None);
391  ///
392  /// let middle: Among<(), i64, ()> = Middle(-321);
393  /// assert_eq!(middle.middle(), Some(-321));
394  /// ```
395  pub fn middle(self) -> Option<M> {
396    match self {
397      Middle(m) => Some(m),
398      _ => None,
399    }
400  }
401
402  /// Convert the right side of `Among<L, M, R>` to an `Option<R>`.
403  ///
404  /// ```
405  /// use among::*;
406  ///
407  /// let left: Among<_, i64, ()> = Left("some value");
408  /// assert_eq!(left.right(),  None);
409  ///
410  /// let middle: Among<(), i64, ()> = Middle(-321);
411  /// assert_eq!(middle.right(), None);
412  ///
413  /// let right: Among<(), i64, _> = Right(321);
414  /// assert_eq!(right.right(), Some(321));
415  /// ```
416  pub fn right(self) -> Option<R> {
417    match self {
418      Right(r) => Some(r),
419      _ => None,
420    }
421  }
422
423  /// Convert `&Among<L, M, R>` to `Among<&L, &M, &R>`.
424  ///
425  /// ```
426  /// use among::*;
427  ///
428  /// let left: Among<_, i64, ()> = Left("some value");
429  /// assert_eq!(left.as_ref(), Left(&"some value"));
430  ///
431  /// let right: Among<(), i64, _> = Right("some value");
432  /// assert_eq!(right.as_ref(), Right(&"some value"));
433  ///
434  /// let middle: Among<(), _, ()> = Middle(-321);
435  /// assert_eq!(middle.as_ref(), Middle(&-321));
436  /// ```
437  pub const fn as_ref(&self) -> Among<&L, &M, &R> {
438    match *self {
439      Left(ref inner) => Left(inner),
440      Middle(ref inner) => Middle(inner),
441      Right(ref inner) => Right(inner),
442    }
443  }
444
445  /// Convert `&mut Among<L, M, R>` to `Among<&mut L, &mut M, &mut R>`.
446  ///
447  /// ```
448  /// use among::*;
449  ///
450  /// fn mutate_left(value: &mut Among<u32, u32, u32>) {
451  ///     if let Some(l) = value.as_mut().left() {
452  ///         *l = 999;
453  ///     }
454  /// }
455  ///
456  /// let mut left = Left(123);
457  /// let mut middle = Middle(123);
458  /// let mut right = Right(123);
459  ///
460  /// mutate_left(&mut left);
461  /// mutate_left(&mut right);
462  /// mutate_left(&mut middle);
463  /// assert_eq!(left, Left(999));
464  /// assert_eq!(right, Right(123));
465  /// assert_eq!(middle, Middle(123));
466  /// ```
467  pub const fn as_mut(&mut self) -> Among<&mut L, &mut M, &mut R> {
468    match *self {
469      Left(ref mut inner) => Left(inner),
470      Middle(ref mut inner) => Middle(inner),
471      Right(ref mut inner) => Right(inner),
472    }
473  }
474
475  /// Convert `Pin<&Among<L, M, R>>` to `Among<Pin<&L>, Pin<&M>, Pin<&R>>`,
476  /// pinned projections of the inner variants.
477  pub const fn as_pin_ref(self: Pin<&Self>) -> Among<Pin<&L>, Pin<&M>, Pin<&R>> {
478    // SAFETY: We can use `new_unchecked` because the `inner` parts are
479    // guaranteed to be pinned, as they come from `self` which is pinned.
480    unsafe {
481      match *Pin::get_ref(self) {
482        Left(ref inner) => Left(Pin::new_unchecked(inner)),
483        Middle(ref inner) => Middle(Pin::new_unchecked(inner)),
484        Right(ref inner) => Right(Pin::new_unchecked(inner)),
485      }
486    }
487  }
488
489  /// Convert `Pin<&mut Among<L, M, R>>` to `Among<Pin<&mut L>, Pin<&mut M>, Pin<&mut R>>`,
490  /// pinned projections of the inner variants.
491  pub const fn as_pin_mut(self: Pin<&mut Self>) -> Among<Pin<&mut L>, Pin<&mut M>, Pin<&mut R>> {
492    // SAFETY: `get_unchecked_mut` is fine because we don't move anything.
493    // We can use `new_unchecked` because the `inner` parts are guaranteed
494    // to be pinned, as they come from `self` which is pinned, and we never
495    // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We
496    // also don't have an implementation of `Drop`, nor manual `Unpin`.
497    unsafe {
498      match *Pin::get_unchecked_mut(self) {
499        Left(ref mut inner) => Left(Pin::new_unchecked(inner)),
500        Middle(ref mut inner) => Middle(Pin::new_unchecked(inner)),
501        Right(ref mut inner) => Right(Pin::new_unchecked(inner)),
502      }
503    }
504  }
505
506  /// Convert `Among<L, M, R>` to `Among<R, M, L>`.
507  ///
508  /// ```
509  /// use among::*;
510  ///
511  /// let left: Among<_, i64, ()> = Left(123);
512  /// assert_eq!(left.flip(), Right(123));
513  ///
514  /// let right: Among<(), i64, _> = Right("some value");
515  /// assert_eq!(right.flip(), Left("some value"));
516  /// ```
517  pub fn flip(self) -> Among<R, M, L> {
518    match self {
519      Left(l) => Right(l),
520      Right(r) => Left(r),
521      Middle(m) => Middle(m),
522    }
523  }
524
525  /// Convert `Among<L, M, R>` to `Among<M, L, R>`.
526  ///
527  /// ```
528  /// use among::*;
529  ///
530  /// let left: Among<i32, i64, ()> = Left(123);
531  /// assert_eq!(left.flip_left_middle(), Middle(123));
532  ///
533  /// let right: Among<i32, i64, _> = Right("some value");
534  /// assert_eq!(right.flip_left_middle(), Right("some value"));
535  ///
536  /// let middle: Among<i32, i64, ()> = Middle(456);
537  /// assert_eq!(middle.flip_left_middle(), Left(456));
538  /// ```
539  pub fn flip_left_middle(self) -> Among<M, L, R> {
540    match self {
541      Left(l) => Middle(l),
542      Right(r) => Right(r),
543      Middle(m) => Left(m),
544    }
545  }
546
547  /// Convert `Among<L, M, R>` to `Among<L, R, M>`.
548  ///
549  /// ```
550  /// use among::*;
551  ///
552  /// let left: Among<i32, i64, ()> = Left(123);
553  /// assert_eq!(left.flip_middle_right(), Left(123));
554  ///
555  /// let right: Among<i32, i64, _> = Right("some value");
556  /// assert_eq!(right.flip_middle_right(), Middle("some value"));
557  ///
558  /// let middle: Among<i32, i64, ()> = Middle(456);
559  /// assert_eq!(middle.flip_middle_right(), Right(456));
560  /// ```
561  pub fn flip_middle_right(self) -> Among<L, R, M> {
562    match self {
563      Left(l) => Left(l),
564      Right(r) => Middle(r),
565      Middle(m) => Right(m),
566    }
567  }
568
569  /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the
570  /// result in `Left`.
571  ///
572  /// ```
573  /// use among::*;
574  ///
575  /// let left: Among<_, u32, u32> = Left(123);
576  /// assert_eq!(left.map_left(|x| x * 2), Left(246));
577  ///
578  /// let right: Among<u32, u32,  _> = Right(123);
579  /// assert_eq!(right.map_left(|x| x * 2), Right(123));
580  ///
581  /// let middle: Among<u32, _, u32> = Middle(123);
582  /// assert_eq!(middle.map_left(|x| x * 3), Middle(123));
583  /// ```
584  pub fn map_left<F, N>(self, f: F) -> Among<N, M, R>
585  where
586    F: FnOnce(L) -> N,
587  {
588    match self {
589      Left(l) => Left(f(l)),
590      Middle(m) => Middle(m),
591      Right(r) => Right(r),
592    }
593  }
594
595  /// Apply the function `f` on the value in the `Middle` variant if it is present rewrapping the
596  /// result in `Middle`.
597  ///
598  /// ```
599  /// use among::*;
600  ///
601  /// let left: Among<_, u32, u32> = Left(123);
602  /// assert_eq!(left.map_middle(|x| x * 2), Left(123));
603  ///
604  /// let right: Among<u32, u32,  _> = Right(123);
605  /// assert_eq!(right.map_middle(|x| x * 2), Right(123));
606  ///
607  /// let middle: Among<u32, _, u32> = Middle(123);
608  /// assert_eq!(middle.map_middle(|x| x * 3), Middle(369));
609  /// ```
610  pub fn map_middle<F, N>(self, f: F) -> Among<L, N, R>
611  where
612    F: FnOnce(M) -> N,
613  {
614    match self {
615      Left(l) => Left(l),
616      Middle(m) => Middle(f(m)),
617      Right(r) => Right(r),
618    }
619  }
620
621  /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the
622  /// result in `Right`.
623  ///
624  /// ```
625  /// use among::*;
626  ///
627  /// let left: Among<_, u32, u32> = Left(123);
628  /// assert_eq!(left.map_right(|x| x * 2), Left(123));
629  ///
630  /// let right: Among<u32, u32, _> = Right(123);
631  /// assert_eq!(right.map_right(|x| x * 2), Right(246));
632  ///
633  /// let middle: Among<u32, _, u32> = Middle(123);
634  /// assert_eq!(middle.map_right(|x| x * 3), Middle(123));
635  /// ```
636  pub fn map_right<F, S>(self, f: F) -> Among<L, M, S>
637  where
638    F: FnOnce(R) -> S,
639  {
640    match self {
641      Left(l) => Left(l),
642      Middle(m) => Middle(m),
643      Right(r) => Right(f(r)),
644    }
645  }
646
647  /// Call `f` with the inner value if `self` is `Left`, then return `self` unchanged.
648  ///
649  /// ```
650  /// use among::*;
651  ///
652  /// let mut seen = 0;
653  /// let left: Among<u32, u32, u32> = Left(5);
654  /// let left = left.inspect_left(|v| seen = *v);
655  /// assert_eq!(seen, 5);
656  /// assert_eq!(left, Left(5));
657  ///
658  /// // Other variants are passed through unobserved.
659  /// let right: Among<u32, u32, u32> = Right(9);
660  /// assert_eq!(right.inspect_left(|_| panic!("not called")), Right(9));
661  /// ```
662  pub fn inspect_left<F>(self, f: F) -> Self
663  where
664    F: FnOnce(&L),
665  {
666    if let Left(ref l) = self {
667      f(l);
668    }
669    self
670  }
671
672  /// Call `f` with the inner value if `self` is `Middle`, then return `self` unchanged.
673  ///
674  /// ```
675  /// use among::*;
676  ///
677  /// let mut seen = 0;
678  /// let middle: Among<u32, u32, u32> = Middle(5);
679  /// let middle = middle.inspect_middle(|v| seen = *v);
680  /// assert_eq!(seen, 5);
681  /// assert_eq!(middle, Middle(5));
682  ///
683  /// let left: Among<u32, u32, u32> = Left(9);
684  /// assert_eq!(left.inspect_middle(|_| panic!("not called")), Left(9));
685  /// ```
686  pub fn inspect_middle<F>(self, f: F) -> Self
687  where
688    F: FnOnce(&M),
689  {
690    if let Middle(ref m) = self {
691      f(m);
692    }
693    self
694  }
695
696  /// Call `f` with the inner value if `self` is `Right`, then return `self` unchanged.
697  ///
698  /// ```
699  /// use among::*;
700  ///
701  /// let mut seen = 0;
702  /// let right: Among<u32, u32, u32> = Right(5);
703  /// let right = right.inspect_right(|v| seen = *v);
704  /// assert_eq!(seen, 5);
705  /// assert_eq!(right, Right(5));
706  ///
707  /// let left: Among<u32, u32, u32> = Left(9);
708  /// assert_eq!(left.inspect_right(|_| panic!("not called")), Left(9));
709  /// ```
710  pub fn inspect_right<F>(self, f: F) -> Self
711  where
712    F: FnOnce(&R),
713  {
714    if let Right(ref r) = self {
715      f(r);
716    }
717    self
718  }
719
720  /// Apply the functions `f` and `g` to the `Left` and `Right` variants
721  /// respectively. This is equivalent to
722  /// [bimap](https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html)
723  /// in functional programming.
724  ///
725  /// ```
726  /// use among::*;
727  ///
728  /// let f = |s: String| s.len();
729  /// let h = |t: u8| t.to_string();
730  /// let g = |u: usize| u * 2;
731  ///
732  /// let left: Among<String, usize, u8> = Left("loopy".into());
733  /// assert_eq!(left.map_among(f, g, h), Left(5));
734  ///
735  /// let right: Among<String, usize, u8> = Right(42);
736  /// assert_eq!(right.map_among(f, g, h), Right("42".into()));
737  /// ```
738  pub fn map_among<F, G, H, S, T, U>(self, f: F, g: G, h: H) -> Among<S, T, U>
739  where
740    F: FnOnce(L) -> S,
741    G: FnOnce(M) -> T,
742    H: FnOnce(R) -> U,
743  {
744    match self {
745      Left(l) => Left(f(l)),
746      Middle(m) => Middle(g(m)),
747      Right(r) => Right(h(r)),
748    }
749  }
750
751  /// Similar to [`map_among`][Self::map_among], with an added context `ctx` accessible to
752  /// both functions.
753  ///
754  /// ```
755  /// use among::*;
756  ///
757  /// let mut sum = 0;
758  ///
759  /// // Both closures want to update the same value, so pass it as context.
760  /// let mut f = |sum: &mut usize, s: String| { *sum += s.len(); s.to_uppercase() };
761  /// let mut g = |sum: &mut usize, i: i32| { *sum += i as usize; i.to_string() };
762  /// let mut h = |sum: &mut usize, u: usize| { *sum += u; u.to_string() };
763  ///
764  /// let left: Among<String, i32, usize> = Left("loopy".into());
765  /// assert_eq!(left.map_among_with(&mut sum, &mut f, &mut g, &mut h), Left("LOOPY".into()));
766  ///
767  /// let right: Among<String, i32, usize> = Right(42);
768  /// assert_eq!(right.map_among_with(&mut sum, &mut f, &mut g, &mut h), Right("42".into()));
769  ///
770  /// let middle: Among<String, i32, usize> = Middle(3);
771  /// assert_eq!(middle.map_among_with(&mut sum, &mut f, &mut g, &mut h), Middle("3".into()));
772  ///
773  /// assert_eq!(sum, 50);
774  /// ```
775  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>
776  where
777    F: FnOnce(Ctx, L) -> S,
778    G: FnOnce(Ctx, M) -> T,
779    H: FnOnce(Ctx, R) -> U,
780  {
781    match self {
782      Left(l) => Left(f(ctx, l)),
783      Middle(m) => Middle(g(ctx, m)),
784      Right(r) => Right(h(ctx, r)),
785    }
786  }
787
788  /// Apply one of three functions depending on contents, unifying their result. If the value is
789  /// `Left(L)` then the first function `f` is applied; if it is `Middle(M)` then the second function `g` is applied;
790  /// if it is `Right(R)` then the third function `h` is applied.
791  ///
792  /// ```
793  /// use among::*;
794  ///
795  /// fn square(n: u32) -> i32 { (n * n) as i32 }
796  /// fn negate(n: i32) -> i32 { -n }
797  /// fn cube(n: u64) -> i32 { (n * n * n) as i32 }
798  ///
799  /// let left: Among<u32, u64, i32> = Left(4);
800  /// assert_eq!(left.among(square, cube, negate), 16);
801  ///
802  /// let right: Among<u32, u64, i32> = Right(-4);
803  /// assert_eq!(right.among(square, cube, negate), 4);
804  ///
805  /// let middle: Among<u32, u64, i32> = Middle(3);
806  /// assert_eq!(middle.among(square, cube, negate), 27);
807  /// ```
808  pub fn among<F, G, H, T>(self, f: F, g: G, h: H) -> T
809  where
810    F: FnOnce(L) -> T,
811    G: FnOnce(M) -> T,
812    H: FnOnce(R) -> T,
813  {
814    match self {
815      Left(l) => f(l),
816      Middle(m) => g(m),
817      Right(r) => h(r),
818    }
819  }
820
821  /// Like [`among`][Self::among], but provide some context to whichever of the
822  /// functions ends up being called.
823  ///
824  /// ```
825  /// // In this example, the context is a mutable reference
826  /// use among::*;
827  ///
828  /// let mut result = Vec::new();
829  ///
830  /// let values = vec![Left(2), Middle(-3), Right(2.7)];
831  ///
832  /// for value in values {
833  ///     value.among_with(&mut result,
834  ///                       |ctx, integer| ctx.push(integer),
835  ///                       |ctx, neg| ctx.push(neg),
836  ///                       |ctx, real| ctx.push(f64::round(real) as i32));
837  /// }
838  ///
839  /// assert_eq!(result, vec![2, -3, 3]);
840  /// ```
841  pub fn among_with<Ctx, F, G, H, T>(self, ctx: Ctx, f: F, g: G, h: H) -> T
842  where
843    F: FnOnce(Ctx, L) -> T,
844    G: FnOnce(Ctx, M) -> T,
845    H: FnOnce(Ctx, R) -> T,
846  {
847    match self {
848      Left(l) => f(ctx, l),
849      Middle(m) => g(ctx, m),
850      Right(r) => h(ctx, r),
851    }
852  }
853
854  /// Apply the function `f` on the value in the `Left` variant if it is present.
855  ///
856  /// ```
857  /// use among::*;
858  ///
859  /// let left: Among<_, u32, u32> = Left(123);
860  /// assert_eq!(left.left_and_then::<_, ()>(|x| Right(x * 2)), Right(246));
861  ///
862  /// let right: Among<u32, u32, _> = Right(123);
863  /// assert_eq!(right.left_and_then(|x| Right::<(), _, _>(x * 2)), Right(123));
864  /// ```
865  pub fn left_and_then<F, S>(self, f: F) -> Among<S, M, R>
866  where
867    F: FnOnce(L) -> Among<S, M, R>,
868  {
869    match self {
870      Left(l) => f(l),
871      Middle(m) => Middle(m),
872      Right(r) => Right(r),
873    }
874  }
875
876  /// Apply the function `f` on the value in the `Middle` variant if it is present.
877  ///
878  /// ```
879  /// use among::*;
880  ///
881  /// let middle: Among<u32, _, u32> = Middle(123);
882  /// assert_eq!(middle.middle_and_then::<_, ()>(|x| Right(x * 2)), Right(246));
883  ///
884  /// let right: Among<u32, u32, _> = Right(123);
885  /// assert_eq!(right.middle_and_then(|x| Right::<_, (), _>(x * 2)), Right(123));
886  /// ```
887  pub fn middle_and_then<F, S>(self, f: F) -> Among<L, S, R>
888  where
889    F: FnOnce(M) -> Among<L, S, R>,
890  {
891    match self {
892      Left(l) => Left(l),
893      Middle(m) => f(m),
894      Right(r) => Right(r),
895    }
896  }
897
898  /// Apply the function `f` on the value in the `Right` variant if it is present.
899  ///
900  /// ```
901  /// use among::*;
902  ///
903  /// let left: Among<_, u32, u32> = Left(123);
904  /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123));
905  ///
906  /// let right: Among<u32, u32, _> = Right(123);
907  /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246));
908  /// ```
909  pub fn right_and_then<F, S>(self, f: F) -> Among<L, M, S>
910  where
911    F: FnOnce(R) -> Among<L, M, S>,
912  {
913    match self {
914      Left(l) => Left(l),
915      Middle(m) => Middle(m),
916      Right(r) => f(r),
917    }
918  }
919
920  /// Convert the inner value to an iterator.
921  ///
922  /// This requires the `Left`, `Middle` and `Right` iterators to have the same item type.
923  /// See [`factor_into_iter`][Among::factor_into_iter] to iterate different types.
924  ///
925  /// ```
926  /// use among::*;
927  ///
928  /// let left: Among<Vec<u32>, Vec<u32>, Vec<u32>> = Left(vec![1, 2, 3, 4, 5]);
929  /// let mut right: Among<Vec<u32>, Vec<u32>, Vec<u32>> = Right(vec![]);
930  /// right.extend(left.into_iter());
931  /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5]));
932  /// ```
933  #[allow(clippy::should_implement_trait)]
934  pub fn into_iter(self) -> Among<L::IntoIter, M::IntoIter, R::IntoIter>
935  where
936    L: IntoIterator,
937    M: IntoIterator<Item = L::Item>,
938    R: IntoIterator<Item = L::Item>,
939  {
940    map_among!(self, inner => inner.into_iter())
941  }
942
943  /// Borrow the inner value as an iterator.
944  ///
945  /// This requires the `Left`, `Middle` and `Right` iterators to have the same item type.
946  /// See [`factor_iter`][Among::factor_iter] to iterate different types.
947  ///
948  /// ```
949  /// use among::*;
950  ///
951  /// let left: Among<_, &[u32], &[u32]> = Left(vec![2, 3]);
952  /// let mut right: Among<Vec<u32>, &[u32], _> = Right(&[4, 5][..]);
953  /// let mut all = vec![1];
954  /// all.extend(left.iter());
955  /// all.extend(right.iter());
956  /// assert_eq!(all, vec![1, 2, 3, 4, 5]);
957  /// ```
958  pub fn iter(
959    &self,
960  ) -> Among<
961    <&L as IntoIterator>::IntoIter,
962    <&M as IntoIterator>::IntoIter,
963    <&R as IntoIterator>::IntoIter,
964  >
965  where
966    for<'a> &'a L: IntoIterator,
967    for<'a> &'a M: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
968    for<'a> &'a R: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
969  {
970    map_among!(self, inner => inner.into_iter())
971  }
972
973  /// Mutably borrow the inner value as an iterator.
974  ///
975  /// This requires the `Left`, `Middle` and `Right` iterators to have the same item type.
976  /// See [`factor_iter_mut`][Among::factor_iter_mut] to iterate different types.
977  ///
978  /// ```
979  /// use among::*;
980  ///
981  /// let mut left: Among<_, Vec<u32>, &mut [u32]> = Left(vec![2, 3]);
982  /// for l in left.iter_mut() {
983  ///     *l *= *l
984  /// }
985  /// assert_eq!(left, Left(vec![4, 9]));
986  ///
987  /// let mut inner = [4, 5];
988  /// let mut right: Among<Vec<u32>, Vec<u32>, _> = Right(&mut inner[..]);
989  /// for r in right.iter_mut() {
990  ///     *r *= *r
991  /// }
992  /// assert_eq!(inner, [16, 25]);
993  ///
994  /// let mut inner = [6, 7];
995  /// let mut middle: Among<Vec<u32>, _, Vec<u32>> = Middle(&mut inner[..]);
996  /// for r in middle.iter_mut() {
997  ///     *r *= *r
998  /// }
999  /// assert_eq!(inner, [36, 49]);
1000  /// ```
1001  pub fn iter_mut(
1002    &mut self,
1003  ) -> Among<
1004    <&mut L as IntoIterator>::IntoIter,
1005    <&mut M as IntoIterator>::IntoIter,
1006    <&mut R as IntoIterator>::IntoIter,
1007  >
1008  where
1009    for<'a> &'a mut L: IntoIterator,
1010    for<'a> &'a mut M: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
1011    for<'a> &'a mut R: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
1012  {
1013    map_among!(self, inner => inner.into_iter())
1014  }
1015
1016  /// Converts an `Among` of `Iterator`s to be an `Iterator` of `Among`s
1017  ///
1018  /// Unlike [`into_iter`][Among::into_iter], this does not require the
1019  /// `Left` and `Right` iterators to have the same item type.
1020  ///
1021  /// ```
1022  /// use among::*;
1023  /// let left: Among<_, Box<[u8]>, Vec<u8>> = Left(&["hello"]);
1024  /// assert_eq!(left.factor_into_iter().next(), Some(Left(&"hello")));
1025  ///
1026  /// let right: Among<&[&str], Box<[u8]>, _> = Right(vec![0, 1]);
1027  /// assert_eq!(right.factor_into_iter().collect::<Vec<_>>(), vec![Right(0), Right(1)]);
1028  ///
1029  /// ```
1030  #[doc(alias = "transpose")]
1031  pub fn factor_into_iter(self) -> IterAmong<L::IntoIter, M::IntoIter, R::IntoIter>
1032  where
1033    L: IntoIterator,
1034    M: IntoIterator,
1035    R: IntoIterator,
1036  {
1037    IterAmong::new(map_among!(self, inner => inner.into_iter()))
1038  }
1039
1040  /// Borrows an `Among` of `Iterator`s to be an `Iterator` of `Among`s
1041  ///
1042  /// Unlike [`iter`][Among::iter], this does not require the
1043  /// `Left`, `Middle` and `Right` iterators to have the same item type.
1044  ///
1045  /// ```
1046  /// use among::*;
1047  /// let left: Among<_, Box<[u8]>, Vec<u8>> = Left(["hello"]);
1048  /// assert_eq!(left.factor_iter().next(), Some(Left(&"hello")));
1049  ///
1050  /// let right: Among<[&str; 2], Box<[u8]>, _> = Right(vec![0, 1]);
1051  /// assert_eq!(right.factor_iter().collect::<Vec<_>>(), vec![Right(&0), Right(&1)]);
1052  ///
1053  /// ```
1054  pub fn factor_iter(
1055    &self,
1056  ) -> IterAmong<
1057    <&L as IntoIterator>::IntoIter,
1058    <&M as IntoIterator>::IntoIter,
1059    <&R as IntoIterator>::IntoIter,
1060  >
1061  where
1062    for<'a> &'a L: IntoIterator,
1063    for<'a> &'a M: IntoIterator,
1064    for<'a> &'a R: IntoIterator,
1065  {
1066    IterAmong::new(map_among!(self, inner => inner.into_iter()))
1067  }
1068
1069  /// Mutably borrows an `Among` of `Iterator`s to be an `Iterator` of `Among`s
1070  ///
1071  /// Unlike [`iter_mut`][Among::iter_mut], this does not require the
1072  /// `Left`, `Middle` and `Right` iterators to have the same item type.
1073  ///
1074  /// ```
1075  /// use among::*;
1076  /// let mut left: Among<_, Box<[u8]>, Vec<u8>> = Left(["hello"]);
1077  /// left.factor_iter_mut().for_each(|x| *x.unwrap_left() = "goodbye");
1078  /// assert_eq!(left, Left(["goodbye"]));
1079  ///
1080  /// let mut right: Among<[&str; 2], Box<[u8]>, _> = Right(vec![0, 1, 2]);
1081  /// right.factor_iter_mut().for_each(|x| if let Right(r) = x { *r = -*r; });
1082  /// assert_eq!(right, Right(vec![0, -1, -2]));
1083  ///
1084  /// ```
1085  pub fn factor_iter_mut(
1086    &mut self,
1087  ) -> IterAmong<
1088    <&mut L as IntoIterator>::IntoIter,
1089    <&mut M as IntoIterator>::IntoIter,
1090    <&mut R as IntoIterator>::IntoIter,
1091  >
1092  where
1093    for<'a> &'a mut L: IntoIterator,
1094    for<'a> &'a mut M: IntoIterator,
1095    for<'a> &'a mut R: IntoIterator,
1096  {
1097    IterAmong::new(map_among!(self, inner => inner.into_iter()))
1098  }
1099
1100  /// Return left value or given value
1101  ///
1102  /// Arguments passed to `left_or` are eagerly evaluated; if you are passing
1103  /// the result of a function call, it is recommended to use
1104  /// [`left_or_else`][Self::left_or_else], which is lazily evaluated.
1105  ///
1106  /// ## Examples
1107  ///
1108  /// ```
1109  /// # use among::*;
1110  /// let left: Among<&str, &str, &str> = Left("left");
1111  /// assert_eq!(left.left_or("foo"), "left");
1112  ///
1113  /// let right: Among<&str, &str, &str> = Right("right");
1114  /// assert_eq!(right.left_or("left"), "left");
1115  ///
1116  /// let middle: Among<&str, &str, &str> = Middle("middle");
1117  /// assert_eq!(middle.left_or("left"), "left");
1118  /// ```
1119  pub fn left_or(self, other: L) -> L {
1120    match self {
1121      Among::Left(l) => l,
1122      Among::Right(_) => other,
1123      Among::Middle(_) => other,
1124    }
1125  }
1126
1127  /// Return left or a default
1128  ///
1129  /// ## Examples
1130  ///
1131  /// ```
1132  /// # use among::*;
1133  /// let left: Among<String, i32, u32> = Left("left".to_string());
1134  /// assert_eq!(left.left_or_default(), "left");
1135  ///
1136  /// let right: Among<String, i32, u32> = Right(42);
1137  /// assert_eq!(right.left_or_default(), String::default());
1138  ///
1139  /// let middle: Among<String, i32, u32> = Middle(-42);
1140  /// assert_eq!(middle.left_or_default(), String::default());
1141  /// ```
1142  pub fn left_or_default(self) -> L
1143  where
1144    L: Default,
1145  {
1146    match self {
1147      Among::Left(l) => l,
1148      Among::Right(_) => L::default(),
1149      Among::Middle(_) => L::default(),
1150    }
1151  }
1152
1153  /// Returns left value or computes it from a closure
1154  ///
1155  /// ## Examples
1156  ///
1157  /// ```
1158  /// # use among::*;
1159  /// let left: Among<String, i32, u32> = Left("3".to_string());
1160  /// assert_eq!(left.left_or_else(|_| unreachable!(), |_| unreachable!()), "3");
1161  ///
1162  /// let right: Among<String, i32, u32> = Right(3);
1163  /// assert_eq!(right.left_or_else(|x| x.to_string(), |x| x.to_string()), "3");
1164  ///
1165  /// let middle: Among<String, i32, u32> = Middle(3);
1166  /// assert_eq!(middle.left_or_else(|x| x.to_string(), |x| x.to_string()), "3");
1167  /// ```
1168  pub fn left_or_else<F, G>(self, f: F, g: G) -> L
1169  where
1170    F: FnOnce(R) -> L,
1171    G: FnOnce(M) -> L,
1172  {
1173    match self {
1174      Among::Left(l) => l,
1175      Among::Right(r) => f(r),
1176      Among::Middle(m) => g(m),
1177    }
1178  }
1179
1180  /// Return middle value or given value
1181  ///
1182  /// Arguments passed to `middle_or` are eagerly evaluated; if you are passing
1183  /// the result of a function call, it is recommended to use
1184  /// [`middle_or_else`][Self::middle_or_else], which is lazily evaluated.
1185  ///
1186  /// ## Examples
1187  ///
1188  /// ```
1189  /// # use among::*;
1190  /// let right: Among<&str, &str, &str> = Right("right");
1191  /// assert_eq!(right.middle_or("middle"), "middle");
1192  ///
1193  /// let left: Among<&str, &str, &str> = Left("left");
1194  /// assert_eq!(left.middle_or("middle"), "middle");
1195  ///
1196  /// let middle: Among<&str, &str, &str> = Middle("middle");
1197  /// assert_eq!(middle.middle_or("foo"), "middle");
1198  /// ```
1199  pub fn middle_or(self, other: M) -> M {
1200    match self {
1201      Among::Middle(m) => m,
1202      _ => other,
1203    }
1204  }
1205
1206  /// Return middle or a default
1207  ///
1208  /// ## Examples
1209  ///
1210  /// ```
1211  /// # use among::*;
1212  /// let left: Among<String, i32, u32> = Left("left".to_string());
1213  /// assert_eq!(left.middle_or_default(), i32::default());
1214  ///
1215  /// let right: Among<String, i32, u32> = Right(42);
1216  /// assert_eq!(right.middle_or_default(), i32::default());
1217  ///
1218  /// let middle: Among<String, i32, u32> = Middle(-42);
1219  /// assert_eq!(middle.middle_or_default(), -42);
1220  /// ```
1221  pub fn middle_or_default(self) -> M
1222  where
1223    M: Default,
1224  {
1225    match self {
1226      Among::Middle(m) => m,
1227      _ => M::default(),
1228    }
1229  }
1230
1231  /// Returns middle value or computes it from a closure
1232  ///
1233  /// ## Examples
1234  ///
1235  /// ```
1236  /// # use among::*;
1237  /// let left: Among<String, i32, String> = Left("3".to_string());
1238  /// assert_eq!(left.middle_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
1239  ///
1240  /// let right: Among<String, i32, String> = Right("3".to_string());
1241  /// assert_eq!(right.middle_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
1242  ///
1243  /// let middle: Among<String, i32, String> = Middle(-3);
1244  /// assert_eq!(middle.middle_or_else(|_| unreachable!(), |_| unreachable!()), -3);
1245  /// ```
1246  pub fn middle_or_else<F, G>(self, f: F, g: G) -> M
1247  where
1248    F: FnOnce(L) -> M,
1249    G: FnOnce(R) -> M,
1250  {
1251    match self {
1252      Among::Left(l) => f(l),
1253      Among::Middle(m) => m,
1254      Among::Right(r) => g(r),
1255    }
1256  }
1257
1258  /// Return right value or given value
1259  ///
1260  /// Arguments passed to `right_or` are eagerly evaluated; if you are passing
1261  /// the result of a function call, it is recommended to use
1262  /// [`right_or_else`][Self::right_or_else], which is lazily evaluated.
1263  ///
1264  /// ## Examples
1265  ///
1266  /// ```
1267  /// # use among::*;
1268  /// let right: Among<&str, &str, &str> = Right("right");
1269  /// assert_eq!(right.right_or("foo"), "right");
1270  ///
1271  /// let left: Among<&str, &str, &str> = Left("left");
1272  /// assert_eq!(left.right_or("right"), "right");
1273  ///
1274  /// let middle: Among<&str, &str, &str> = Middle("middle");
1275  /// assert_eq!(middle.right_or("right"), "right");
1276  /// ```
1277  pub fn right_or(self, other: R) -> R {
1278    match self {
1279      Among::Left(_) => other,
1280      Among::Middle(_) => other,
1281      Among::Right(r) => r,
1282    }
1283  }
1284
1285  /// Return right or a default
1286  ///
1287  /// ## Examples
1288  ///
1289  /// ```
1290  /// # use among::*;
1291  /// let left: Among<String, i32, u32> = Left("left".to_string());
1292  /// assert_eq!(left.right_or_default(), u32::default());
1293  ///
1294  /// let right: Among<String, i32, u32> = Right(42);
1295  /// assert_eq!(right.right_or_default(), 42);
1296  ///
1297  /// let middle: Among<String, i32, u32> = Middle(-42);
1298  /// assert_eq!(middle.right_or_default(), u32::default());
1299  /// ```
1300  pub fn right_or_default(self) -> R
1301  where
1302    R: Default,
1303  {
1304    match self {
1305      Among::Left(_) => R::default(),
1306      Among::Middle(_) => R::default(),
1307      Among::Right(r) => r,
1308    }
1309  }
1310
1311  /// Returns right value or computes it from a closure
1312  ///
1313  /// ## Examples
1314  ///
1315  /// ```
1316  /// # use among::*;
1317  /// let left: Among<String, &str, u32> = Left("3".to_string());
1318  /// assert_eq!(left.right_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
1319  ///
1320  /// let right: Among<String, &str, u32> = Right(3);
1321  /// assert_eq!(right.right_or_else(|_| unreachable!(), |_| unreachable!()), 3);
1322  ///
1323  /// let middle: Among<String, &str, u32> = Middle("3");
1324  /// assert_eq!(middle.right_or_else(|x| x.parse().unwrap(), |x| x.parse().unwrap()), 3);
1325  /// ```
1326  pub fn right_or_else<F, G>(self, f: F, g: G) -> R
1327  where
1328    F: FnOnce(L) -> R,
1329    G: FnOnce(M) -> R,
1330  {
1331    match self {
1332      Among::Left(l) => f(l),
1333      Among::Middle(m) => g(m),
1334      Among::Right(r) => r,
1335    }
1336  }
1337
1338  /// Returns the left value
1339  ///
1340  /// ## Examples
1341  ///
1342  /// ```
1343  /// # use among::*;
1344  /// let left: Among<_, (), ()> = Left(3);
1345  /// assert_eq!(left.unwrap_left(), 3);
1346  /// ```
1347  ///
1348  /// # Panics
1349  ///
1350  /// When `Among` is a `Middle` or `Right` value
1351  ///
1352  /// ```should_panic
1353  /// # use among::*;
1354  /// let right: Among<(), (), _> = Right(3);
1355  /// right.unwrap_left();
1356  /// ```
1357  ///
1358  /// ```should_panic
1359  /// # use among::*;
1360  /// let middle: Among<(), _, ()> = Middle(3);
1361  /// middle.unwrap_left();
1362  /// ```
1363  pub fn unwrap_left(self) -> L
1364  where
1365    M: core::fmt::Debug,
1366    R: core::fmt::Debug,
1367  {
1368    match self {
1369      Among::Left(l) => l,
1370      Among::Middle(m) => {
1371        panic!("called `Among::unwrap_left()` on a `Middle` value: {:?}", m)
1372      }
1373      Among::Right(r) => {
1374        panic!("called `Among::unwrap_left()` on a `Right` value: {:?}", r)
1375      }
1376    }
1377  }
1378
1379  /// Returns the middle value
1380  ///
1381  /// ## Examples
1382  ///
1383  /// ```
1384  /// # use among::*;
1385  /// let middle: Among<(), _, ()> = Middle(3);
1386  /// assert_eq!(middle.unwrap_middle(), 3);
1387  /// ```
1388  ///
1389  /// # Panics
1390  ///
1391  /// When `Among` is a `Left` or `Right` value
1392  ///
1393  /// ```should_panic
1394  /// # use among::*;
1395  /// let right: Among<(), (), _> = Right(3);
1396  /// right.unwrap_middle();
1397  /// ```
1398  ///
1399  /// ```should_panic
1400  /// # use among::*;
1401  /// let left: Among<_, (), ()> = Left(3);
1402  /// left.unwrap_middle();
1403  /// ```
1404  pub fn unwrap_middle(self) -> M
1405  where
1406    L: core::fmt::Debug,
1407    R: core::fmt::Debug,
1408  {
1409    match self {
1410      Among::Left(l) => {
1411        panic!("called `Among::unwrap_middle()` on a `Left` value: {:?}", l)
1412      }
1413      Among::Middle(m) => m,
1414      Among::Right(r) => {
1415        panic!(
1416          "called `Among::unwrap_middle()` on a `Right` value: {:?}",
1417          r
1418        )
1419      }
1420    }
1421  }
1422
1423  /// Returns the right value
1424  ///
1425  /// ## Examples
1426  ///
1427  /// ```
1428  /// # use among::*;
1429  /// let right: Among<(), (), _> = Right(3);
1430  /// assert_eq!(right.unwrap_right(), 3);
1431  /// ```
1432  ///
1433  /// # Panics
1434  ///
1435  /// When `Among` is a `Left` or `Middle` value
1436  ///
1437  /// ```should_panic
1438  /// # use among::*;
1439  /// let left: Among<_, (), ()> = Left(3);
1440  /// left.unwrap_right();
1441  /// ```
1442  ///
1443  /// ```should_panic
1444  /// # use among::*;
1445  /// let middle: Among<(), _, ()> = Middle(3);
1446  /// middle.unwrap_right();
1447  /// ```
1448  pub fn unwrap_right(self) -> R
1449  where
1450    L: core::fmt::Debug,
1451    M: core::fmt::Debug,
1452  {
1453    match self {
1454      Among::Right(r) => r,
1455      Among::Middle(m) => {
1456        panic!(
1457          "called `Among::unwrap_right()` on a `Middle` value: {:?}",
1458          m
1459        )
1460      }
1461      Among::Left(l) => panic!("called `Among::unwrap_right()` on a `Left` value: {:?}", l),
1462    }
1463  }
1464
1465  /// Returns the left value
1466  ///
1467  /// ## Examples
1468  ///
1469  /// ```
1470  /// # use among::*;
1471  /// let left: Among<_, (), ()> = Left(3);
1472  /// assert_eq!(left.expect_left("value was not Left"), 3);
1473  /// ```
1474  ///
1475  /// # Panics
1476  ///
1477  /// When `Among` is a `Right` value
1478  ///
1479  /// ```should_panic
1480  /// # use among::*;
1481  /// let right: Among<(), (), _> = Right(3);
1482  /// right.expect_left("value was not Left");
1483  /// ```
1484  ///
1485  /// When `Among` is a `Middle` value
1486  ///
1487  /// ```should_panic
1488  /// # use among::*;
1489  /// let middle: Among<(), _, ()> = Middle(3);
1490  /// middle.expect_left("value was not Left");
1491  /// ```
1492  pub fn expect_left(self, msg: &str) -> L
1493  where
1494    M: core::fmt::Debug,
1495    R: core::fmt::Debug,
1496  {
1497    match self {
1498      Among::Left(l) => l,
1499      Among::Middle(m) => panic!("{}: {:?}", msg, m),
1500      Among::Right(r) => panic!("{}: {:?}", msg, r),
1501    }
1502  }
1503
1504  /// Returns the left value
1505  ///
1506  /// ## Examples
1507  ///
1508  /// ```
1509  /// # use among::*;
1510  /// let middle: Among<(), _, ()> = Middle(3);
1511  /// assert_eq!(middle.expect_middle("value was Middle"), 3);
1512  /// ```
1513  ///
1514  /// # Panics
1515  ///
1516  /// When `Among` is a `Right` value
1517  ///
1518  /// ```should_panic
1519  /// # use among::*;
1520  /// let right: Among<(), (), _> = Right(3);
1521  /// right.expect_middle("value was not Middle");
1522  /// ```
1523  ///
1524  /// When `Among` is a `Left` value
1525  ///
1526  /// ```should_panic
1527  /// # use among::*;
1528  /// let left: Among<_, (), ()> = Left(3);
1529  /// left.expect_middle("value was not Middle");
1530  /// ```
1531  pub fn expect_middle(self, msg: &str) -> M
1532  where
1533    L: core::fmt::Debug,
1534    R: core::fmt::Debug,
1535  {
1536    match self {
1537      Among::Left(l) => panic!("{}: {:?}", msg, l),
1538      Among::Middle(m) => m,
1539      Among::Right(r) => panic!("{}: {:?}", msg, r),
1540    }
1541  }
1542
1543  /// Returns the right value
1544  ///
1545  /// ## Examples
1546  ///
1547  /// ```
1548  /// # use among::*;
1549  /// let right: Among<(), (), _> = Right(3);
1550  /// assert_eq!(right.expect_right("value was not Right"), 3);
1551  /// ```
1552  ///
1553  /// # Panics
1554  ///
1555  /// When `Among` is a `Left` value
1556  ///
1557  /// ```should_panic
1558  /// # use among::*;
1559  /// let left: Among<_, (), ()> = Left(3);
1560  /// left.expect_right("value was not Right");
1561  /// ```
1562  ///
1563  /// When `Among` is a `Middle` value
1564  ///
1565  /// ```should_panic
1566  /// # use among::*;
1567  /// let middle: Among<(), _, ()> = Middle(3);
1568  /// middle.expect_right("value was not Right");
1569  /// ```
1570  pub fn expect_right(self, msg: &str) -> R
1571  where
1572    L: core::fmt::Debug,
1573    M: core::fmt::Debug,
1574  {
1575    match self {
1576      Among::Right(r) => r,
1577      Among::Middle(m) => panic!("{}: {:?}", msg, m),
1578      Among::Left(l) => panic!("{}: {:?}", msg, l),
1579    }
1580  }
1581
1582  /// Shift the contained value.
1583  ///
1584  /// The `Left` variant becomes `Middle`, `Middle` becomes `Right`, and `Right` becomes `Left`.
1585  ///
1586  /// ## Examples
1587  ///
1588  /// ```
1589  /// # use among::*;
1590  /// let left: Among<u8, u16, u32> = Left(123);
1591  /// assert_eq!(left.shift_right(), Middle(123));
1592  ///
1593  /// let middle: Among<u8, u16, u32> = Middle(456);
1594  /// assert_eq!(middle.shift_right(), Right(456));
1595  ///
1596  /// let right: Among<u8, u16, u32> = Right(789);
1597  /// assert_eq!(right.shift_right(), Left(789));
1598  /// ```
1599  pub fn shift_right(self) -> Among<R, L, M> {
1600    match self {
1601      Among::Left(l) => Among::Middle(l),
1602      Among::Middle(m) => Among::Right(m),
1603      Among::Right(r) => Among::Left(r),
1604    }
1605  }
1606
1607  /// Shift the contained value.
1608  ///
1609  /// The `Left` variant becomes `Right`, `Middle` becomes `Left`, and `Right` becomes `Middle`.
1610  ///
1611  /// ## Examples
1612  ///
1613  /// ```
1614  /// # use among::*;
1615  /// let left: Among<u8, u16, u32> = Left(123);
1616  /// assert_eq!(left.shift_left(), Right(123));
1617  ///
1618  /// let middle: Among<u8, u16, u32> = Middle(456);
1619  /// assert_eq!(middle.shift_left(), Left(456));
1620  ///
1621  /// let right: Among<u8, u16, u32> = Right(789);
1622  /// assert_eq!(right.shift_left(), Middle(789));
1623  /// ```
1624  pub fn shift_left(self) -> Among<M, R, L> {
1625    match self {
1626      Among::Left(l) => Among::Right(l),
1627      Among::Middle(m) => Among::Left(m),
1628      Among::Right(r) => Among::Middle(r),
1629    }
1630  }
1631
1632  /// Replace `self` with `Left(value)` and return a mutable reference to the new value.
1633  ///
1634  /// Any previously-held `Middle` or `Right` value is dropped.
1635  ///
1636  /// ```
1637  /// use among::*;
1638  ///
1639  /// let mut a: Among<u32, u32, u32> = Right(1);
1640  /// let l = a.insert_left(10);
1641  /// *l += 1;
1642  /// assert_eq!(a, Left(11));
1643  /// ```
1644  pub fn insert_left(&mut self, value: L) -> &mut L {
1645    *self = Left(value);
1646    match self {
1647      Left(l) => l,
1648      _ => unreachable!(),
1649    }
1650  }
1651
1652  /// Replace `self` with `Middle(value)` and return a mutable reference to the new value.
1653  ///
1654  /// Any previously-held `Left` or `Right` value is dropped.
1655  ///
1656  /// ```
1657  /// use among::*;
1658  ///
1659  /// let mut a: Among<u32, u32, u32> = Left(1);
1660  /// let m = a.insert_middle(20);
1661  /// *m += 1;
1662  /// assert_eq!(a, Middle(21));
1663  /// ```
1664  pub fn insert_middle(&mut self, value: M) -> &mut M {
1665    *self = Middle(value);
1666    match self {
1667      Middle(m) => m,
1668      _ => unreachable!(),
1669    }
1670  }
1671
1672  /// Replace `self` with `Right(value)` and return a mutable reference to the new value.
1673  ///
1674  /// Any previously-held `Left` or `Middle` value is dropped.
1675  ///
1676  /// ```
1677  /// use among::*;
1678  ///
1679  /// let mut a: Among<u32, u32, u32> = Left(1);
1680  /// let r = a.insert_right(30);
1681  /// *r += 1;
1682  /// assert_eq!(a, Right(31));
1683  /// ```
1684  pub fn insert_right(&mut self, value: R) -> &mut R {
1685    *self = Right(value);
1686    match self {
1687      Right(r) => r,
1688      _ => unreachable!(),
1689    }
1690  }
1691
1692  /// If `self` is `Left`, return a mutable reference to the contained value.
1693  /// Otherwise replace `self` with `Left(default)` and return a mutable reference to it.
1694  ///
1695  /// ```
1696  /// use among::*;
1697  ///
1698  /// let mut keep: Among<u32, u32, u32> = Left(7);
1699  /// assert_eq!(*keep.get_or_insert_left(99), 7);
1700  ///
1701  /// let mut overwrite: Among<u32, u32, u32> = Right(1);
1702  /// assert_eq!(*overwrite.get_or_insert_left(99), 99);
1703  /// assert_eq!(overwrite, Left(99));
1704  /// ```
1705  pub fn get_or_insert_left(&mut self, default: L) -> &mut L {
1706    self.get_or_insert_left_with(|| default)
1707  }
1708
1709  /// If `self` is `Middle`, return a mutable reference to the contained value.
1710  /// Otherwise replace `self` with `Middle(default)` and return a mutable reference to it.
1711  ///
1712  /// ```
1713  /// use among::*;
1714  ///
1715  /// let mut keep: Among<u32, u32, u32> = Middle(7);
1716  /// assert_eq!(*keep.get_or_insert_middle(99), 7);
1717  ///
1718  /// let mut overwrite: Among<u32, u32, u32> = Right(1);
1719  /// assert_eq!(*overwrite.get_or_insert_middle(99), 99);
1720  /// assert_eq!(overwrite, Middle(99));
1721  /// ```
1722  pub fn get_or_insert_middle(&mut self, default: M) -> &mut M {
1723    self.get_or_insert_middle_with(|| default)
1724  }
1725
1726  /// If `self` is `Right`, return a mutable reference to the contained value.
1727  /// Otherwise replace `self` with `Right(default)` and return a mutable reference to it.
1728  ///
1729  /// ```
1730  /// use among::*;
1731  ///
1732  /// let mut keep: Among<u32, u32, u32> = Right(7);
1733  /// assert_eq!(*keep.get_or_insert_right(99), 7);
1734  ///
1735  /// let mut overwrite: Among<u32, u32, u32> = Left(1);
1736  /// assert_eq!(*overwrite.get_or_insert_right(99), 99);
1737  /// assert_eq!(overwrite, Right(99));
1738  /// ```
1739  pub fn get_or_insert_right(&mut self, default: R) -> &mut R {
1740    self.get_or_insert_right_with(|| default)
1741  }
1742
1743  /// Like [`get_or_insert_left`][Self::get_or_insert_left] but computes the default lazily.
1744  ///
1745  /// ```
1746  /// use among::*;
1747  ///
1748  /// let mut a: Among<u32, u32, u32> = Right(1);
1749  /// let l = a.get_or_insert_left_with(|| 42);
1750  /// *l += 1;
1751  /// assert_eq!(a, Left(43));
1752  /// ```
1753  pub fn get_or_insert_left_with<F>(&mut self, f: F) -> &mut L
1754  where
1755    F: FnOnce() -> L,
1756  {
1757    if !self.is_left() {
1758      *self = Left(f());
1759    }
1760    match self {
1761      Left(l) => l,
1762      _ => unreachable!(),
1763    }
1764  }
1765
1766  /// Like [`get_or_insert_middle`][Self::get_or_insert_middle] but computes the default lazily.
1767  ///
1768  /// ```
1769  /// use among::*;
1770  ///
1771  /// let mut a: Among<u32, u32, u32> = Right(1);
1772  /// let m = a.get_or_insert_middle_with(|| 42);
1773  /// *m += 1;
1774  /// assert_eq!(a, Middle(43));
1775  /// ```
1776  pub fn get_or_insert_middle_with<F>(&mut self, f: F) -> &mut M
1777  where
1778    F: FnOnce() -> M,
1779  {
1780    if !self.is_middle() {
1781      *self = Middle(f());
1782    }
1783    match self {
1784      Middle(m) => m,
1785      _ => unreachable!(),
1786    }
1787  }
1788
1789  /// Like [`get_or_insert_right`][Self::get_or_insert_right] but computes the default lazily.
1790  ///
1791  /// ```
1792  /// use among::*;
1793  ///
1794  /// let mut a: Among<u32, u32, u32> = Left(1);
1795  /// let r = a.get_or_insert_right_with(|| 42);
1796  /// *r += 1;
1797  /// assert_eq!(a, Right(43));
1798  /// ```
1799  pub fn get_or_insert_right_with<F>(&mut self, f: F) -> &mut R
1800  where
1801    F: FnOnce() -> R,
1802  {
1803    if !self.is_right() {
1804      *self = Right(f());
1805    }
1806    match self {
1807      Right(r) => r,
1808      _ => unreachable!(),
1809    }
1810  }
1811
1812  /// Convert the contained value into `T`
1813  ///
1814  /// ## Examples
1815  ///
1816  /// ```
1817  /// # use among::*;
1818  /// // Both u16 and u32 can be converted to u64.
1819  /// let left: Among<u16, u32, u64> = Left(3u16);
1820  /// assert_eq!(left.among_into::<u64>(), 3u64);
1821  /// let middle: Among<u16, u32, u64> = Middle(3u32);
1822  /// assert_eq!(middle.among_into::<u64>(), 3u64);
1823  /// let right: Among<u16, u32, u64> = Right(7u64);
1824  /// assert_eq!(right.among_into::<u64>(), 7u64);
1825  /// ```
1826  pub fn among_into<T>(self) -> T
1827  where
1828    L: Into<T>,
1829    M: Into<T>,
1830    R: Into<T>,
1831  {
1832    match self {
1833      Among::Left(l) => l.into(),
1834      Among::Middle(m) => m.into(),
1835      Among::Right(r) => r.into(),
1836    }
1837  }
1838
1839  /// Attempt to convert the contained value into `T`, wrapping any conversion error
1840  /// in an `Among` preserving the originating side.
1841  ///
1842  /// ## Examples
1843  ///
1844  /// ```
1845  /// # use among::*;
1846  /// // i64 -> i32 is fallible. Picking values that fit succeeds.
1847  /// let left: Among<i64, i32, u32> = Left(3i64);
1848  /// assert_eq!(left.try_among_into::<i32>().ok(), Some(3i32));
1849  ///
1850  /// // A value that doesn't fit comes back as an Among carrying the source-side error.
1851  /// let left: Among<i64, i32, u32> = Left(i64::MAX);
1852  /// assert!(matches!(left.try_among_into::<i32>(), Err(Left(_))));
1853  /// ```
1854  #[allow(clippy::type_complexity)]
1855  pub fn try_among_into<T>(
1856    self,
1857  ) -> Result<T, Among<<L as TryInto<T>>::Error, <M as TryInto<T>>::Error, <R as TryInto<T>>::Error>>
1858  where
1859    L: TryInto<T>,
1860    M: TryInto<T>,
1861    R: TryInto<T>,
1862  {
1863    match self {
1864      Among::Left(l) => l.try_into().map_err(Among::Left),
1865      Among::Middle(m) => m.try_into().map_err(Among::Middle),
1866      Among::Right(r) => r.try_into().map_err(Among::Right),
1867    }
1868  }
1869}
1870
1871impl<L, M, R> Among<Option<L>, Option<M>, Option<R>> {
1872  /// Factors out `None` from an `Among` of [`Option`].
1873  ///
1874  /// ```
1875  /// use among::*;
1876  /// let left: Among<_, Option<u32>, Option<String>> = Left(Some(vec![0]));
1877  /// assert_eq!(left.factor_none(), Some(Left(vec![0])));
1878  ///
1879  /// let right: Among<Option<Vec<u8>>, Option<u32>, _> = Right(Some(String::new()));
1880  /// assert_eq!(right.factor_none(), Some(Right(String::new())));
1881  ///
1882  /// let middle: Among<Option<Vec<u8>>, _, Option<String>> = Middle(Some(123));
1883  /// assert_eq!(middle.factor_none(), Some(Middle(123)));
1884  /// ```
1885  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1886  // #[doc(alias = "transpose")]
1887  pub fn factor_none(self) -> Option<Among<L, M, R>> {
1888    match self {
1889      Left(l) => l.map(Among::Left),
1890      Middle(m) => m.map(Among::Middle),
1891      Right(r) => r.map(Among::Right),
1892    }
1893  }
1894}
1895
1896impl<L, M, R, E> Among<Result<L, E>, Result<M, E>, Result<R, E>> {
1897  /// Factors out a homogenous type from an `Among` of [`Result`].
1898  ///
1899  /// Here, the homogeneous type is the `Err` type of the [`Result`].
1900  ///
1901  /// ```
1902  /// use among::*;
1903  /// let left: Among<_, Result<u32, u32>, Result<String, u32>> = Left(Ok(vec![0]));
1904  /// assert_eq!(left.factor_err(), Ok(Left(vec![0])));
1905  ///
1906  /// let right: Among<Result<Vec<u8>, u32>, Result<u32, u32>, _> = Right(Ok(String::new()));
1907  /// assert_eq!(right.factor_err(), Ok(Right(String::new())));
1908  ///
1909  /// let middle: Among<Result<Vec<u8>, u32>, _, Result<String, u32>> = Middle(Ok(123));
1910  /// assert_eq!(middle.factor_err(), Ok(Middle(123)));
1911  /// ```
1912  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1913  // #[doc(alias = "transpose")]
1914  pub fn factor_err(self) -> Result<Among<L, M, R>, E> {
1915    match self {
1916      Left(l) => l.map(Among::Left),
1917      Middle(m) => m.map(Among::Middle),
1918      Right(r) => r.map(Among::Right),
1919    }
1920  }
1921}
1922
1923impl<T, L, M, R> Among<Result<T, L>, Result<T, M>, Result<T, R>> {
1924  /// Factors out a homogenous type from an `Among` of [`Result`].
1925  ///
1926  /// Here, the homogeneous type is the `Ok` type of the [`Result`].
1927  ///
1928  /// ```
1929  /// use among::*;
1930  /// let left: Among<_, Result<u32, i64>, Result<u32, String>> = Left(Err(vec![0]));
1931  /// assert_eq!(left.factor_ok(), Err(Left(vec![0])));
1932  ///
1933  /// let right: Among<Result<u32, Vec<u8>>, Result<u32, i64>, _> = Right(Err(String::new()));
1934  /// assert_eq!(right.factor_ok(), Err(Right(String::new())));
1935  ///
1936  /// let middle: Among<Result<u32, Vec<u8>>, _, Result<u32, String>> = Middle(Err(-123));
1937  /// assert_eq!(middle.factor_ok(), Err(Middle(-123)));
1938  /// ```
1939  // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1940  // #[doc(alias = "transpose")]
1941  pub fn factor_ok(self) -> Result<T, Among<L, M, R>> {
1942    match self {
1943      Left(l) => l.map_err(Among::Left),
1944      Middle(m) => m.map_err(Among::Middle),
1945      Right(r) => r.map_err(Among::Right),
1946    }
1947  }
1948}
1949
1950impl<T, L, M, R> Among<(T, L), (T, M), (T, R)> {
1951  /// Factor out a homogeneous type from an among of pairs.
1952  ///
1953  /// Here, the homogeneous type is the first element of the pairs.
1954  ///
1955  /// ```
1956  /// use among::*;
1957  /// let left: Among<_, (u32, i64), (u32, String)> = Left((123, vec![0]));
1958  /// assert_eq!(left.factor_first().0, 123);
1959  ///
1960  /// let right: Among<(u32, Vec<u8>), (u32, i64), _> = Right((123, String::new()));
1961  /// assert_eq!(right.factor_first().0, 123);
1962  ///
1963  /// let middle: Among<(u32, Vec<u8>), _, (u32, String)> = Middle((123, vec![0]));
1964  /// assert_eq!(middle.factor_first().0, 123);
1965  /// ```
1966  pub fn factor_first(self) -> (T, Among<L, M, R>) {
1967    match self {
1968      Left((t, l)) => (t, Left(l)),
1969      Middle((t, m)) => (t, Middle(m)),
1970      Right((t, r)) => (t, Right(r)),
1971    }
1972  }
1973}
1974
1975impl<T, L, M, R> Among<(L, T), (M, T), (R, T)> {
1976  /// Factor out a homogeneous type from an among of pairs.
1977  ///
1978  /// Here, the homogeneous type is the second element of the pairs.
1979  ///
1980  /// ```
1981  /// use among::*;
1982  /// let left: Among<_, (i64, u32), (String, u32)> = Left((vec![0], 123));
1983  /// assert_eq!(left.factor_second().1, 123);
1984  ///
1985  /// let right: Among<(Vec<u8>, u32), (i64, u32), _> = Right((String::new(), 123));
1986  /// assert_eq!(right.factor_second().1, 123);
1987  ///
1988  /// let middle: Among<(Vec<u8>, u32), _, (String, u32)> = Middle((-1, 123));
1989  /// assert_eq!(middle.factor_second().1, 123);
1990  /// ```
1991  pub fn factor_second(self) -> (Among<L, M, R>, T) {
1992    match self {
1993      Left((l, t)) => (Left(l), t),
1994      Middle((m, t)) => (Middle(m), t),
1995      Right((r, t)) => (Right(r), t),
1996    }
1997  }
1998}
1999
2000impl<T> Among<T, T, T> {
2001  /// Extract the value of an among over two equivalent types.
2002  ///
2003  /// ```
2004  /// use among::*;
2005  ///
2006  /// let left: Among<_, _, u32> = Left(123);
2007  /// assert_eq!(left.into_inner(), 123);
2008  ///
2009  /// let right: Among<u32, _, _> = Right(123);
2010  /// assert_eq!(right.into_inner(), 123);
2011  ///
2012  /// let middle: Among<_, u32, _> = Middle(123);
2013  /// assert_eq!(middle.into_inner(), 123);
2014  /// ```
2015  pub fn into_inner(self) -> T {
2016    for_all!(self, inner => inner)
2017  }
2018
2019  /// Borrow the contained value when all three type parameters match.
2020  ///
2021  /// Unlike [`into_inner`][Self::into_inner], this does not consume `self`.
2022  ///
2023  /// ```
2024  /// use among::*;
2025  ///
2026  /// let left: Among<i32, i32, i32> = Left(1);
2027  /// let middle: Among<i32, i32, i32> = Middle(2);
2028  /// let right: Among<i32, i32, i32> = Right(3);
2029  ///
2030  /// assert_eq!(*left.as_inner(), 1);
2031  /// assert_eq!(*middle.as_inner(), 2);
2032  /// assert_eq!(*right.as_inner(), 3);
2033  /// ```
2034  pub const fn as_inner(&self) -> &T {
2035    for_all!(*self, ref inner => inner)
2036  }
2037
2038  /// Mutably borrow the contained value when all three type parameters match.
2039  ///
2040  /// Unlike [`into_inner`][Self::into_inner], this does not consume `self`.
2041  ///
2042  /// ```
2043  /// use among::*;
2044  ///
2045  /// let mut value: Among<i32, i32, i32> = Middle(0);
2046  /// *value.as_inner_mut() = 42;
2047  /// assert_eq!(value, Middle(42));
2048  /// ```
2049  pub const fn as_inner_mut(&mut self) -> &mut T {
2050    for_all!(*self, ref mut inner => inner)
2051  }
2052
2053  /// Map `f` over the contained value and return the result in the
2054  /// corresponding variant.
2055  ///
2056  /// ```
2057  /// use among::*;
2058  ///
2059  /// let value: Among<_, _, i32> = Right(42);
2060  ///
2061  /// let other = value.map(|x| x * 2);
2062  /// assert_eq!(other, Right(84));
2063  /// ```
2064  pub fn map<F, M>(self, f: F) -> Among<M, M, M>
2065  where
2066    F: FnOnce(T) -> M,
2067  {
2068    match self {
2069      Left(l) => Left(f(l)),
2070      Middle(m) => Middle(f(m)),
2071      Right(r) => Right(f(r)),
2072    }
2073  }
2074}
2075
2076impl<L, M, R> Among<&L, &M, &R> {
2077  /// Maps an `Among<&L, &M, &R>` to an `Among<L, M, R>` by cloning the contents of
2078  /// among branch.
2079  pub fn cloned(self) -> Among<L, M, R>
2080  where
2081    L: Clone,
2082    M: Clone,
2083    R: Clone,
2084  {
2085    match self {
2086      Self::Left(l) => Among::Left(l.clone()),
2087      Self::Middle(m) => Among::Middle(m.clone()),
2088      Self::Right(r) => Among::Right(r.clone()),
2089    }
2090  }
2091
2092  /// Maps an `Among<&L, &M, &R>` to an `Among<L, M, R>` by copying the contents of
2093  /// among branch.
2094  pub const fn copied(self) -> Among<L, M, R>
2095  where
2096    L: Copy,
2097    M: Copy,
2098    R: Copy,
2099  {
2100    match self {
2101      Self::Left(l) => Among::Left(*l),
2102      Self::Middle(m) => Among::Middle(*m),
2103      Self::Right(r) => Among::Right(*r),
2104    }
2105  }
2106}
2107
2108impl<L, M, R> Among<&mut L, &mut M, &mut R> {
2109  /// Maps an `Among<&mut L, &mut M, &mut R>` to an `Among<L, M, R>` by cloning the contents of
2110  /// among branch.
2111  pub fn cloned(self) -> Among<L, M, R>
2112  where
2113    L: Clone,
2114    M: Clone,
2115    R: Clone,
2116  {
2117    match self {
2118      Self::Left(l) => Among::Left(l.clone()),
2119      Self::Middle(m) => Among::Middle(m.clone()),
2120      Self::Right(r) => Among::Right(r.clone()),
2121    }
2122  }
2123
2124  /// Maps an `Among<&mut L, &mut M, &mut R>` to an `Among<L, M, R>` by copying the contents of
2125  /// among branch.
2126  pub const fn copied(self) -> Among<L, M, R>
2127  where
2128    L: Copy,
2129    M: Copy,
2130    R: Copy,
2131  {
2132    match self {
2133      Self::Left(l) => Among::Left(*l),
2134      Self::Middle(m) => Among::Middle(*m),
2135      Self::Right(r) => Among::Right(*r),
2136    }
2137  }
2138}
2139
2140/// `Among<L, M, R>` is a future if both `L`, `M` and `R` are futures.
2141impl<L, M, R> Future for Among<L, M, R>
2142where
2143  L: Future,
2144  M: Future,
2145  R: Future,
2146{
2147  type Output = Among<L::Output, M::Output, R::Output>;
2148
2149  fn poll(
2150    self: Pin<&mut Self>,
2151    cx: &mut core::task::Context<'_>,
2152  ) -> core::task::Poll<Self::Output> {
2153    match self.as_pin_mut() {
2154      Left(l) => l.poll(cx).map(Left),
2155      Middle(m) => m.poll(cx).map(Middle),
2156      Right(r) => r.poll(cx).map(Right),
2157    }
2158  }
2159}
2160
2161#[cfg(any(test, feature = "std"))]
2162/// `Among<L, M, R>` implements `Read` if both `L` and `R` do.
2163///
2164/// Requires crate feature `"std"`
2165impl<L, M, R> Read for Among<L, M, R>
2166where
2167  L: Read,
2168  M: Read,
2169  R: Read,
2170{
2171  fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2172    for_all!(*self, ref mut inner => inner.read(buf))
2173  }
2174
2175  fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
2176    for_all!(*self, ref mut inner => inner.read_exact(buf))
2177  }
2178
2179  fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
2180    for_all!(*self, ref mut inner => inner.read_to_end(buf))
2181  }
2182
2183  fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
2184    for_all!(*self, ref mut inner => inner.read_to_string(buf))
2185  }
2186}
2187
2188#[cfg(any(test, feature = "std"))]
2189/// `Among<L, M, R>` implements `Seek` if both `L` and `R` do.
2190///
2191/// Requires crate feature `"std"`
2192impl<L, M, R> Seek for Among<L, M, R>
2193where
2194  L: Seek,
2195  M: Seek,
2196  R: Seek,
2197{
2198  fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
2199    for_all!(*self, ref mut inner => inner.seek(pos))
2200  }
2201}
2202
2203#[cfg(any(test, feature = "std"))]
2204/// Requires crate feature `"std"`
2205impl<L, M, R> BufRead for Among<L, M, R>
2206where
2207  L: BufRead,
2208  M: BufRead,
2209  R: BufRead,
2210{
2211  fn fill_buf(&mut self) -> io::Result<&[u8]> {
2212    for_all!(*self, ref mut inner => inner.fill_buf())
2213  }
2214
2215  fn consume(&mut self, amt: usize) {
2216    for_all!(*self, ref mut inner => inner.consume(amt))
2217  }
2218
2219  fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
2220    for_all!(*self, ref mut inner => inner.read_until(byte, buf))
2221  }
2222
2223  fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
2224    for_all!(*self, ref mut inner => inner.read_line(buf))
2225  }
2226}
2227
2228#[cfg(any(test, feature = "std"))]
2229/// `Among<L, M, R>` implements `Write` if all of `L`, `M` and `R` do.
2230///
2231/// Requires crate feature `"std"`
2232impl<L, M, R> Write for Among<L, M, R>
2233where
2234  L: Write,
2235  M: Write,
2236  R: Write,
2237{
2238  fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2239    for_all!(*self, ref mut inner => inner.write(buf))
2240  }
2241
2242  fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2243    for_all!(*self, ref mut inner => inner.write_all(buf))
2244  }
2245
2246  fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
2247    for_all!(*self, ref mut inner => inner.write_fmt(fmt))
2248  }
2249
2250  fn flush(&mut self) -> io::Result<()> {
2251    for_all!(*self, ref mut inner => inner.flush())
2252  }
2253}
2254
2255impl<L, M, R, Target> AsRef<Target> for Among<L, M, R>
2256where
2257  L: AsRef<Target>,
2258  M: AsRef<Target>,
2259  R: AsRef<Target>,
2260{
2261  fn as_ref(&self) -> &Target {
2262    for_all!(*self, ref inner => inner.as_ref())
2263  }
2264}
2265
2266macro_rules! impl_specific_ref_and_mut {
2267    ($t:ty, $($attr:meta),* ) => {
2268        $(#[$attr])*
2269        impl<L, M, R> AsRef<$t> for Among<L, M, R>
2270            where L: AsRef<$t>, M: AsRef<$t>, R: AsRef<$t>,
2271        {
2272            fn as_ref(&self) -> &$t {
2273                for_all!(*self, ref inner => inner.as_ref())
2274            }
2275        }
2276
2277        $(#[$attr])*
2278        impl<L, M, R> AsMut<$t> for Among<L, M, R>
2279            where L: AsMut<$t>, M: AsMut<$t>, R: AsMut<$t>,
2280        {
2281            fn as_mut(&mut self) -> &mut $t {
2282                for_all!(*self, ref mut inner => inner.as_mut())
2283            }
2284        }
2285    };
2286}
2287
2288impl_specific_ref_and_mut!(str,);
2289impl_specific_ref_and_mut!(
2290  ::std::path::Path,
2291  cfg(feature = "std"),
2292  doc = "Requires crate feature `std`."
2293);
2294impl_specific_ref_and_mut!(
2295  ::std::ffi::OsStr,
2296  cfg(feature = "std"),
2297  doc = "Requires crate feature `std`."
2298);
2299impl_specific_ref_and_mut!(
2300  ::std::ffi::CStr,
2301  cfg(feature = "std"),
2302  doc = "Requires crate feature `std`."
2303);
2304
2305impl<L, M, R, Target> AsRef<[Target]> for Among<L, M, R>
2306where
2307  L: AsRef<[Target]>,
2308  M: AsRef<[Target]>,
2309  R: AsRef<[Target]>,
2310{
2311  fn as_ref(&self) -> &[Target] {
2312    for_all!(*self, ref inner => inner.as_ref())
2313  }
2314}
2315
2316impl<L, M, R, Target> AsMut<Target> for Among<L, M, R>
2317where
2318  L: AsMut<Target>,
2319  M: AsMut<Target>,
2320  R: AsMut<Target>,
2321{
2322  fn as_mut(&mut self) -> &mut Target {
2323    for_all!(*self, ref mut inner => inner.as_mut())
2324  }
2325}
2326
2327impl<L, M, R, Target> AsMut<[Target]> for Among<L, M, R>
2328where
2329  L: AsMut<[Target]>,
2330  M: AsMut<[Target]>,
2331  R: AsMut<[Target]>,
2332{
2333  fn as_mut(&mut self) -> &mut [Target] {
2334    for_all!(*self, ref mut inner => inner.as_mut())
2335  }
2336}
2337
2338impl<L, M, R> Deref for Among<L, M, R>
2339where
2340  L: Deref,
2341  M: Deref<Target = L::Target>,
2342  R: Deref<Target = L::Target>,
2343{
2344  type Target = L::Target;
2345
2346  fn deref(&self) -> &Self::Target {
2347    for_all!(*self, ref inner => &**inner)
2348  }
2349}
2350
2351impl<L, M, R> DerefMut for Among<L, M, R>
2352where
2353  L: DerefMut,
2354  M: DerefMut<Target = L::Target>,
2355  R: DerefMut<Target = L::Target>,
2356{
2357  fn deref_mut(&mut self) -> &mut Self::Target {
2358    for_all!(*self, ref mut inner => &mut *inner)
2359  }
2360}
2361
2362#[cfg(any(test, feature = "std"))]
2363/// `Among` implements `Error` if *all* of `L`, `M` and `R` implement it.
2364///
2365/// Requires crate feature `"std"`
2366impl<L, M, R> Error for Among<L, M, R>
2367where
2368  L: Error,
2369  M: Error,
2370  R: Error,
2371{
2372  fn source(&self) -> Option<&(dyn Error + 'static)> {
2373    for_all!(*self, ref inner => inner.source())
2374  }
2375
2376  #[allow(deprecated)]
2377  fn description(&self) -> &str {
2378    for_all!(*self, ref inner => inner.description())
2379  }
2380
2381  #[allow(deprecated)]
2382  fn cause(&self) -> Option<&dyn Error> {
2383    for_all!(*self, ref inner => inner.cause())
2384  }
2385}
2386
2387impl<L, M, R> fmt::Display for Among<L, M, R>
2388where
2389  L: fmt::Display,
2390  M: fmt::Display,
2391  R: fmt::Display,
2392{
2393  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2394    for_all!(*self, ref inner => inner.fmt(f))
2395  }
2396}
2397
2398#[test]
2399fn basic() {
2400  let mut e = Left(2);
2401  let m = Middle(2);
2402  let r = Right(2);
2403  assert_eq!(e, Left(2));
2404  e = r;
2405  assert_eq!(e, Right(2));
2406  assert_eq!(e.left(), None);
2407  assert_eq!(e.middle(), None);
2408  assert_eq!(e.right(), Some(2));
2409  assert_eq!(e.as_ref().right(), Some(&2));
2410  assert_eq!(e.as_mut().right(), Some(&mut 2));
2411  e = m;
2412  assert_eq!(e, Middle(2));
2413  assert_eq!(e.left(), None);
2414  assert_eq!(e.right(), None);
2415  assert_eq!(e.middle(), Some(2));
2416  assert_eq!(e.as_ref().middle(), Some(&2));
2417  assert_eq!(e.as_mut().middle(), Some(&mut 2));
2418}
2419
2420#[test]
2421fn deref() {
2422  use std::{borrow::Cow, string::String};
2423
2424  fn is_str(_: &str) {}
2425  let value: Among<String, Cow<'_, str>, &str> = Left(String::from("test"));
2426  is_str(&value);
2427}
2428
2429#[test]
2430fn iter() {
2431  let x = 3;
2432  let mut iter = match x {
2433    3 => Left(0..10),
2434    6 => Middle(11..17),
2435    _ => Right(17..),
2436  };
2437
2438  assert_eq!(iter.next(), Some(0));
2439  assert_eq!(iter.count(), 9);
2440}
2441
2442#[test]
2443fn seek() {
2444  use std::{io, vec};
2445
2446  let use_empty = 1;
2447  let mut mockdata = [0x00; 256];
2448  for (i, elem) in mockdata.iter_mut().enumerate() {
2449    *elem = i as u8;
2450  }
2451  let mockvec: vec::Vec<u8> = vec![];
2452
2453  let mut reader = if use_empty == 0 {
2454    // Empty didn't impl Seek until Rust 1.51
2455    Left(io::Cursor::new([]))
2456  } else if use_empty == 1 {
2457    Right(io::Cursor::new(&mockdata[..]))
2458  } else {
2459    Middle(io::Cursor::new(&mockvec[..]))
2460  };
2461
2462  let mut buf = [0u8; 16];
2463  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
2464  assert_eq!(buf, mockdata[..buf.len()]);
2465
2466  // the first read should advance the cursor and return the next 16 bytes thus the `ne`
2467  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
2468  assert_ne!(buf, mockdata[..buf.len()]);
2469
2470  // if the seek operation fails it should read 16..31 instead of 0..15
2471  reader.seek(io::SeekFrom::Start(0)).unwrap();
2472  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
2473  assert_eq!(buf, mockdata[..buf.len()]);
2474}
2475
2476#[test]
2477fn read_write() {
2478  use std::{io, vec};
2479
2480  let io = 1;
2481  let mockdata = [0xff; 256];
2482  let mut mockvec = io::Cursor::new(vec![]);
2483
2484  let mut reader = if io == 0 {
2485    Left(io::stdin())
2486  } else if io == 1 {
2487    Right(&mockdata[..])
2488  } else {
2489    Middle(&mut mockvec)
2490  };
2491
2492  let mut buf = [0u8; 16];
2493  assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
2494  assert_eq!(&buf, &mockdata[..buf.len()]);
2495
2496  let mut mockbuf = [0u8; 256];
2497  let mut writer = if io == 0 {
2498    Left(io::stdout())
2499  } else if io == 1 {
2500    Right(&mut mockbuf[..])
2501  } else {
2502    Middle(&mut mockvec)
2503  };
2504
2505  let buf = [1u8; 16];
2506  assert_eq!(writer.write(&buf).unwrap(), buf.len());
2507}
2508
2509/// A helper macro to check if AsRef and AsMut are implemented for a given type.
2510macro_rules! check_t {
2511  ($t:ty) => {{
2512    fn check_ref<T: AsRef<$t>>() {}
2513    fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>, T3: AsRef<$t>>() {
2514      check_ref::<Among<T1, T2, T3>>()
2515    }
2516    fn check_mut<T: AsMut<$t>>() {}
2517    fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>, T3: AsMut<$t>>() {
2518      check_mut::<Among<T1, T2, T3>>()
2519    }
2520  }};
2521}
2522
2523// This "unused" method is here to ensure that compilation doesn't fail on given types.
2524fn _unsized_ref_propagation() {
2525  check_t!(str);
2526
2527  fn check_array_ref<T: AsRef<[Item]>, Item>() {}
2528  fn check_array_mut<T: AsMut<[Item]>, Item>() {}
2529
2530  fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, T3: AsRef<[Item]>, Item>() {
2531    check_array_ref::<Among<T1, T2, T3>, _>()
2532  }
2533
2534  fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, T3: AsMut<[Item]>, Item>() {
2535    check_array_mut::<Among<T1, T2, T3>, _>()
2536  }
2537}
2538
2539// This "unused" method is here to ensure that compilation doesn't fail on given types.
2540#[cfg(feature = "std")]
2541fn _unsized_std_propagation() {
2542  check_t!(::std::path::Path);
2543  check_t!(::std::ffi::OsStr);
2544  check_t!(::std::ffi::CStr);
2545}