Skip to main content

either_or_both/either/
mod.rs

1//! The `Either` enum
2
3macro_rules! map_each {
4    ($src:expr) => {
5        match $src {
6            Self::Left(left) => Left(left),
7            Self::Right(left) => Right(left),
8        }
9    };
10}
11
12macro_rules! each {
13    ($src:expr, $( $rest:tt )*) => {
14        match $src {
15            Self::Left(left) => left $($rest)*,
16            Self::Right(right) => right $($rest)*,
17        }
18    };
19    ($src:expr) => {
20        match $src {
21            Self::Left(left) => left,
22            Self::Right(right) => right,
23        }
24    };
25}
26
27pub mod iter;
28pub mod traits;
29
30use core::mem;
31use core::ops::{Deref, DerefMut};
32use core::pin::Pin;
33
34use iter::{InnerIterEither, SwapIterEither};
35use Either::*;
36
37use crate::iter_either::{IterEither, IterMutEither};
38use crate::EitherOrBoth;
39
40/// Represent values with two possibilities. `Either` can be either `Left` or `Right`
41#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43#[cfg_attr(feature = "serde", allow(clippy::unsafe_derive_deserialize))]
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45pub enum Either<L, R = L> {
46    /// Represent a left value
47    Left(L),
48    /// Represent a right value
49    Right(R),
50}
51
52impl<L, R> Either<L, R> {
53    ////////////////////////////////////////////////////////////////////////////////
54    // Boolish
55    ////////////////////////////////////////////////////////////////////////////////
56
57    /// Returns `true` if `Either` is a [`Left`] value.
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// use either_or_both::Either;
63    ///
64    /// let either = Either::<u8>::Left(1);
65    /// assert_eq!(either.is_left(), true);
66    ///
67    /// let either = Either::<u8>::Right(1);
68    /// assert_eq!(either.is_left(), false);
69    /// ```
70    #[must_use = "if you intended to assert that this is a left value, consider `.unwrap_left()` \
71                  instead"]
72    #[inline]
73    pub const fn is_left(&self) -> bool {
74        matches!(self, Self::Left(_))
75    }
76
77    /// Returns `true` if `Either` is [`Left`] and the contained value matches a predicate
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use either_or_both::Either;
83    ///
84    /// let either: Either<u8> = Either::Left(1);
85    /// assert_eq!(either.is_left_and(|l| l == 1), true);
86    ///
87    /// let either: Either<u8> = Either::Left(1);
88    /// assert_eq!(either.is_left_and(|l| l == 2), false);
89    ///
90    /// let either: Either<u8> = Either::Right(1);
91    /// assert_eq!(either.is_left_and(|l| l == 1), false);
92    /// ```
93    #[must_use]
94    #[inline]
95    pub fn is_left_and<F>(self, f: F) -> bool
96    where
97        F: FnOnce(L) -> bool,
98    {
99        match self {
100            Self::Left(left) => f(left),
101            Self::Right(_) => false,
102        }
103    }
104    /// Returns `true` if `Either` is [`Left`] or the [`Right`] value matches a predicate
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use either_or_both::Either;
110    ///
111    /// let either: Either<u8, char> = Either::Left(1);
112    /// assert_eq!(either.is_left_or(|r| r == 'c'), true);
113    ///
114    /// let either: Either<u8, char> = Either::Right('c');
115    /// assert_eq!(either.is_left_or(|r| r == 'c'), true);
116    ///
117    /// let either: Either<u8, char> = Either::Right('c');
118    /// assert_eq!(either.is_left_or(|r| r == 'm'), false);
119    /// ```
120    #[must_use]
121    #[inline]
122    pub fn is_left_or<F>(self, f: F) -> bool
123    where
124        F: FnOnce(R) -> bool,
125    {
126        match self {
127            Self::Left(_) => true,
128            Self::Right(right) => f(right),
129        }
130    }
131
132    /// Returns `true` if `Either` is a [`Right`] value.
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use either_or_both::Either;
138    ///
139    /// let either = Either::<u8, char>::Right('c');
140    /// assert_eq!(either.is_right(), true);
141    ///
142    /// let either = Either::<u8, char>::Left(1);
143    /// assert_eq!(either.is_right(), false);
144    /// ```
145    #[must_use = "if you intended to assert that this is a right value, consider `.unwrap_right()` \
146                  instead"]
147    #[inline]
148    pub const fn is_right(&self) -> bool {
149        matches!(self, Self::Right(_))
150    }
151
152    /// Returns `true` if `Either` is [`Right`] and the contained value matches a
153    /// predicate
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use either_or_both::Either;
159    ///
160    /// let either: Either<u8, char> = Either::Right('c');
161    /// assert_eq!(either.is_right_and(|r| r == 'c'), true);
162    ///
163    /// let either: Either<u8, char> = Either::Right('c');
164    /// assert_eq!(either.is_right_and(|r| r == 'm'), false);
165    ///
166    /// let either: Either<u8, char> = Either::Left(1);
167    /// assert_eq!(either.is_right_and(|r| r == 'c'), false);
168    /// ```
169    #[must_use]
170    #[inline]
171    pub fn is_right_and<F>(self, f: F) -> bool
172    where
173        F: FnOnce(R) -> bool,
174    {
175        match self {
176            Self::Right(right) => f(right),
177            Self::Left(_) => false,
178        }
179    }
180
181    /// Returns `true` if `Either` is [`Right`] or the [`Left`] value matches a predicate
182    ///
183    /// # Examples
184    ///
185    /// ```
186    /// use either_or_both::Either;
187    ///
188    /// let either: Either<u8, char> = Either::Right('c');
189    /// assert_eq!(either.is_right_or(|l| l == 1), true);
190    ///
191    /// let either: Either<u8, char> = Either::Left(1);
192    /// assert_eq!(either.is_right_or(|l| l == 1), true);
193    ///
194    /// let either: Either<u8, char> = Either::Left(2);
195    /// assert_eq!(either.is_right_or(|l| l == 1), false);
196    /// ```
197    #[must_use]
198    #[inline]
199    pub fn is_right_or<F>(self, f: F) -> bool
200    where
201        F: FnOnce(L) -> bool,
202    {
203        match self {
204            Self::Right(_) => true,
205            Self::Left(left) => f(left),
206        }
207    }
208
209    ////////////////////////////////////////////////////////////////////////////////
210    // As reference conversions
211    ////////////////////////////////////////////////////////////////////////////////
212
213    /// Converts from `&Either<L, R>` to `Either<&L, &R>`.
214    ///
215    /// # Examples
216    ///
217    /// Calculate the length of the [strings] without moving the [`Strings`].
218    ///
219    /// [strings]: String
220    /// [`Strings`]: String
221    ///
222    /// ```
223    /// use either_or_both::Either;
224    ///
225    /// let text: Either<String> = Either::Left("left value".to_owned());
226    ///
227    /// // Cast `Either<String>` to `Either<&String>` and then apply a map consuming the
228    /// // result of `as_ref` instead of `text` itself
229    /// let length: Either<usize> = text.as_ref().map(String::len);
230    /// assert_eq!(length, Either::Left(10));
231    ///
232    /// println!("`text` has not been moved: {:?}", &text);
233    /// ```
234    #[allow(clippy::same_name_method)]
235    #[inline]
236    pub const fn as_ref(&self) -> Either<&L, &R> {
237        map_each!(self)
238    }
239
240    /// Converts from `&mut Either<L, R>` to `Either<&mut L, &mut R>`.
241    ///
242    /// # Examples
243    ///
244    /// ```
245    /// use either_or_both::Either;
246    ///
247    /// let mut either: Either<u8, char> = Either::Left(1);
248    ///
249    /// match either.as_mut() {
250    ///     Either::Left(left) => *left = 3,
251    ///     Either::Right(right) => *right = 'x',
252    /// }
253    ///
254    /// assert_eq!(either, Either::Left(3))
255    /// ```
256    #[allow(clippy::same_name_method)]
257    #[inline]
258    pub fn as_mut(&mut self) -> Either<&mut L, &mut R> {
259        map_each!(self)
260    }
261
262    /// Converts from `Either<L, R>` to `Either<&L::Target, &R::Target>`.
263    ///
264    /// This method keeps the original `Either` unchanged, while creating a new instance
265    /// that holds a reference to the original. It also coerces the inner values
266    /// through the `Deref` trait.
267    ///
268    /// ```
269    /// use either_or_both::Either;
270    ///
271    /// let values: Either<String> = Either::Left("left".to_owned());
272    /// let deref: Either<&str> = values.as_deref();
273    /// assert_eq!(deref.left(), Some("left"));
274    /// ```
275    #[inline]
276    pub fn as_deref(&self) -> Either<&<L as Deref>::Target, &<R as Deref>::Target>
277    where
278        L: Deref,
279        R: Deref,
280    {
281        self.as_ref().bimap(|l| &**l, |r| &**r)
282    }
283
284    /// Converts from `Either<L, R>` to `Either<&mut L::Target, &mut R::Target>`.
285    ///
286    /// This method keeps the original `Either` unchanged, while creating a new instance
287    /// that holds a mutable reference to the inner type's [`Deref::Target`] type.
288    ///
289    /// ```
290    /// use either_or_both::Either;
291    ///
292    /// let mut value: Either<String> = Either::Left("left".to_owned());
293    /// let upper_case: Either<&mut str> = value.as_deref_mut().map(|v| {
294    ///     v.make_ascii_uppercase();
295    ///     v
296    /// });
297    ///
298    /// assert_eq!(upper_case.left(), Some("LEFT".to_owned().as_mut_str()));
299    /// ```
300    #[inline]
301    pub fn as_deref_mut(&mut self) -> Either<&mut <L as Deref>::Target, &mut <R as Deref>::Target>
302    where
303        L: DerefMut,
304        R: DerefMut,
305    {
306        self.as_mut().bimap(|l| &mut **l, |r| &mut **r)
307    }
308
309    /// Converts from `Pin<&Either<L, R>>` to `Either<Pin<&L>, Pin<&R>>`.
310    #[must_use]
311    #[inline]
312    pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>> {
313        // SAFETY: `x` is guaranteed to be pinned because it comes from `self` which is pinned.
314        unsafe {
315            match Pin::get_ref(self) {
316                Self::Left(left) => Left(Pin::new_unchecked(left)),
317                Self::Right(right) => Right(Pin::new_unchecked(right)),
318            }
319        }
320    }
321
322    /// Converts from `Pin<&mut Either<L, R>>` to `Either<Pin<&mut L>, Pin<&mut R>>`.
323    #[must_use]
324    #[inline]
325    pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>> {
326        // SAFETY: `x` is guaranteed to be pinned because it comes from `self` which is pinned.
327        unsafe {
328            match Pin::get_unchecked_mut(self) {
329                Self::Left(left) => Left(Pin::new_unchecked(left)),
330                Self::Right(right) => Right(Pin::new_unchecked(right)),
331            }
332        }
333    }
334
335    ////////////////////////////////////////////////////////////////////////////////
336    // Unwrapping the contained values
337    ////////////////////////////////////////////////////////////////////////////////
338
339    /// Returns the contained left value consuming `self`.
340    ///
341    /// # Panics
342    ///
343    /// Panics with a custom panic message provided by `msg` if there is no left value
344    /// present
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// use either_or_both::Either;
350    ///
351    /// let value: Either<&str> = Either::Left("left");
352    /// assert_eq!(value.expect_left("should be left"), "left");
353    /// ```
354    ///
355    /// This example panics with the message `should be left`
356    ///
357    /// ```should_panic
358    /// use either_or_both::Either;
359    ///
360    /// let value: Either<&str> = Either::Right("right");
361    /// value.expect_left("should be left");
362    /// ```
363    #[track_caller]
364    #[inline]
365    pub fn expect_left(self, msg: &str) -> L {
366        match self {
367            Self::Left(left) => left,
368            Self::Right(_) => {
369                panic!("{msg}");
370            }
371        }
372    }
373
374    /// Returns the contained right value consuming `self`.
375    ///
376    /// # Panics
377    ///
378    /// Panics with a custom panic message provided by `msg` if there is no right value
379    /// present
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use either_or_both::Either;
385    ///
386    /// let value: Either<&str> = Either::Right("right");
387    /// assert_eq!(value.expect_right("should be right"), "right");
388    /// ```
389    ///
390    /// The following example panics with the message `should be right`
391    ///
392    /// ```should_panic
393    /// use either_or_both::Either;
394    ///
395    /// let value: Either<&str> = Either::Left("left");
396    /// value.expect_right("should be right");
397    /// ```
398    #[track_caller]
399    #[inline]
400    pub fn expect_right(self, msg: &str) -> R {
401        match self {
402            Self::Left(_) => {
403                panic!("{msg}");
404            }
405            Self::Right(right) => right,
406        }
407    }
408
409    /// Returns the contained left value consuming `self`.
410    ///
411    /// # Panics
412    ///
413    /// Panics if `Either` is a [`Right`] variant
414    ///
415    /// # Examples
416    ///
417    /// ```
418    /// use either_or_both::Either;
419    ///
420    /// let value: Either<&str> = Either::Left("left");
421    /// assert_eq!(value.unwrap_left(), "left");
422    /// ```
423    ///
424    /// ```should_panic
425    /// use either_or_both::Either;
426    ///
427    /// let value: Either<&str> = Either::Right("right");
428    /// value.unwrap_left(); // panics
429    /// ```
430    #[track_caller]
431    #[inline]
432    pub fn unwrap_left(self) -> L {
433        self.expect_left("Called `Either::unwrap_left` on a `Right` value")
434    }
435
436    /// Returns the contained left value consuming `self`, without checking that the value
437    /// is not [`Left`].
438    ///
439    /// # SAFETY
440    ///
441    /// Calling this method on a [`Right`] variant is *[undefined behavior]*.
442    ///
443    /// # Examples
444    ///
445    /// ```
446    /// use either_or_both::Either;
447    ///
448    /// let value: Either<&str> = Either::Left("left");
449    /// assert_eq!(unsafe { value.unwrap_left_unchecked() }, "left");
450    /// ```
451    ///
452    /// The following example introduces *[undefined behavior]*
453    ///
454    /// ```no_run
455    /// use either_or_both::Either;
456    ///
457    /// let value: Either<&str> = Either::Right("right");
458    /// assert_eq!(unsafe { value.unwrap_left_unchecked() }, "left");
459    /// ```
460    ///
461    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
462    #[track_caller]
463    #[inline]
464    pub unsafe fn unwrap_left_unchecked(self) -> L {
465        match self {
466            Self::Left(left) => left,
467            // SAFETY: the safety contract must be upheld by the caller.
468            Self::Right(_) => core::hint::unreachable_unchecked(), // cov:excl-line
469        }
470    }
471
472    /// Returns the contained right value consuming `self`.
473    ///
474    /// # Panics
475    ///
476    /// Panics if `Either` is a [`Left`] variant
477    ///
478    /// # Examples
479    ///
480    /// ```
481    /// use either_or_both::Either;
482    ///
483    /// let value: Either<&str> = Either::Right("right");
484    /// assert_eq!(value.unwrap_right(), "right");
485    /// ```
486    ///
487    /// ```should_panic
488    /// use either_or_both::Either;
489    ///
490    /// let value: Either<&str> = Either::Left("left");
491    /// value.unwrap_right(); // panics
492    /// ```
493    #[track_caller]
494    #[inline]
495    pub fn unwrap_right(self) -> R {
496        self.expect_right("Called `Either::unwrap_right` on a `Left` value")
497    }
498
499    /// Returns the contained right value consuming `self`, without checking that the
500    /// value is not [`Right`].
501    ///
502    /// # SAFETY
503    ///
504    /// Calling this method on a [`Left`] variant is *[undefined behavior]*.
505    ///
506    /// # Examples
507    ///
508    /// ```
509    /// use either_or_both::Either;
510    ///
511    /// let value: Either<&str> = Either::Right("right");
512    /// assert_eq!(unsafe { value.unwrap_right_unchecked() }, "right");
513    /// ```
514    ///
515    /// The following example introduces *[undefined behavior]*
516    ///
517    /// ```no_run
518    /// use either_or_both::Either;
519    ///
520    /// let value: Either<&str> = Either::Left("left");
521    /// assert_eq!(unsafe { value.unwrap_right_unchecked() }, "right");
522    /// ```
523    ///
524    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
525    #[track_caller]
526    #[inline]
527    pub unsafe fn unwrap_right_unchecked(self) -> R {
528        match self {
529            // SAFETY: the safety contract must be upheld by the caller.
530            Self::Left(_) => core::hint::unreachable_unchecked(), // cov:excl-line
531            Self::Right(right) => right,
532        }
533    }
534
535    ////////////////////////////////////////////////////////////////////////////////
536    // Getting the contained values
537    ////////////////////////////////////////////////////////////////////////////////
538
539    /// If a left value is present, return `Some` containing the value otherwise return
540    /// `None`.
541    ///
542    /// # Examples
543    ///
544    /// ```
545    /// use either_or_both::Either;
546    ///
547    /// let value: Either<u8, char> = Either::Left(1);
548    /// assert_eq!(value.left(), Some(1));
549    ///
550    /// let value: Either<u8, char> = Either::Right('c');
551    /// assert_eq!(value.left(), None);
552    /// ```
553    #[inline]
554    pub fn left(self) -> Option<L> {
555        match self {
556            Self::Left(left) => Some(left),
557            Self::Right(_) => None,
558        }
559    }
560
561    /// Returns [`Right`] if the `Either` is [`Right`] otherwise returns `other`.
562    ///
563    /// The `left_and` combinator eagerly evaluates its arguments, which can result in
564    /// unnecessary computations. When chaining operations that involve function
565    /// calls, use [`left_and_then`] instead. It evaluates the function lazily.
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// use either_or_both::Either;
571    ///
572    /// let x: Either<u8, char> = Either::Left(1);
573    /// let y: Either<&str, char> = Either::Left("left");
574    /// assert_eq!(x.left_and(y), Either::Left("left"));
575    ///
576    /// let x: Either<u8, char> = Either::Right('c');
577    /// let y: Either<&str, char> = Either::Left("left");
578    /// assert_eq!(x.left_and(y), Either::Right('c'));
579    /// ```
580    ///
581    /// [`left_and_then`]: Either::left_and_then
582    #[inline]
583    #[must_use]
584    pub fn left_and<T>(self, other: Either<T, R>) -> Either<T, R> {
585        match self {
586            Self::Left(_) => other,
587            Self::Right(right) => Right(right),
588        }
589    }
590
591    /// Returns [`Right`] otherwise calls `f` with the left value and returns the result.
592    ///
593    /// # Examples
594    ///
595    /// ```
596    /// use either_or_both::Either;
597    ///
598    /// fn left_to_string(x: u8) -> Either<String, char> {
599    ///     Either::Left(x.to_string())
600    /// }
601    ///
602    /// let x: Either<u8, char> = Either::Left(1);
603    /// assert_eq!(x.left_and_then(left_to_string), Either::Left(1.to_string()));
604    ///
605    /// let x: Either<u8, char> = Either::Right('c');
606    /// assert_eq!(x.left_and_then(left_to_string), Either::Right('c'));
607    /// ```
608    #[inline]
609    #[must_use]
610    pub fn left_and_then<F, T>(self, f: F) -> Either<T, R>
611    where
612        F: FnOnce(L) -> Either<T, R>,
613    {
614        match self {
615            Self::Left(left) => f(left),
616            Self::Right(right) => Right(right),
617        }
618    }
619
620    /// If a left value is present, return `Some` containing the value otherwise return
621    /// `None`.
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// use either_or_both::Either;
627    ///
628    /// let value: Either<u8, char> = Either::Right('c');
629    /// assert_eq!(value.right(), Some('c'));
630    ///
631    /// let value: Either<u8, char> = Either::Left(1);
632    /// assert_eq!(value.right(), None);
633    /// ```
634    #[inline]
635    pub fn right(self) -> Option<R> {
636        match self {
637            Self::Left(_) => None,
638            Self::Right(right) => Some(right),
639        }
640    }
641
642    /// Returns [`Left`] if the `Either` is [`Left`] otherwise returns `other`.
643    ///
644    /// The `right_and` combinator eagerly evaluates its arguments, which can result in
645    /// unnecessary computations. When chaining operations that involve function
646    /// calls, use [`right_and_then`] instead. It evaluates the function lazily.
647    ///
648    /// # Examples
649    ///
650    /// ```
651    /// use either_or_both::Either;
652    ///
653    /// let x: Either<u8, char> = Either::Right('c');
654    /// let y: Either<u8, &str> = Either::Right("right");
655    /// assert_eq!(x.right_and(y), Either::Right("right"));
656    ///
657    /// let x: Either<u8, char> = Either::Left(1);
658    /// let y: Either<u8, &str> = Either::Right("right");
659    /// assert_eq!(x.right_and(y), Either::Left(1));
660    /// ```
661    ///
662    /// [`right_and_then`]: Either::right_and_then
663    #[inline]
664    #[must_use]
665    pub fn right_and<T>(self, other: Either<L, T>) -> Either<L, T> {
666        match self {
667            Self::Left(left) => Left(left),
668            Self::Right(_) => other,
669        }
670    }
671
672    /// Returns [`Left`] otherwise calls `f` with the right value and returns the result.
673    ///
674    /// # Examples
675    ///
676    /// ```
677    /// use either_or_both::Either;
678    ///
679    /// fn right_to_string(x: char) -> Either<u8, String> {
680    ///     Either::Right(x.to_string())
681    /// }
682    ///
683    /// let x: Either<u8, char> = Either::Right('c');
684    /// assert_eq!(
685    ///     x.right_and_then(right_to_string),
686    ///     Either::Right('c'.to_string())
687    /// );
688    ///
689    /// let x: Either<u8, char> = Either::Left(1);
690    /// assert_eq!(x.right_and_then(right_to_string), Either::Left(1));
691    /// ```
692    #[inline]
693    #[must_use]
694    pub fn right_and_then<F, T>(self, f: F) -> Either<L, T>
695    where
696        F: FnOnce(R) -> Either<L, T>,
697    {
698        match self {
699            Self::Left(left) => Left(left),
700            Self::Right(right) => f(right),
701        }
702    }
703
704    ////////////////////////////////////////////////////////////////////////////////
705    // Iterators
706    ////////////////////////////////////////////////////////////////////////////////
707
708    /// Consumes the inner iterators and returns an iterator that yields items of type
709    /// `Either<L, R>`.
710    ///
711    ///
712    /// This iterator allows traversing inner iterators with different types
713    ///
714    /// # Examples
715    ///
716    /// ```
717    /// use either_or_both::Either;
718    ///
719    /// let x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
720    /// let mut iter = x.into_iter_swap(); // moves `x` and the iterators
721    ///
722    /// assert_eq!(iter.next(), Some(Either::Left(1)));
723    /// assert_eq!(iter.next(), Some(Either::Left(2)));
724    /// assert_eq!(iter.next(), None);
725    /// ```
726    pub fn into_iter_swap(
727        self,
728    ) -> SwapIterEither<<L as IntoIterator>::IntoIter, <R as IntoIterator>::IntoIter>
729    where
730        L: IntoIterator,
731        R: IntoIterator,
732    {
733        SwapIterEither::new(self.bimap(IntoIterator::into_iter, IntoIterator::into_iter))
734    }
735
736    /// Borrow the inner iterators and returns an iterator that yields items of type
737    /// `Either<&L, &R>`.
738    ///
739    /// This iterator allows traversing inner iterators with different types
740    ///
741    /// # Examples
742    ///
743    /// ```
744    /// use either_or_both::Either;
745    ///
746    /// let x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
747    /// let mut iter = x.iter_swap();
748    ///
749    /// assert_eq!(iter.next(), Some(Either::Left(&1)));
750    /// assert_eq!(iter.next(), Some(Either::Left(&2)));
751    /// assert_eq!(iter.next(), None);
752    ///
753    /// println!("{x:?}"); // still can access `x`
754    /// ```
755    pub fn iter_swap(
756        &self,
757    ) -> SwapIterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter>
758    where
759        for<'a> &'a L: IntoIterator,
760        for<'a> &'a R: IntoIterator,
761    {
762        SwapIterEither::new(
763            self.as_ref()
764                .bimap(IntoIterator::into_iter, IntoIterator::into_iter),
765        )
766    }
767
768    /// Mutably borrows the inner iterators returning an iterator that yields items of
769    /// type `Either<&mut L, &mut R>`.
770    ///
771    /// This iterator allows traversing inner iterators with different types
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// use either_or_both::Either;
777    ///
778    /// let mut x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
779    /// let mut iter = x.iter_swap_mut();
780    ///
781    /// assert_eq!(iter.next(), Some(Either::Left(&mut 1)));
782    /// assert_eq!(iter.next(), Some(Either::Left(&mut 2)));
783    /// assert_eq!(iter.next(), None);
784    ///
785    /// println!("{x:?}"); // still can access `x`
786    /// ```
787    pub fn iter_swap_mut(
788        &mut self,
789    ) -> SwapIterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter>
790    where
791        for<'a> &'a mut L: IntoIterator,
792        for<'a> &'a mut R: IntoIterator,
793    {
794        SwapIterEither::new(
795            self.as_mut()
796                .bimap(IntoIterator::into_iter, IntoIterator::into_iter),
797        )
798    }
799
800    ////////////////////////////////////////////////////////////////////////////////
801    // Conversions
802    ////////////////////////////////////////////////////////////////////////////////
803
804    /// Converts `Either<L, R>` to `Either<R, L>`.
805    ///
806    /// # Examples
807    ///
808    /// ```
809    /// use either_or_both::Either;
810    ///
811    /// let value: Either<u8, char> = Either::Left(1);
812    /// assert_eq!(value.flip(), Either::Right(1));
813    ///
814    /// let value: Either<u8, char> = Either::Right('c');
815    /// assert_eq!(value.flip(), Either::Left('c'));
816    /// ```
817    #[inline]
818    #[must_use]
819    pub fn flip(self) -> Either<R, L> {
820        match self {
821            Self::Left(left) => Right(left),
822            Self::Right(right) => Left(right),
823        }
824    }
825
826    /// Applies mapping functions to the left and right values returning an `Either<T,
827    /// U>`.
828    ///
829    /// # Examples
830    ///
831    /// ```
832    /// use either_or_both::Either;
833    ///
834    /// let map_left = |left: u8| left.to_string();
835    /// let map_right = |right: char| right as i32;
836    ///
837    /// let value: Either<u8, char> = Either::Left(1);
838    /// assert_eq!(
839    ///     value.bimap(map_left, map_right),
840    ///     Either::Left("1".to_owned())
841    /// );
842    ///
843    /// let value: Either<u8, char> = Either::Right('c');
844    /// assert_eq!(value.bimap(map_left, map_right), Either::Right(99));
845    /// ```
846    #[inline]
847    pub fn bimap<F, G, T, U>(self, f: F, g: G) -> Either<T, U>
848    where
849        F: FnOnce(L) -> T,
850        G: FnOnce(R) -> U,
851    {
852        match self {
853            Self::Left(left) => Left(f(left)),
854            Self::Right(right) => Right(g(right)),
855        }
856    }
857
858    /// Applies a mapping function to the left value returning an `Either<T, R>`.
859    ///
860    /// # Examples
861    ///
862    /// ```
863    /// use either_or_both::Either;
864    ///
865    /// let map_left = |left: u8| left.to_string();
866    ///
867    /// let value: Either<u8, char> = Either::Left(1);
868    /// assert_eq!(value.map_left(map_left), Either::Left("1".to_owned()));
869    ///
870    /// let value: Either<u8, char> = Either::Right('c');
871    /// assert_eq!(value.map_left(map_left), Either::Right('c'));
872    /// ```
873    #[inline]
874    pub fn map_left<F, T>(self, f: F) -> Either<T, R>
875    where
876        F: FnOnce(L) -> T,
877    {
878        match self {
879            Self::Left(left) => Left(f(left)),
880            Self::Right(right) => Right(right),
881        }
882    }
883
884    /// Returns the provided default value if this is a [`Right`] or applies a mapping
885    /// function to the contained left value.
886    ///
887    /// The `map_left_or` combinator eagerly evaluates its arguments, which can result in
888    /// unnecessary computations. When chaining operations that involve function calls,
889    /// use [`map_left_or_else`] instead. It evaluates the function lazily.
890    ///
891    /// # Examples
892    ///
893    /// ```
894    /// use either_or_both::Either;
895    ///
896    /// let map_left = |left: u8| left as u64 + 1;
897    ///
898    /// let value: Either<u8, char> = Either::Right('c');
899    /// assert_eq!(value.map_left_or(42, map_left), 42u64);
900    ///
901    /// let value: Either<u8, char> = Either::Left(1);
902    /// assert_eq!(value.map_left_or(42, map_left), 2u64);
903    /// ```
904    ///
905    /// [`map_left_or_else`]: Either::map_left_or_else
906    #[inline]
907    pub fn map_left_or<F, T>(self, default: T, f: F) -> T
908    where
909        F: FnOnce(L) -> T,
910    {
911        self.map_left_or_else(|| default, f)
912    }
913
914    /// Applies the given function to the left value , mapping `L` to `T` otherwise
915    /// returns the [default value] for type `T`.
916    ///
917    /// # Examples
918    ///
919    /// ```
920    /// use either_or_both::Either;
921    ///
922    /// let map_left = |left: u8| left as u64 + 1;
923    ///
924    /// let value: Either<u8, char> = Either::Right('c');
925    /// assert_eq!(value.map_left_or_default(map_left), 0u64);
926    ///
927    /// let value: Either<u8, char> = Either::Left(1);
928    /// assert_eq!(value.map_left_or_default(map_left), 2u64);
929    /// ```
930    ///
931    /// [default value]: Default::default
932    #[inline]
933    pub fn map_left_or_default<F, T>(self, f: F) -> T
934    where
935        F: FnOnce(L) -> T,
936        T: Default,
937    {
938        self.map_left_or_else(T::default, f)
939    }
940
941    /// Applies the given function to the left value, mapping `L` to `T` otherwise applies
942    /// a different function.
943    ///
944    /// # Examples
945    ///
946    /// ```
947    /// use either_or_both::Either;
948    ///
949    /// let map_left = |left: u8| left.to_string();
950    ///
951    /// let value: Either<u8, char> = Either::Right('c');
952    /// assert_eq!(
953    ///     value.map_left_or_else(|| String::from("left"), map_left),
954    ///     String::from("left")
955    /// );
956    ///
957    /// let value: Either<u8, char> = Either::Left(1);
958    /// assert_eq!(
959    ///     value.map_left_or_else(|| String::from("left"), map_left),
960    ///     1.to_string()
961    /// );
962    /// ```
963    #[inline]
964    pub fn map_left_or_else<D, F, T>(self, default: D, f: F) -> T
965    where
966        F: FnOnce(L) -> T,
967        D: FnOnce() -> T,
968    {
969        match self {
970            Self::Left(left) => f(left),
971            Self::Right(_) => default(),
972        }
973    }
974
975    /// Applies a mapping function to the right value returning an `Either<L, T>`.
976    ///
977    /// # Examples
978    ///
979    /// ```
980    /// use either_or_both::Either;
981    ///
982    /// let map_right = |right: char| right.to_string();
983    ///
984    /// let value: Either<u8, char> = Either::Right('c');
985    /// assert_eq!(value.map_right(map_right), Either::Right("c".to_owned()));
986    ///
987    /// let value: Either<u8, char> = Either::Left(1);
988    /// assert_eq!(value.map_right(map_right), Either::Left(1));
989    /// ```
990    #[inline]
991    pub fn map_right<F, T>(self, f: F) -> Either<L, T>
992    where
993        F: FnOnce(R) -> T,
994    {
995        match self {
996            Self::Left(left) => Left(left),
997            Self::Right(right) => Right(f(right)),
998        }
999    }
1000
1001    /// Returns the provided default value if this is a [`Left`] or applies a mapping
1002    /// function to the contained right value.
1003    ///
1004    /// The `map_right_or` combinator eagerly evaluates its arguments, which can result in
1005    /// unnecessary computations. When chaining operations that involve function calls,
1006    /// use [`map_right_or_else`] instead. It evaluates the function lazily.
1007    ///
1008    /// # Examples
1009    ///
1010    /// ```
1011    /// use either_or_both::Either;
1012    ///
1013    /// let map_right = |right: char| right as i32;
1014    ///
1015    /// let value: Either<u8, char> = Either::Right('c');
1016    /// assert_eq!(value.map_right_or(42, map_right), 99i32);
1017    ///
1018    /// let value: Either<u8, char> = Either::Left(1);
1019    /// assert_eq!(value.map_right_or(42, map_right), 42i32);
1020    /// ```
1021    ///
1022    /// [`map_right_or_else`]: Either::map_right_or_else
1023    #[inline]
1024    #[must_use]
1025    pub fn map_right_or<F, T>(self, default: T, f: F) -> T
1026    where
1027        F: FnOnce(R) -> T,
1028    {
1029        self.map_right_or_else(|| default, f)
1030    }
1031
1032    /// Applies the given function to the right value, mapping `R` to `T` otherwise
1033    /// returns the [default value] for type `T`.
1034    ///
1035    /// # Examples
1036    ///
1037    /// ```
1038    /// use either_or_both::Either;
1039    ///
1040    /// let map_right = |right: char| right as u64 + 1;
1041    ///
1042    /// let value: Either<u8, char> = Either::Right('c');
1043    /// assert_eq!(value.map_right_or_default(map_right), 100u64);
1044    ///
1045    /// let value: Either<u8, char> = Either::Left(1);
1046    /// assert_eq!(value.map_right_or_default(map_right), 0u64);
1047    /// ```
1048    ///
1049    /// [default value]: Default::default
1050    #[inline]
1051    pub fn map_right_or_default<F, T>(self, f: F) -> T
1052    where
1053        F: FnOnce(R) -> T,
1054        T: Default,
1055    {
1056        self.map_right_or_else(T::default, f)
1057    }
1058
1059    /// Applies the given function to the right value, mapping `R` to `T` otherwise
1060    /// applies a different function.
1061    ///
1062    /// # Examples
1063    ///
1064    /// ```
1065    /// use either_or_both::Either;
1066    ///
1067    /// let map_right = |right: char| right.to_string();
1068    ///
1069    /// let value: Either<u8, char> = Either::Right('c');
1070    /// assert_eq!(
1071    ///     value.map_right_or_else(|| String::from("right"), map_right),
1072    ///     "c".to_owned()
1073    /// );
1074    ///
1075    /// let value: Either<u8, char> = Either::Left(1);
1076    /// assert_eq!(
1077    ///     value.map_right_or_else(|| String::from("right"), map_right),
1078    ///     String::from("right")
1079    /// );
1080    /// ```
1081    #[inline]
1082    pub fn map_right_or_else<D, F, T>(self, default: D, f: F) -> T
1083    where
1084        F: FnOnce(R) -> T,
1085        D: FnOnce() -> T,
1086    {
1087        match self {
1088            Self::Left(_) => default(),
1089            Self::Right(right) => f(right),
1090        }
1091    }
1092
1093    /// Calls functions with a reference to the contained values returning the original
1094    /// `Either`.
1095    ///
1096    /// # Examples
1097    ///
1098    /// ```
1099    /// use either_or_both::Either;
1100    ///
1101    /// // Prints a single line with "Left is: 1"
1102    /// let value: Either<u8, char> = Either::Left(1);
1103    /// let left = value
1104    ///     .biinspect(|l| println!("Left is: {l}"), |r| println!("Right is: {r}"))
1105    ///     .expect_left("should be a left value");
1106    /// assert_eq!(left, 1);
1107    ///
1108    /// // Prints a single line with "Right is: c"
1109    /// let value: Either<u8, char> = Either::Right('c');
1110    /// let right = value
1111    ///     .biinspect(|l| println!("Left is: {l}"), |r| println!("Right is: {r}"))
1112    ///     .expect_right("should be a right value");
1113    /// assert_eq!(right, 'c');
1114    /// ```
1115    #[inline]
1116    #[must_use]
1117    pub fn biinspect<F, G>(self, f: F, g: G) -> Self
1118    where
1119        for<'a> F: Fn(&'a L),
1120        for<'a> G: Fn(&'a R),
1121    {
1122        match &self {
1123            Self::Left(left) => f(left),
1124            Self::Right(right) => g(right),
1125        }
1126        self
1127    }
1128
1129    /// Calls a function with a reference to the contained left value returning the
1130    /// original `Either`.
1131    ///
1132    /// # Examples
1133    ///
1134    /// ```
1135    /// use either_or_both::Either;
1136    ///
1137    /// // Prints a single line with "Left is: 1"
1138    /// let value: Either<u8, char> = Either::Left(1);
1139    /// let left = value
1140    ///     .inspect_left(|l| println!("Left is: {l}"))
1141    ///     .expect_left("should be a left value");
1142    /// assert_eq!(left, 1);
1143    ///
1144    /// // Prints nothing
1145    /// let value: Either<u8, char> = Either::Right('c');
1146    /// let right = value
1147    ///     .inspect_left(|l| println!("Left is: {l}"))
1148    ///     .expect_right("should be a right value");
1149    /// assert_eq!(right, 'c');
1150    /// ```
1151    #[inline]
1152    #[must_use]
1153    pub fn inspect_left<F>(self, f: F) -> Self
1154    where
1155        for<'a> F: Fn(&'a L),
1156    {
1157        match &self {
1158            Self::Left(left) => f(left),
1159            Self::Right(_) => {}
1160        }
1161        self
1162    }
1163
1164    /// Calls a function with a reference to the contained right value returning the
1165    /// original `Either`.
1166    ///
1167    /// # Examples
1168    ///
1169    /// ```
1170    /// use either_or_both::Either;
1171    ///
1172    /// // Prints a single line with "Right is: c"
1173    /// let value: Either<u8, char> = Either::Right('c');
1174    /// let right = value
1175    ///     .inspect_right(|r| println!("Right is: {r}"))
1176    ///     .expect_right("should be a right value");
1177    /// assert_eq!(right, 'c');
1178    ///
1179    /// // Prints nothing
1180    /// let value: Either<u8, char> = Either::Left(1);
1181    /// let left = value
1182    ///     .inspect_right(|r| println!("Right is: {r}"))
1183    ///     .expect_left("should be a left value");
1184    /// assert_eq!(left, 1);
1185    /// ```
1186    #[inline]
1187    #[must_use]
1188    pub fn inspect_right<F>(self, f: F) -> Self
1189    where
1190        for<'a> F: Fn(&'a R),
1191    {
1192        match &self {
1193            Self::Left(_) => {}
1194            Self::Right(right) => f(right),
1195        }
1196        self
1197    }
1198
1199    /// Consumes this `Either` applying functions to the contained values taking mutable
1200    /// references to capture variables.
1201    ///
1202    /// # Examples
1203    ///
1204    /// ```
1205    /// use either_or_both::Either;
1206    ///
1207    /// let mut left = vec![];
1208    /// let mut right = vec![];
1209    ///
1210    /// let value: Either<u8, char> = Either::Left(1);
1211    /// value.biapply(|l| left.push(l), |r| right.push(r)); // moves `value`
1212    ///
1213    /// assert_eq!(left, vec![1]);
1214    /// ```
1215    ///
1216    /// The following example will not compile with the error: "cannot borrow `both` as mutable
1217    /// more than once at a time".
1218    ///
1219    /// If you need to apply a function that requires mutable access a single element
1220    /// simultaneously, consider using [`biapply_with`] instead.
1221    ///
1222    /// ```compile_fail
1223    /// use either_or_both::Either;
1224    ///
1225    /// let mut both = vec![];
1226    ///
1227    /// let value: Either<u8, char> = Either::Left(1);
1228    /// value.biapply(|l| both.push(l), |r| both.push(r as u8));
1229    /// ```
1230    ///
1231    /// [`biapply_with`]: Either::biapply_with
1232    #[inline]
1233    pub fn biapply<F, G>(self, mut f: F, mut g: G)
1234    where
1235        F: FnMut(L),
1236        G: FnMut(R),
1237    {
1238        match self {
1239            Self::Left(left) => f(left),
1240            Self::Right(right) => g(right),
1241        }
1242    }
1243
1244    /// Consumes this `Either` applying functions to the contained values and a given
1245    /// accumulator.
1246    ///
1247    /// # Examples
1248    ///
1249    /// ```
1250    /// use either_or_both::Either;
1251    ///
1252    /// let mut both = vec![];
1253    ///
1254    /// let value: Either<u8, char> = Either::Left(1);
1255    /// value.biapply_with(&mut both, |acc, l| acc.push(l), |acc, r| acc.push(r as u8));
1256    ///
1257    /// let value: Either<u8, char> = Either::Right('c');
1258    /// value.biapply_with(&mut both, |acc, l| acc.push(l), |acc, r| acc.push(r as u8));
1259    ///
1260    /// assert_eq!(both, vec![1, 99]);
1261    /// ```
1262    ///
1263    /// [`flip`]: Either::flip
1264    #[inline]
1265    pub fn biapply_with<F, G, Acc>(self, acc: Acc, mut f: F, mut g: G)
1266    where
1267        F: FnMut(Acc, L),
1268        G: FnMut(Acc, R),
1269    {
1270        match self {
1271            Self::Left(left) => f(acc, left),
1272            Self::Right(right) => g(acc, right),
1273        }
1274    }
1275
1276    /// Consumes this `Either` applying a function to the contained left value.
1277    ///
1278    /// # Examples
1279    ///
1280    /// ```
1281    /// use either_or_both::Either;
1282    ///
1283    /// let mut left = vec![];
1284    /// let value: Either<u8, char> = Either::Left(1);
1285    /// value.apply_left(|l| left.push(l));
1286    /// assert_eq!(left, vec![1]);
1287    ///
1288    /// let mut left = vec![];
1289    /// let value: Either<u8, char> = Either::Right('c');
1290    /// value.apply_left(|l| left.push(l));
1291    /// assert_eq!(left.is_empty(), true);
1292    /// ```
1293    #[inline]
1294    pub fn apply_left<F>(self, mut f: F)
1295    where
1296        F: FnMut(L),
1297    {
1298        match self {
1299            Self::Left(left) => f(left),
1300            Self::Right(_) => {}
1301        }
1302    }
1303
1304    /// Consumes this `Either` applying a function to the contained right value.
1305    ///
1306    /// # Examples
1307    ///
1308    /// ```
1309    /// use either_or_both::Either;
1310    ///
1311    /// let mut right = vec![];
1312    /// let value: Either<u8, char> = Either::Right('c');
1313    /// value.apply_right(|r| right.push(r));
1314    /// assert_eq!(right, vec!['c']);
1315    ///
1316    /// let mut right = vec![];
1317    /// let value: Either<u8, char> = Either::Left(1);
1318    /// value.apply_right(|r| right.push(r));
1319    /// assert_eq!(right.is_empty(), true);
1320    /// ```
1321    #[inline]
1322    pub fn apply_right<F>(self, mut f: F)
1323    where
1324        F: FnMut(R),
1325    {
1326        match self {
1327            Self::Right(right) => f(right),
1328            Self::Left(_) => {}
1329        }
1330    }
1331
1332    /// Returns the contained values applying a mapping function which converts the `L`
1333    /// and `R` values to a uniform type.
1334    ///
1335    /// # Examples
1336    ///
1337    /// ```
1338    /// use either_or_both::Either;
1339    ///
1340    /// let value: Either<u8, char> = Either::Left(1);
1341    /// assert_eq!(
1342    ///     value.bireduce(|l| l.to_string(), |r| r.to_string()),
1343    ///     "1".to_owned()
1344    /// );
1345    ///
1346    /// let value: Either<u8, char> = Either::Right('c');
1347    /// assert_eq!(
1348    ///     value.bireduce(|l| l.to_string(), |r| r.to_string()),
1349    ///     "c".to_owned()
1350    /// );
1351    /// ```
1352    #[inline]
1353    #[must_use]
1354    pub fn bireduce<F, G, T>(self, f: F, g: G) -> T
1355    where
1356        F: FnOnce(L) -> T,
1357        G: FnOnce(R) -> T,
1358    {
1359        match self {
1360            Self::Left(left) => f(left),
1361            Self::Right(right) => g(right),
1362        }
1363    }
1364
1365    /// Returns the left value otherwise applies a function to a [`Right`] variant,
1366    /// converting it into an `L` value.
1367    ///
1368    /// # Example
1369    ///
1370    /// ```
1371    /// use either_or_both::Either;
1372    ///
1373    /// let value: Either<u8, char> = Either::Right('c');
1374    /// assert_eq!(value.reduce_left(|r| r as u8), 99);
1375    ///
1376    /// let value: Either<u8, char> = Either::Left(1);
1377    /// assert_eq!(value.reduce_left(|r| r as u8), 1);
1378    /// ```
1379    #[inline]
1380    #[must_use]
1381    pub fn reduce_left<F>(self, f: F) -> L
1382    where
1383        F: FnOnce(R) -> L,
1384    {
1385        match self {
1386            Self::Left(left) => left,
1387            Self::Right(right) => f(right),
1388        }
1389    }
1390
1391    /// Returns the right value otherwise applies a function to a [`Left`] variant,
1392    /// converting it into an `R` value.
1393    ///
1394    /// # Examples
1395    ///
1396    /// ```
1397    /// use either_or_both::Either;
1398    ///
1399    /// let value: Either<u8, char> = Either::Right('c');
1400    /// assert_eq!(value.reduce_right(|l| l as char), 'c');
1401    ///
1402    /// let value: Either<u8, char> = Either::Left(0);
1403    /// assert_eq!(value.reduce_right(|l| l as char), '\0');
1404    /// ```
1405    #[inline]
1406    #[must_use]
1407    pub fn reduce_right<F>(self, f: F) -> R
1408    where
1409        F: FnOnce(L) -> R,
1410    {
1411        match self {
1412            Self::Left(left) => f(left),
1413            Self::Right(right) => right,
1414        }
1415    }
1416
1417    /// Transforms the `Either<L, R>` into a `Result<R, L>`.
1418    ///
1419    /// Following the [convention], the left value represents an error and a right value
1420    /// represents a correct value.
1421    ///
1422    /// # Examples
1423    ///
1424    /// ```
1425    /// use either_or_both::Either;
1426    ///
1427    /// let value: Either<&str, u8> = Either::Right(1);
1428    /// assert_eq!(value.ok(), Ok(1));
1429    ///
1430    /// let value: Either<&str, u8> = Either::Left("this is an error");
1431    /// assert_eq!(value.ok(), Err("this is an error"));
1432    /// ```
1433    ///
1434    /// [convention]: ./index.html#conventions-and-edge-cases
1435    #[allow(clippy::missing_errors_doc)]
1436    #[inline]
1437    pub fn ok(self) -> Result<R, L> {
1438        match self {
1439            Self::Left(left) => Err(left),
1440            Self::Right(right) => Ok(right),
1441        }
1442    }
1443
1444    /// Transforms the `Either<L, R>` into a `Result<R, L>` using the provided `error` as
1445    /// error value.
1446    ///
1447    /// Following the [convention], the left value represents an error and a right value
1448    /// represents a correct value.
1449    ///
1450    /// The `ok_or` combinator eagerly evaluates its arguments, which can result in
1451    /// unnecessary computations. When chaining operations that involve function
1452    /// calls, use [`ok_or_else`] instead. It evaluates the function lazily.
1453    ///
1454    /// # Examples
1455    ///
1456    /// ```
1457    /// use either_or_both::Either;
1458    ///
1459    /// let value: Either<u8, char> = Either::Right('c');
1460    /// assert_eq!(value.ok_or("error message"), Ok('c'));
1461    ///
1462    /// let value: Either<u8, char> = Either::Left(1);
1463    /// assert_eq!(value.ok_or("error message"), Err("error message"));
1464    /// ```
1465    ///
1466    /// [`ok_or_else`]: Either::ok_or_else
1467    /// [convention]: ./index.html#conventions-and-edge-cases
1468    #[allow(clippy::missing_errors_doc)]
1469    #[inline]
1470    pub fn ok_or<E>(self, error: E) -> Result<R, E> {
1471        self.ok_or_else(|| error)
1472    }
1473
1474    /// Transforms the `Either<L, R>` into a `Result<R, L>` using the result of an `error`
1475    /// function as error value.
1476    ///
1477    /// Following the [convention], the left value represents an error and a right value
1478    /// represents a correct value.
1479    ///
1480    /// The `ok_or` combinator eagerly evaluates its arguments, which can result in
1481    /// unnecessary computations. When chaining operations that involve function
1482    /// calls, use [`ok_or_else`] instead. It evaluates the function lazily.
1483    ///
1484    /// # Examples
1485    ///
1486    /// ```
1487    /// use either_or_both::Either;
1488    ///
1489    /// let value: Either<u8, char> = Either::Right('c');
1490    /// assert_eq!(value.ok_or_else(|| String::from("error message")), Ok('c'));
1491    ///
1492    /// let value: Either<u8, char> = Either::Left(1);
1493    /// assert_eq!(
1494    ///     value.ok_or_else(|| String::from("error message")),
1495    ///     Err(String::from("error message"))
1496    /// );
1497    /// ```
1498    ///
1499    /// [`ok_or_else`]: Either::ok_or_else
1500    /// [convention]: ./index.html#conventions-and-edge-cases
1501    #[allow(clippy::missing_errors_doc)]
1502    #[inline]
1503    pub fn ok_or_else<F, E>(self, error: F) -> Result<R, E>
1504    where
1505        F: FnOnce() -> E,
1506    {
1507        match self {
1508            Self::Left(_) => Err(error()),
1509            Self::Right(ok) => Ok(ok),
1510        }
1511    }
1512
1513    /// Returns a tuple (L, R) with the provided values filling in any missing left or
1514    /// right value.
1515    ///
1516    /// # Examples
1517    ///
1518    /// ```
1519    /// use either_or_both::Either;
1520    ///
1521    /// let value: Either<u8, char> = Either::Left(1);
1522    /// assert_eq!(value.or(2, 'm'), (1, 'm'));
1523    ///
1524    /// let value: Either<u8, char> = Either::Right('c');
1525    /// assert_eq!(value.or(2, 'm'), (2, 'c'));
1526    /// ```
1527    #[inline]
1528    #[must_use]
1529    pub fn or(self, left: L, right: R) -> (L, R) {
1530        match self {
1531            Self::Left(left) => (left, right),
1532            Self::Right(right) => (left, right),
1533        }
1534    }
1535
1536    /// Returns a tuple (L, R) where any missing left or right value is replaced with its
1537    /// respective default value.
1538    ///
1539    /// # Examples
1540    ///
1541    /// ```
1542    /// use either_or_both::Either;
1543    ///
1544    /// let value: Either<u8, char> = Either::Left(1);
1545    /// assert_eq!(value.or_default(), (1, '\0'));
1546    ///
1547    /// let value: Either<u8, char> = Either::Right('c');
1548    /// assert_eq!(value.or_default(), (0, 'c'));
1549    /// ```
1550    #[inline]
1551    pub fn or_default(self) -> (L, R)
1552    where
1553        L: Default,
1554        R: Default,
1555    {
1556        match self {
1557            Self::Left(left) => (left, R::default()),
1558            Self::Right(right) => (L::default(), right),
1559        }
1560    }
1561
1562    /// Returns a tuple (L, R) where any missing left or right value is computed with the
1563    /// given functions.
1564    ///
1565    /// # Examples
1566    ///
1567    /// ```
1568    /// use either_or_both::Either;
1569    ///
1570    /// let value: Either<u8, char> = Either::Left(1);
1571    /// assert_eq!(value.or_else(|| 1 + 1, || char::from(100)), (1, 'd'));
1572    ///
1573    /// let value: Either<u8, char> = Either::Right('c');
1574    /// assert_eq!(value.or_else(|| 1 + 1, || char::from(100)), (2, 'c'));
1575    /// ```
1576    #[inline]
1577    pub fn or_else<F, G>(self, f: F, g: G) -> (L, R)
1578    where
1579        F: FnOnce() -> L,
1580        G: FnOnce() -> R,
1581    {
1582        match self {
1583            Self::Left(left) => (left, g()),
1584            Self::Right(right) => (f(), right),
1585        }
1586    }
1587
1588    /// Inserts `left` into the `Either` consuming it and returning an `EitherOrBoth`
1589    ///
1590    /// # Examples
1591    ///
1592    /// ```
1593    /// use either_or_both::{Either, EitherOrBoth};
1594    ///
1595    /// let value: Either<u8, char> = Either::Left(1);
1596    /// assert_eq!(value.inject_left(2), EitherOrBoth::Left(2));
1597    ///
1598    /// let value: Either<u8, char> = Either::Right('c');
1599    /// assert_eq!(value.inject_left(1), EitherOrBoth::Both(1, 'c'));
1600    /// ```
1601    #[inline]
1602    #[must_use]
1603    pub fn inject_left(self, left: L) -> EitherOrBoth<L, R> {
1604        match self {
1605            Self::Left(_) => EitherOrBoth::Left(left),
1606            Self::Right(right) => EitherOrBoth::Both(left, right),
1607        }
1608    }
1609
1610    /// Inserts `right` into the `Either` consuming it and returning an `EitherOrBoth`
1611    ///
1612    /// # Examples
1613    ///
1614    /// ```
1615    /// use either_or_both::{Either, EitherOrBoth};
1616    ///
1617    /// let value: Either<u8, char> = Either::Right('c');
1618    /// assert_eq!(value.inject_right('m'), EitherOrBoth::Right('m'));
1619    ///
1620    /// let value: Either<u8, char> = Either::Left(1);
1621    /// assert_eq!(value.inject_right('m'), EitherOrBoth::Both(1, 'm'));
1622    /// ```
1623    #[inline]
1624    #[must_use]
1625    pub fn inject_right(self, right: R) -> EitherOrBoth<L, R> {
1626        match self {
1627            Self::Left(left) => EitherOrBoth::Both(left, right),
1628            Self::Right(_) => EitherOrBoth::Right(right),
1629        }
1630    }
1631
1632    /// Converts into a [`Left`] variant, using the contained left value or applying a
1633    /// mapping function to the [`Right`] value.
1634    ///
1635    /// # Examples
1636    ///
1637    /// ```
1638    /// use either_or_both::Either;
1639    ///
1640    /// let value: Either<u8, char> = Either::Left(1);
1641    /// assert_eq!(value.into_left(|r| r as u8), Either::Left(1));
1642    ///
1643    /// let value: Either<u8, char> = Either::Right('c');
1644    /// assert_eq!(value.into_left(|r| r as u8), Either::Left(99));
1645    /// ```
1646    #[inline]
1647    #[must_use]
1648    pub fn into_left<F>(self, f: F) -> Self
1649    where
1650        F: FnOnce(R) -> L,
1651    {
1652        match self {
1653            Self::Left(_) => self,
1654            Self::Right(right) => Self::Left(f(right)),
1655        }
1656    }
1657
1658    /// Converts into a [`Right`] variant, using the contained right value or applying a
1659    /// mapping function to the [`Left`] value.
1660    ///
1661    /// # Examples
1662    ///
1663    /// ```
1664    /// use either_or_both::Either;
1665    ///
1666    /// let value: Either<u8, char> = Either::Right('c');
1667    /// assert_eq!(value.into_right(|l| l as char), Either::Right('c'));
1668    ///
1669    /// let value: Either<u8, char> = Either::Left(0);
1670    /// assert_eq!(value.into_right(|l| l as char), Either::Right('\0'));
1671    /// ```
1672    #[inline]
1673    #[must_use]
1674    pub fn into_right<F>(self, f: F) -> Self
1675    where
1676        F: FnOnce(L) -> R,
1677    {
1678        match self {
1679            Self::Left(left) => Self::Right(f(left)),
1680            Self::Right(_) => self,
1681        }
1682    }
1683
1684    ////////////////////////////////////////////////////////////////////////////////
1685    // Replacing values
1686    ////////////////////////////////////////////////////////////////////////////////
1687
1688    /// Replaces the `left` value returning the old value if present
1689    ///
1690    /// # Examples
1691    ///
1692    /// ```
1693    /// use either_or_both::Either;
1694    ///
1695    /// let mut value: Either<u8, char> = Either::Left(1);
1696    /// let old = value.replace_left(2);
1697    /// assert_eq!(old, Some(1));
1698    /// assert_eq!(value, Either::Left(2));
1699    ///
1700    /// let mut value: Either<u8, char> = Either::Right('c');
1701    /// let old = value.replace_left(2);
1702    /// assert_eq!(old, None);
1703    /// assert_eq!(value, Either::Right('c'));
1704    /// ```
1705    #[inline]
1706    pub fn replace_left(&mut self, value: L) -> Option<L> {
1707        match self {
1708            Self::Left(left) => Some(mem::replace(left, value)),
1709            Self::Right(_) => None,
1710        }
1711    }
1712
1713    /// Replaces the `right` value returning the old value if present
1714    ///
1715    /// # Examples
1716    ///
1717    /// ```
1718    /// use either_or_both::Either;
1719    ///
1720    /// let mut value: Either<u8, char> = Either::Right('c');
1721    /// let old = value.replace_right('m');
1722    /// assert_eq!(old, Some('c'));
1723    /// assert_eq!(value, Either::Right('m'));
1724    ///
1725    /// let mut value: Either<u8, char> = Either::Left(1);
1726    /// let old = value.replace_right('m');
1727    /// assert_eq!(old, None);
1728    /// assert_eq!(value, Either::Left(1));
1729    /// ```
1730    #[inline]
1731    pub fn replace_right(&mut self, value: R) -> Option<R> {
1732        match self {
1733            Self::Right(right) => Some(mem::replace(right, value)),
1734            Self::Left(_) => None,
1735        }
1736    }
1737}
1738
1739impl<T> Either<T, T> {
1740    /// Consumes this `Either` applying a function to the contained value (of a uniform
1741    /// type) taking mutable references to capture variables.
1742    ///
1743    /// # Examples
1744    ///
1745    /// ```
1746    /// use either_or_both::Either;
1747    ///
1748    /// let mut both = vec![];
1749    ///
1750    /// let value: Either<char> = Either::Left('c');
1751    /// value.apply(|c| both.push(c));
1752    ///
1753    /// let value: Either<char> = Either::Right('a');
1754    /// value.apply(|c| both.push(c));
1755    ///
1756    /// assert_eq!(both, vec!['c', 'a']);
1757    /// ```
1758    #[inline]
1759    pub fn apply<F>(self, mut f: F)
1760    where
1761        F: FnMut(T),
1762    {
1763        match self {
1764            Self::Left(left) => f(left),
1765            Self::Right(right) => f(right),
1766        }
1767    }
1768
1769    /// Calls a function with a reference to the contained value (of a uniform type)
1770    /// returning the original `Either`.
1771    ///
1772    /// # Examples
1773    ///
1774    /// ```
1775    /// use either_or_both::Either;
1776    ///
1777    /// // Prints a single line with "The value is: c"
1778    /// let value: Either<char> = Either::Left('c');
1779    /// let left = value
1780    ///     .inspect(|c| println!("The value is: {c}"))
1781    ///     .expect_left("should be a left value");
1782    /// assert_eq!(left, 'c');
1783    ///
1784    /// // Prints a single line with "The value is: a"
1785    /// let value: Either<char> = Either::Right('a');
1786    /// let right = value
1787    ///     .inspect(|c| println!("The value is: {c}"))
1788    ///     .expect_right("should be a right value");
1789    ///
1790    /// assert_eq!(right, 'a');
1791    /// ```
1792    #[inline]
1793    #[must_use]
1794    pub fn inspect<F>(self, f: F) -> Self
1795    where
1796        for<'a> F: Fn(&'a T),
1797    {
1798        match &self {
1799            Self::Left(left) => f(left),
1800            Self::Right(right) => f(right),
1801        }
1802
1803        self
1804    }
1805
1806    /// Returns an iterator over the contained value of a uniform type
1807    ///
1808    /// # Examples
1809    ///
1810    /// ```
1811    /// use either_or_both::EitherOrBoth;
1812    ///
1813    /// let value: EitherOrBoth<char> = EitherOrBoth::Left('c');
1814    /// let mut iter = value.iter();
1815    /// assert_eq!(iter.next(), Some(&'c'));
1816    /// assert_eq!(iter.next(), None);
1817    ///
1818    /// let value: EitherOrBoth<char> = EitherOrBoth::Right('c');
1819    /// let mut iter = value.iter();
1820    /// assert_eq!(iter.next(), Some(&'c'));
1821    /// assert_eq!(iter.next(), None);
1822    /// ```
1823    #[inline]
1824    pub fn iter(&self) -> IterEither<'_, T> {
1825        IterEither::new(self)
1826    }
1827
1828    /// Returns an iterator over the contained mutable value of a uniform type
1829    ///
1830    /// # Examples
1831    ///
1832    /// ```
1833    /// use either_or_both::EitherOrBoth;
1834    ///
1835    /// let mut value: EitherOrBoth<char> = EitherOrBoth::Left('c');
1836    /// let mut iter = value.iter_mut();
1837    /// assert_eq!(iter.next(), Some(&mut 'c'));
1838    /// assert_eq!(iter.next(), None);
1839    ///
1840    /// let mut value: EitherOrBoth<char> = EitherOrBoth::Right('c');
1841    /// let mut iter = value.iter_mut();
1842    /// assert_eq!(iter.next(), Some(&mut 'c'));
1843    /// assert_eq!(iter.next(), None);
1844    /// ```
1845    #[inline]
1846    pub fn iter_mut(&mut self) -> IterMutEither<'_, T> {
1847        IterMutEither::new(self)
1848    }
1849
1850    /// Consumes the `Either`, returning an iterator over the contained iterator of a
1851    /// uniform type
1852    ///
1853    /// For iteration over contained iterators with non-uniform types, you can use
1854    /// [`into_iter_swap`] instead.
1855    ///
1856    /// # Examples
1857    ///
1858    /// ```
1859    /// use either_or_both::Either;
1860    ///
1861    /// let value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
1862    /// let collected: Vec<char> = value.into_iter_inner().collect();
1863    /// assert_eq!(collected, vec!['c', 'a']);
1864    /// ```
1865    ///
1866    /// [`into_iter_swap`]: Either::into_iter_swap
1867    pub fn into_iter_inner(self) -> InnerIterEither<<T as IntoIterator>::IntoIter>
1868    where
1869        T: IntoIterator,
1870    {
1871        InnerIterEither::new(self.map(IntoIterator::into_iter))
1872    }
1873
1874    /// Returns an iterator over the contained iterator of a uniform type
1875    ///
1876    /// For iteration over contained iterators with non-uniform types, you can use
1877    /// [`iter_swap`] instead.
1878    ///
1879    /// # Examples
1880    ///
1881    /// ```
1882    /// use either_or_both::Either;
1883    ///
1884    /// let value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
1885    /// let collected: Vec<&char> = value.iter_inner().collect();
1886    /// assert_eq!(collected, vec![&'c', &'a']);
1887    /// ```
1888    ///
1889    /// [`iter_swap`]: Either::into_iter_swap
1890    pub fn iter_inner(&self) -> InnerIterEither<<&T as IntoIterator>::IntoIter>
1891    where
1892        for<'a> &'a T: IntoIterator,
1893    {
1894        InnerIterEither::new(self.as_ref().map(IntoIterator::into_iter))
1895    }
1896
1897    /// Returns an iterator over the mutable values of the contained iterator of a uniform
1898    /// type
1899    ///
1900    /// For iteration over contained iterators with non-uniform types, you can use
1901    /// [`iter_swap_mut`] instead.
1902    ///
1903    /// # Examples
1904    ///
1905    /// ```
1906    /// use either_or_both::Either;
1907    ///
1908    /// let mut value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
1909    /// let collected: Vec<&mut char> = value.iter_inner_mut().collect();
1910    /// assert_eq!(collected, vec![&mut 'c', &mut 'a']);
1911    /// ```
1912    ///
1913    /// [`iter_swap_mut`]: Either::iter_swap_mut
1914    pub fn iter_inner_mut(&mut self) -> InnerIterEither<<&mut T as IntoIterator>::IntoIter>
1915    where
1916        for<'a> &'a mut T: IntoIterator,
1917    {
1918        InnerIterEither::new(self.as_mut().map(IntoIterator::into_iter))
1919    }
1920
1921    /// Applies a mapping function to the left and right values (of a uniform type)
1922    /// returning an `Either<U, U>`.
1923    ///
1924    /// # Examples
1925    ///
1926    /// ```
1927    /// use either_or_both::Either;
1928    ///
1929    /// let value: Either<char> = Either::Left('c');
1930    /// assert_eq!(value.map(|c| c.to_string()), Either::Left("c".to_owned()));
1931    ///
1932    /// let value: Either<char> = Either::Right('a');
1933    /// assert_eq!(value.map(|c| c.to_string()), Either::Right("a".to_owned()));
1934    /// ```
1935    #[inline]
1936    pub fn map<F, U>(self, f: F) -> Either<U, U>
1937    where
1938        F: FnOnce(T) -> U,
1939    {
1940        match self {
1941            Self::Left(left) => Left(f(left)),
1942            Self::Right(right) => Right(f(right)),
1943        }
1944    }
1945
1946    /// Returns the contained [`Left`] or [`Right`] value of uniform type.
1947    ///
1948    /// # Example
1949    ///
1950    /// ```
1951    /// use either_or_both::Either;
1952    ///
1953    /// let value: Either<u8> = Either::Left(1);
1954    /// assert_eq!(value.reduce(), 1);
1955    ///
1956    /// let value: Either<u8> = Either::Right(2);
1957    /// assert_eq!(value.reduce(), 2);
1958    /// ```
1959    #[inline]
1960    #[must_use]
1961    pub fn reduce(self) -> T {
1962        match self {
1963            Self::Left(left) => left,
1964            Self::Right(right) => right,
1965        }
1966    }
1967
1968    /// Returns the contained [`Left`] or [`Right`] value applying a mapping function to
1969    /// the contained values.
1970    ///
1971    /// # Example
1972    ///
1973    /// ```
1974    /// use either_or_both::Either;
1975    ///
1976    /// let value: Either<u8> = Either::Left(1);
1977    /// assert_eq!(value.reduce_map(|v| v + 1), 2);
1978    ///
1979    /// let value: Either<u8> = Either::Right(2);
1980    /// assert_eq!(value.reduce_map(|v| v + 1), 3);
1981    /// ```
1982    #[inline]
1983    pub fn reduce_map<F, U>(self, f: F) -> U
1984    where
1985        F: FnOnce(T) -> U,
1986    {
1987        match self {
1988            Self::Left(left) => f(left),
1989            Self::Right(right) => f(right),
1990        }
1991    }
1992}
1993
1994impl<L, R> Either<&L, &R> {
1995    /// Converts an `Either<&L, &R>` into an `Either<L, R>` by cloning its contents
1996    ///
1997    /// # Examples
1998    ///
1999    /// ```
2000    /// use either_or_both::Either;
2001    ///
2002    /// let value: Either<u8, char> = Either::Left(1);
2003    /// let refs: Either<&u8, &char> = value.as_ref();
2004    /// assert_eq!(refs.cloned(), Either::Left(1));
2005    /// ```
2006    #[must_use = "`self` will be dropped if the result is not used"]
2007    pub fn cloned(self) -> Either<L, R>
2008    where
2009        L: Clone,
2010        R: Clone,
2011    {
2012        match self {
2013            Self::Left(left) => Left(left.clone()),
2014            Self::Right(right) => Right(right.clone()),
2015        }
2016    }
2017
2018    /// Converts an `Either<&L, &R>` into an `Either<L, R>` by copying its contents.
2019    ///
2020    /// # Examples
2021    ///
2022    /// ```
2023    /// use either_or_both::Either;
2024    ///
2025    /// let value: Either<u8, char> = Either::Left(1);
2026    /// let refs: Either<&u8, &char> = value.as_ref();
2027    /// assert_eq!(refs.copied(), Either::Left(1));
2028    /// ```
2029    #[must_use = "`self` will be dropped if the result is not used"]
2030    pub const fn copied(self) -> Either<L, R>
2031    where
2032        L: Copy,
2033        R: Copy,
2034    {
2035        match self {
2036            Self::Left(left) => Left(*left),
2037            Self::Right(right) => Right(*right),
2038        }
2039    }
2040}
2041
2042impl<L, R> Either<&mut L, &mut R> {
2043    /// Converts an `Either<&mut L, &mut R>` into an `Either<L, R>` by cloning its
2044    /// contents.
2045    ///
2046    /// # Examples
2047    ///
2048    /// ```
2049    /// use either_or_both::Either;
2050    ///
2051    /// let mut value: Either<u8, char> = Either::Left(1);
2052    /// let refs: Either<&mut u8, &mut char> = value.as_mut();
2053    /// assert_eq!(refs.cloned(), Either::Left(1));
2054    /// ```
2055    #[must_use = "`self` will be dropped if the result is not used"]
2056    pub fn cloned(self) -> Either<L, R>
2057    where
2058        L: Clone,
2059        R: Clone,
2060    {
2061        match self {
2062            Self::Left(left) => Left(left.clone()),
2063            Self::Right(right) => Right(right.clone()),
2064        }
2065    }
2066
2067    /// Converts an `Either<&mut L, &mut R>` into an `Either<L, R>` by copying its
2068    /// contents
2069    ///
2070    /// # Examples
2071    ///
2072    /// ```
2073    /// use either_or_both::Either;
2074    ///
2075    /// let mut value: Either<u8, char> = Either::Left(1);
2076    /// let refs: Either<&mut u8, &mut char> = value.as_mut();
2077    /// assert_eq!(refs.copied(), Either::Left(1));
2078    /// ```
2079    #[must_use = "`self` will be dropped if the result is not used"]
2080    pub fn copied(self) -> Either<L, R>
2081    where
2082        L: Copy,
2083        R: Copy,
2084    {
2085        match self {
2086            Self::Left(left) => Left(*left),
2087            Self::Right(right) => Right(*right),
2088        }
2089    }
2090}
2091
2092impl<L1, L2, R1, R2> Either<(L1, R1), (L2, R2)> {
2093    /// Transposes a `Either` of tuples to a tuple of `Eithers`
2094    ///
2095    /// # Examples
2096    ///
2097    /// ```
2098    /// use either_or_both::Either;
2099    ///
2100    /// let value: Either<(u8, char), (i32, u64)> = Either::Left((1, 'c'));
2101    /// assert_eq!(value.transpose(), (Either::Left(1), Either::Left('c')));
2102    ///
2103    /// let value: Either<(u8, char), (i32, u64)> = Either::Right((-2, 10));
2104    /// assert_eq!(value.transpose(), (Either::Right(-2), Either::Right(10)));
2105    /// ```
2106    #[must_use]
2107    pub fn transpose(self) -> (Either<L1, L2>, Either<R1, R2>) {
2108        match self {
2109            Self::Left((l1, r1)) => (Left(l1), Left(r1)),
2110            Self::Right((l2, r2)) => (Right(l2), Right(r2)),
2111        }
2112    }
2113}
2114
2115impl<L, R, T> Either<(T, L), (T, R)> {
2116    /// Transposes an `Either` of tuples to a tuple of a single value and an `Either` with
2117    /// the left value having a uniform type
2118    ///
2119    /// # Examples
2120    ///
2121    /// ```
2122    /// use either_or_both::Either;
2123    ///
2124    /// let value: Either<(u8, char), (u8, i32)> = Either::Left((1, 'c'));
2125    /// assert_eq!(value.transpose_left(), (1, Either::Left('c')));
2126    ///
2127    /// let value: Either<(u8, char), (u8, i32)> = Either::Right((2, -10));
2128    /// assert_eq!(value.transpose_left(), (2, Either::Right(-10)));
2129    /// ```
2130    #[must_use]
2131    pub fn transpose_left(self) -> (T, Either<L, R>) {
2132        match self {
2133            Self::Left((target, left)) => (target, Left(left)),
2134            Self::Right((target, right)) => (target, Right(right)),
2135        }
2136    }
2137}
2138
2139impl<L, R, T> Either<(L, T), (R, T)> {
2140    /// Transposes an `Either` of tuples to a tuple of a single value and an `Either` with
2141    /// the right value having a uniform type
2142    ///
2143    /// # Examples
2144    ///
2145    /// ```
2146    /// use either_or_both::Either;
2147    ///
2148    /// let value: Either<(u8, char), (i32, char)> = Either::Left((1, 'c'));
2149    /// assert_eq!(value.transpose_right(), (Either::Left(1), 'c'));
2150    ///
2151    /// let value: Either<(u8, char), (i32, char)> = Either::Right((-2, 'a'));
2152    /// assert_eq!(value.transpose_right(), (Either::Right(-2), 'a'));
2153    /// ```
2154    #[must_use]
2155    pub fn transpose_right(self) -> (Either<L, R>, T) {
2156        match self {
2157            Self::Left((left, target)) => (Left(left), target),
2158            Self::Right((right, target)) => (Right(right), target),
2159        }
2160    }
2161}
2162
2163impl<L, R> Either<Option<L>, Option<R>> {
2164    /// Transposes an `Either` of [`Options`] to an option of an `Either`
2165    ///
2166    /// # Examples
2167    ///
2168    /// ```
2169    /// use either_or_both::Either;
2170    ///
2171    /// let value: Either<Option<u8>, Option<char>> = Either::Left(Some(1));
2172    /// assert_eq!(value.transpose(), Some(Either::Left(1)));
2173    ///
2174    /// let value: Either<Option<u8>, Option<char>> = Either::Left(None);
2175    /// assert_eq!(value.transpose(), None);
2176    ///
2177    /// let value: Either<Option<u8>, Option<char>> = Either::Right(Some('c'));
2178    /// assert_eq!(value.transpose(), Some(Either::Right('c')));
2179    /// ```
2180    ///
2181    /// [`Options`]: Option
2182    #[inline]
2183    #[must_use]
2184    pub fn transpose(self) -> Option<Either<L, R>> {
2185        match self {
2186            Self::Left(left) => left.map(Left),
2187            Self::Right(right) => right.map(Right),
2188        }
2189    }
2190}
2191
2192impl<L, R, E1, E2> Either<Result<L, E1>, Result<R, E2>> {
2193    /// Transposes an `Either` of [`Results`] to a [`Result`] of an `Either`
2194    ///
2195    /// # Examples
2196    ///
2197    /// ```
2198    /// use either_or_both::Either;
2199    ///
2200    /// let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Left(Ok(1));
2201    /// assert_eq!(value.transpose(), Ok(Either::Left(1)));
2202    ///
2203    /// let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Left(Err('c'));
2204    /// assert_eq!(value.transpose(), Err(Either::Left('c')));
2205    ///
2206    /// let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Right(Ok(-2));
2207    /// assert_eq!(value.transpose(), Ok(Either::Right(-2)));
2208    /// ```
2209    ///
2210    /// [`Results`]: Result
2211    #[allow(clippy::missing_errors_doc)]
2212    #[inline]
2213    pub fn transpose(self) -> Result<Either<L, R>, Either<E1, E2>> {
2214        match self {
2215            Self::Left(left) => match left {
2216                Ok(ok) => Ok(Left(ok)),
2217                Err(err) => Err(Left(err)),
2218            },
2219            Self::Right(right) => match right {
2220                Ok(ok) => Ok(Right(ok)),
2221                Err(err) => Err(Right(err)),
2222            },
2223        }
2224    }
2225}
2226
2227impl<L, R, E> Either<Result<L, E>, Result<R, E>> {
2228    /// Transposes an `Either` of [`Results`] to a [`Result`] with an uniform error type
2229    ///
2230    /// # Examples
2231    ///
2232    /// ```
2233    /// use either_or_both::Either;
2234    ///
2235    /// let x: Either<Result<u8, char>, Result<i32, char>> = Either::Left(Ok(1));
2236    /// assert_eq!(x.transpose_err(), Ok(Either::Left(1)));
2237    ///
2238    /// let x: Either<Result<u8, char>, Result<i32, char>> = Either::Left(Err('c'));
2239    /// assert_eq!(x.transpose_err(), Err('c'));
2240    ///
2241    /// let x: Either<Result<u8, char>, Result<i32, char>> = Either::Right(Ok(-2));
2242    /// assert_eq!(x.transpose_err(), Ok(Either::Right(-2)));
2243    /// ```
2244    ///
2245    /// [`Results`]: Result
2246    #[allow(clippy::missing_errors_doc)]
2247    #[inline]
2248    pub fn transpose_err(self) -> Result<Either<L, R>, E> {
2249        match self {
2250            Self::Left(left) => left.map(Left),
2251            Self::Right(right) => right.map(Right),
2252        }
2253    }
2254}
2255
2256impl<T, E1, E2> Either<Result<T, E1>, Result<T, E2>> {
2257    /// Transposes an `Either` of [`Results`] to a [`Result`] with an uniform correct type
2258    ///
2259    /// # Examples
2260    ///
2261    /// ```
2262    /// use either_or_both::Either;
2263    ///
2264    /// let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Left(Ok(2));
2265    /// assert_eq!(x.transpose_ok(), Ok(2));
2266    ///
2267    /// let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Left(Err('c'));
2268    /// assert_eq!(x.transpose_ok(), Err(Either::Left('c')));
2269    ///
2270    /// let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Right(Ok(2));
2271    /// assert_eq!(x.transpose_ok(), Ok(2));
2272    /// ```
2273    ///
2274    /// [`Results`]: Result
2275    #[allow(clippy::missing_errors_doc)]
2276    #[inline]
2277    pub fn transpose_ok(self) -> Result<T, Either<E1, E2>> {
2278        match self {
2279            Self::Left(left) => left.map_err(Left),
2280            Self::Right(right) => right.map_err(Right),
2281        }
2282    }
2283}