1 //! The enum [`Either`] with variants `Left` and `Right` is a general purpose
2 //! sum type with two cases.
3 //!
4 //! [`Either`]: enum.Either.html
5 //!
6 //! **Crate features:**
7 //!
8 //! * `"use_std"`
9 //!   Enabled by default. Disable to make the library `#![no_std]`.
10 //!
11 //! * `"serde"`
12 //!   Disabled by default. Enable to `#[derive(Serialize, Deserialize)]` for `Either`
13 //!
14 
15 #![doc(html_root_url = "https://docs.rs/either/1/")]
16 #![no_std]
17 
18 #[cfg(any(test, feature = "use_std"))]
19 extern crate std;
20 
21 #[cfg(feature = "serde")]
22 pub mod serde_untagged;
23 
24 #[cfg(feature = "serde")]
25 pub mod serde_untagged_optional;
26 
27 use core::convert::{AsMut, AsRef};
28 use core::fmt;
29 use core::future::Future;
30 use core::ops::Deref;
31 use core::ops::DerefMut;
32 use core::pin::Pin;
33 
34 #[cfg(any(test, feature = "use_std"))]
35 use std::error::Error;
36 #[cfg(any(test, feature = "use_std"))]
37 use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
38 
39 pub use crate::Either::{Left, Right};
40 
41 /// The enum `Either` with variants `Left` and `Right` is a general purpose
42 /// sum type with two cases.
43 ///
44 /// The `Either` type is symmetric and treats its variants the same way, without
45 /// preference.
46 /// (For representing success or error, use the regular `Result` enum instead.)
47 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48 #[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
49 pub enum Either<L, R> {
50     /// A value of type `L`.
51     Left(L),
52     /// A value of type `R`.
53     Right(R),
54 }
55 
56 /// Evaluate the provided expression for both [`Either::Left`] and [`Either::Right`].
57 ///
58 /// This macro is useful in cases where both sides of [`Either`] can be interacted with
59 /// in the same way even though the don't share the same type.
60 ///
61 /// Syntax: `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)`
62 ///
63 /// # Example
64 ///
65 /// ```
66 /// use either::Either;
67 ///
68 /// fn length(owned_or_borrowed: Either<String, &'static str>) -> usize {
69 ///     either::for_both!(owned_or_borrowed, s => s.len())
70 /// }
71 ///
72 /// fn main() {
73 ///     let borrowed = Either::Right("Hello world!");
74 ///     let owned = Either::Left("Hello world!".to_owned());
75 ///
76 ///     assert_eq!(length(borrowed), 12);
77 ///     assert_eq!(length(owned), 12);
78 /// }
79 /// ```
80 #[macro_export]
81 macro_rules! for_both {
82     ($value:expr, $pattern:pat => $result:expr) => {
83         match $value {
84             $crate::Either::Left($pattern) => $result,
85             $crate::Either::Right($pattern) => $result,
86         }
87     };
88 }
89 
90 /// Macro for unwrapping the left side of an [`Either`], which fails early
91 /// with the opposite side. Can only be used in functions that return
92 /// `Either` because of the early return of `Right` that it provides.
93 ///
94 /// See also [`try_right!`] for its dual, which applies the same just to the
95 /// right side.
96 ///
97 /// # Example
98 ///
99 /// ```
100 /// use either::{Either, Left, Right};
101 ///
102 /// fn twice(wrapper: Either<u32, &str>) -> Either<u32, &str> {
103 ///     let value = either::try_left!(wrapper);
104 ///     Left(value * 2)
105 /// }
106 ///
107 /// fn main() {
108 ///     assert_eq!(twice(Left(2)), Left(4));
109 ///     assert_eq!(twice(Right("ups")), Right("ups"));
110 /// }
111 /// ```
112 #[macro_export]
113 macro_rules! try_left {
114     ($expr:expr) => {
115         match $expr {
116             $crate::Left(val) => val,
117             $crate::Right(err) => return $crate::Right(::core::convert::From::from(err)),
118         }
119     };
120 }
121 
122 /// Dual to [`try_left!`], see its documentation for more information.
123 #[macro_export]
124 macro_rules! try_right {
125     ($expr:expr) => {
126         match $expr {
127             $crate::Left(err) => return $crate::Left(::core::convert::From::from(err)),
128             $crate::Right(val) => val,
129         }
130     };
131 }
132 
133 macro_rules! map_either {
134     ($value:expr, $pattern:pat => $result:expr) => {
135         match $value {
136             Left($pattern) => Left($result),
137             Right($pattern) => Right($result),
138         }
139     };
140 }
141 
142 mod iterator;
143 pub use self::iterator::IterEither;
144 
145 mod into_either;
146 pub use self::into_either::IntoEither;
147 
148 impl<L: Clone, R: Clone> Clone for Either<L, R> {
clone(&self) -> Self149     fn clone(&self) -> Self {
150         match self {
151             Left(inner) => Left(inner.clone()),
152             Right(inner) => Right(inner.clone()),
153         }
154     }
155 
clone_from(&mut self, source: &Self)156     fn clone_from(&mut self, source: &Self) {
157         match (self, source) {
158             (Left(dest), Left(source)) => dest.clone_from(source),
159             (Right(dest), Right(source)) => dest.clone_from(source),
160             (dest, source) => *dest = source.clone(),
161         }
162     }
163 }
164 
165 impl<L, R> Either<L, R> {
166     /// Return true if the value is the `Left` variant.
167     ///
168     /// ```
169     /// use either::*;
170     ///
171     /// let values = [Left(1), Right("the right value")];
172     /// assert_eq!(values[0].is_left(), true);
173     /// assert_eq!(values[1].is_left(), false);
174     /// ```
is_left(&self) -> bool175     pub fn is_left(&self) -> bool {
176         match *self {
177             Left(_) => true,
178             Right(_) => false,
179         }
180     }
181 
182     /// Return true if the value is the `Right` variant.
183     ///
184     /// ```
185     /// use either::*;
186     ///
187     /// let values = [Left(1), Right("the right value")];
188     /// assert_eq!(values[0].is_right(), false);
189     /// assert_eq!(values[1].is_right(), true);
190     /// ```
is_right(&self) -> bool191     pub fn is_right(&self) -> bool {
192         !self.is_left()
193     }
194 
195     /// Convert the left side of `Either<L, R>` to an `Option<L>`.
196     ///
197     /// ```
198     /// use either::*;
199     ///
200     /// let left: Either<_, ()> = Left("some value");
201     /// assert_eq!(left.left(),  Some("some value"));
202     ///
203     /// let right: Either<(), _> = Right(321);
204     /// assert_eq!(right.left(), None);
205     /// ```
left(self) -> Option<L>206     pub fn left(self) -> Option<L> {
207         match self {
208             Left(l) => Some(l),
209             Right(_) => None,
210         }
211     }
212 
213     /// Convert the right side of `Either<L, R>` to an `Option<R>`.
214     ///
215     /// ```
216     /// use either::*;
217     ///
218     /// let left: Either<_, ()> = Left("some value");
219     /// assert_eq!(left.right(),  None);
220     ///
221     /// let right: Either<(), _> = Right(321);
222     /// assert_eq!(right.right(), Some(321));
223     /// ```
right(self) -> Option<R>224     pub fn right(self) -> Option<R> {
225         match self {
226             Left(_) => None,
227             Right(r) => Some(r),
228         }
229     }
230 
231     /// Convert `&Either<L, R>` to `Either<&L, &R>`.
232     ///
233     /// ```
234     /// use either::*;
235     ///
236     /// let left: Either<_, ()> = Left("some value");
237     /// assert_eq!(left.as_ref(), Left(&"some value"));
238     ///
239     /// let right: Either<(), _> = Right("some value");
240     /// assert_eq!(right.as_ref(), Right(&"some value"));
241     /// ```
as_ref(&self) -> Either<&L, &R>242     pub fn as_ref(&self) -> Either<&L, &R> {
243         match *self {
244             Left(ref inner) => Left(inner),
245             Right(ref inner) => Right(inner),
246         }
247     }
248 
249     /// Convert `&mut Either<L, R>` to `Either<&mut L, &mut R>`.
250     ///
251     /// ```
252     /// use either::*;
253     ///
254     /// fn mutate_left(value: &mut Either<u32, u32>) {
255     ///     if let Some(l) = value.as_mut().left() {
256     ///         *l = 999;
257     ///     }
258     /// }
259     ///
260     /// let mut left = Left(123);
261     /// let mut right = Right(123);
262     /// mutate_left(&mut left);
263     /// mutate_left(&mut right);
264     /// assert_eq!(left, Left(999));
265     /// assert_eq!(right, Right(123));
266     /// ```
as_mut(&mut self) -> Either<&mut L, &mut R>267     pub fn as_mut(&mut self) -> Either<&mut L, &mut R> {
268         match *self {
269             Left(ref mut inner) => Left(inner),
270             Right(ref mut inner) => Right(inner),
271         }
272     }
273 
274     /// Convert `Pin<&Either<L, R>>` to `Either<Pin<&L>, Pin<&R>>`,
275     /// pinned projections of the inner variants.
as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>>276     pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>> {
277         // SAFETY: We can use `new_unchecked` because the `inner` parts are
278         // guaranteed to be pinned, as they come from `self` which is pinned.
279         unsafe {
280             match *Pin::get_ref(self) {
281                 Left(ref inner) => Left(Pin::new_unchecked(inner)),
282                 Right(ref inner) => Right(Pin::new_unchecked(inner)),
283             }
284         }
285     }
286 
287     /// Convert `Pin<&mut Either<L, R>>` to `Either<Pin<&mut L>, Pin<&mut R>>`,
288     /// pinned projections of the inner variants.
as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>>289     pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>> {
290         // SAFETY: `get_unchecked_mut` is fine because we don't move anything.
291         // We can use `new_unchecked` because the `inner` parts are guaranteed
292         // to be pinned, as they come from `self` which is pinned, and we never
293         // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We
294         // also don't have an implementation of `Drop`, nor manual `Unpin`.
295         unsafe {
296             match *Pin::get_unchecked_mut(self) {
297                 Left(ref mut inner) => Left(Pin::new_unchecked(inner)),
298                 Right(ref mut inner) => Right(Pin::new_unchecked(inner)),
299             }
300         }
301     }
302 
303     /// Convert `Either<L, R>` to `Either<R, L>`.
304     ///
305     /// ```
306     /// use either::*;
307     ///
308     /// let left: Either<_, ()> = Left(123);
309     /// assert_eq!(left.flip(), Right(123));
310     ///
311     /// let right: Either<(), _> = Right("some value");
312     /// assert_eq!(right.flip(), Left("some value"));
313     /// ```
flip(self) -> Either<R, L>314     pub fn flip(self) -> Either<R, L> {
315         match self {
316             Left(l) => Right(l),
317             Right(r) => Left(r),
318         }
319     }
320 
321     /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the
322     /// result in `Left`.
323     ///
324     /// ```
325     /// use either::*;
326     ///
327     /// let left: Either<_, u32> = Left(123);
328     /// assert_eq!(left.map_left(|x| x * 2), Left(246));
329     ///
330     /// let right: Either<u32, _> = Right(123);
331     /// assert_eq!(right.map_left(|x| x * 2), Right(123));
332     /// ```
map_left<F, M>(self, f: F) -> Either<M, R> where F: FnOnce(L) -> M,333     pub fn map_left<F, M>(self, f: F) -> Either<M, R>
334     where
335         F: FnOnce(L) -> M,
336     {
337         match self {
338             Left(l) => Left(f(l)),
339             Right(r) => Right(r),
340         }
341     }
342 
343     /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the
344     /// result in `Right`.
345     ///
346     /// ```
347     /// use either::*;
348     ///
349     /// let left: Either<_, u32> = Left(123);
350     /// assert_eq!(left.map_right(|x| x * 2), Left(123));
351     ///
352     /// let right: Either<u32, _> = Right(123);
353     /// assert_eq!(right.map_right(|x| x * 2), Right(246));
354     /// ```
map_right<F, S>(self, f: F) -> Either<L, S> where F: FnOnce(R) -> S,355     pub fn map_right<F, S>(self, f: F) -> Either<L, S>
356     where
357         F: FnOnce(R) -> S,
358     {
359         match self {
360             Left(l) => Left(l),
361             Right(r) => Right(f(r)),
362         }
363     }
364 
365     /// Apply the functions `f` and `g` to the `Left` and `Right` variants
366     /// respectively. This is equivalent to
367     /// [bimap](https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html)
368     /// in functional programming.
369     ///
370     /// ```
371     /// use either::*;
372     ///
373     /// let f = |s: String| s.len();
374     /// let g = |u: u8| u.to_string();
375     ///
376     /// let left: Either<String, u8> = Left("loopy".into());
377     /// assert_eq!(left.map_either(f, g), Left(5));
378     ///
379     /// let right: Either<String, u8> = Right(42);
380     /// assert_eq!(right.map_either(f, g), Right("42".into()));
381     /// ```
map_either<F, G, M, S>(self, f: F, g: G) -> Either<M, S> where F: FnOnce(L) -> M, G: FnOnce(R) -> S,382     pub fn map_either<F, G, M, S>(self, f: F, g: G) -> Either<M, S>
383     where
384         F: FnOnce(L) -> M,
385         G: FnOnce(R) -> S,
386     {
387         match self {
388             Left(l) => Left(f(l)),
389             Right(r) => Right(g(r)),
390         }
391     }
392 
393     /// Similar to [`map_either`][Self::map_either], with an added context `ctx` accessible to
394     /// both functions.
395     ///
396     /// ```
397     /// use either::*;
398     ///
399     /// let mut sum = 0;
400     ///
401     /// // Both closures want to update the same value, so pass it as context.
402     /// let mut f = |sum: &mut usize, s: String| { *sum += s.len(); s.to_uppercase() };
403     /// let mut g = |sum: &mut usize, u: usize| { *sum += u; u.to_string() };
404     ///
405     /// let left: Either<String, usize> = Left("loopy".into());
406     /// assert_eq!(left.map_either_with(&mut sum, &mut f, &mut g), Left("LOOPY".into()));
407     ///
408     /// let right: Either<String, usize> = Right(42);
409     /// assert_eq!(right.map_either_with(&mut sum, &mut f, &mut g), Right("42".into()));
410     ///
411     /// assert_eq!(sum, 47);
412     /// ```
map_either_with<Ctx, F, G, M, S>(self, ctx: Ctx, f: F, g: G) -> Either<M, S> where F: FnOnce(Ctx, L) -> M, G: FnOnce(Ctx, R) -> S,413     pub fn map_either_with<Ctx, F, G, M, S>(self, ctx: Ctx, f: F, g: G) -> Either<M, S>
414     where
415         F: FnOnce(Ctx, L) -> M,
416         G: FnOnce(Ctx, R) -> S,
417     {
418         match self {
419             Left(l) => Left(f(ctx, l)),
420             Right(r) => Right(g(ctx, r)),
421         }
422     }
423 
424     /// Apply one of two functions depending on contents, unifying their result. If the value is
425     /// `Left(L)` then the first function `f` is applied; if it is `Right(R)` then the second
426     /// function `g` is applied.
427     ///
428     /// ```
429     /// use either::*;
430     ///
431     /// fn square(n: u32) -> i32 { (n * n) as i32 }
432     /// fn negate(n: i32) -> i32 { -n }
433     ///
434     /// let left: Either<u32, i32> = Left(4);
435     /// assert_eq!(left.either(square, negate), 16);
436     ///
437     /// let right: Either<u32, i32> = Right(-4);
438     /// assert_eq!(right.either(square, negate), 4);
439     /// ```
either<F, G, T>(self, f: F, g: G) -> T where F: FnOnce(L) -> T, G: FnOnce(R) -> T,440     pub fn either<F, G, T>(self, f: F, g: G) -> T
441     where
442         F: FnOnce(L) -> T,
443         G: FnOnce(R) -> T,
444     {
445         match self {
446             Left(l) => f(l),
447             Right(r) => g(r),
448         }
449     }
450 
451     /// Like [`either`][Self::either], but provide some context to whichever of the
452     /// functions ends up being called.
453     ///
454     /// ```
455     /// // In this example, the context is a mutable reference
456     /// use either::*;
457     ///
458     /// let mut result = Vec::new();
459     ///
460     /// let values = vec![Left(2), Right(2.7)];
461     ///
462     /// for value in values {
463     ///     value.either_with(&mut result,
464     ///                       |ctx, integer| ctx.push(integer),
465     ///                       |ctx, real| ctx.push(f64::round(real) as i32));
466     /// }
467     ///
468     /// assert_eq!(result, vec![2, 3]);
469     /// ```
either_with<Ctx, F, G, T>(self, ctx: Ctx, f: F, g: G) -> T where F: FnOnce(Ctx, L) -> T, G: FnOnce(Ctx, R) -> T,470     pub fn either_with<Ctx, F, G, T>(self, ctx: Ctx, f: F, g: G) -> T
471     where
472         F: FnOnce(Ctx, L) -> T,
473         G: FnOnce(Ctx, R) -> T,
474     {
475         match self {
476             Left(l) => f(ctx, l),
477             Right(r) => g(ctx, r),
478         }
479     }
480 
481     /// Apply the function `f` on the value in the `Left` variant if it is present.
482     ///
483     /// ```
484     /// use either::*;
485     ///
486     /// let left: Either<_, u32> = Left(123);
487     /// assert_eq!(left.left_and_then::<_,()>(|x| Right(x * 2)), Right(246));
488     ///
489     /// let right: Either<u32, _> = Right(123);
490     /// assert_eq!(right.left_and_then(|x| Right::<(), _>(x * 2)), Right(123));
491     /// ```
left_and_then<F, S>(self, f: F) -> Either<S, R> where F: FnOnce(L) -> Either<S, R>,492     pub fn left_and_then<F, S>(self, f: F) -> Either<S, R>
493     where
494         F: FnOnce(L) -> Either<S, R>,
495     {
496         match self {
497             Left(l) => f(l),
498             Right(r) => Right(r),
499         }
500     }
501 
502     /// Apply the function `f` on the value in the `Right` variant if it is present.
503     ///
504     /// ```
505     /// use either::*;
506     ///
507     /// let left: Either<_, u32> = Left(123);
508     /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123));
509     ///
510     /// let right: Either<u32, _> = Right(123);
511     /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246));
512     /// ```
right_and_then<F, S>(self, f: F) -> Either<L, S> where F: FnOnce(R) -> Either<L, S>,513     pub fn right_and_then<F, S>(self, f: F) -> Either<L, S>
514     where
515         F: FnOnce(R) -> Either<L, S>,
516     {
517         match self {
518             Left(l) => Left(l),
519             Right(r) => f(r),
520         }
521     }
522 
523     /// Convert the inner value to an iterator.
524     ///
525     /// This requires the `Left` and `Right` iterators to have the same item type.
526     /// See [`factor_into_iter`][Either::factor_into_iter] to iterate different types.
527     ///
528     /// ```
529     /// use either::*;
530     ///
531     /// let left: Either<_, Vec<u32>> = Left(vec![1, 2, 3, 4, 5]);
532     /// let mut right: Either<Vec<u32>, _> = Right(vec![]);
533     /// right.extend(left.into_iter());
534     /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5]));
535     /// ```
536     #[allow(clippy::should_implement_trait)]
into_iter(self) -> Either<L::IntoIter, R::IntoIter> where L: IntoIterator, R: IntoIterator<Item = L::Item>,537     pub fn into_iter(self) -> Either<L::IntoIter, R::IntoIter>
538     where
539         L: IntoIterator,
540         R: IntoIterator<Item = L::Item>,
541     {
542         map_either!(self, inner => inner.into_iter())
543     }
544 
545     /// Borrow the inner value as an iterator.
546     ///
547     /// This requires the `Left` and `Right` iterators to have the same item type.
548     /// See [`factor_iter`][Either::factor_iter] to iterate different types.
549     ///
550     /// ```
551     /// use either::*;
552     ///
553     /// let left: Either<_, &[u32]> = Left(vec![2, 3]);
554     /// let mut right: Either<Vec<u32>, _> = Right(&[4, 5][..]);
555     /// let mut all = vec![1];
556     /// all.extend(left.iter());
557     /// all.extend(right.iter());
558     /// assert_eq!(all, vec![1, 2, 3, 4, 5]);
559     /// ```
iter(&self) -> Either<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter> where for<'a> &'a L: IntoIterator, for<'a> &'a R: IntoIterator<Item = <&'a L as IntoIterator>::Item>,560     pub fn iter(&self) -> Either<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter>
561     where
562         for<'a> &'a L: IntoIterator,
563         for<'a> &'a R: IntoIterator<Item = <&'a L as IntoIterator>::Item>,
564     {
565         map_either!(self, inner => inner.into_iter())
566     }
567 
568     /// Mutably borrow the inner value as an iterator.
569     ///
570     /// This requires the `Left` and `Right` iterators to have the same item type.
571     /// See [`factor_iter_mut`][Either::factor_iter_mut] to iterate different types.
572     ///
573     /// ```
574     /// use either::*;
575     ///
576     /// let mut left: Either<_, &mut [u32]> = Left(vec![2, 3]);
577     /// for l in left.iter_mut() {
578     ///     *l *= *l
579     /// }
580     /// assert_eq!(left, Left(vec![4, 9]));
581     ///
582     /// let mut inner = [4, 5];
583     /// let mut right: Either<Vec<u32>, _> = Right(&mut inner[..]);
584     /// for r in right.iter_mut() {
585     ///     *r *= *r
586     /// }
587     /// assert_eq!(inner, [16, 25]);
588     /// ```
iter_mut( &mut self, ) -> Either<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter> where for<'a> &'a mut L: IntoIterator, for<'a> &'a mut R: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,589     pub fn iter_mut(
590         &mut self,
591     ) -> Either<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter>
592     where
593         for<'a> &'a mut L: IntoIterator,
594         for<'a> &'a mut R: IntoIterator<Item = <&'a mut L as IntoIterator>::Item>,
595     {
596         map_either!(self, inner => inner.into_iter())
597     }
598 
599     /// Converts an `Either` of `Iterator`s to be an `Iterator` of `Either`s
600     ///
601     /// Unlike [`into_iter`][Either::into_iter], this does not require the
602     /// `Left` and `Right` iterators to have the same item type.
603     ///
604     /// ```
605     /// use either::*;
606     /// let left: Either<_, Vec<u8>> = Left(&["hello"]);
607     /// assert_eq!(left.factor_into_iter().next(), Some(Left(&"hello")));
608 
609     /// let right: Either<&[&str], _> = Right(vec![0, 1]);
610     /// assert_eq!(right.factor_into_iter().collect::<Vec<_>>(), vec![Right(0), Right(1)]);
611     ///
612     /// ```
613     // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
614     // #[doc(alias = "transpose")]
factor_into_iter(self) -> IterEither<L::IntoIter, R::IntoIter> where L: IntoIterator, R: IntoIterator,615     pub fn factor_into_iter(self) -> IterEither<L::IntoIter, R::IntoIter>
616     where
617         L: IntoIterator,
618         R: IntoIterator,
619     {
620         IterEither::new(map_either!(self, inner => inner.into_iter()))
621     }
622 
623     /// Borrows an `Either` of `Iterator`s to be an `Iterator` of `Either`s
624     ///
625     /// Unlike [`iter`][Either::iter], this does not require the
626     /// `Left` and `Right` iterators to have the same item type.
627     ///
628     /// ```
629     /// use either::*;
630     /// let left: Either<_, Vec<u8>> = Left(["hello"]);
631     /// assert_eq!(left.factor_iter().next(), Some(Left(&"hello")));
632 
633     /// let right: Either<[&str; 2], _> = Right(vec![0, 1]);
634     /// assert_eq!(right.factor_iter().collect::<Vec<_>>(), vec![Right(&0), Right(&1)]);
635     ///
636     /// ```
factor_iter( &self, ) -> IterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter> where for<'a> &'a L: IntoIterator, for<'a> &'a R: IntoIterator,637     pub fn factor_iter(
638         &self,
639     ) -> IterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter>
640     where
641         for<'a> &'a L: IntoIterator,
642         for<'a> &'a R: IntoIterator,
643     {
644         IterEither::new(map_either!(self, inner => inner.into_iter()))
645     }
646 
647     /// Mutably borrows an `Either` of `Iterator`s to be an `Iterator` of `Either`s
648     ///
649     /// Unlike [`iter_mut`][Either::iter_mut], this does not require the
650     /// `Left` and `Right` iterators to have the same item type.
651     ///
652     /// ```
653     /// use either::*;
654     /// let mut left: Either<_, Vec<u8>> = Left(["hello"]);
655     /// left.factor_iter_mut().for_each(|x| *x.unwrap_left() = "goodbye");
656     /// assert_eq!(left, Left(["goodbye"]));
657 
658     /// let mut right: Either<[&str; 2], _> = Right(vec![0, 1, 2]);
659     /// right.factor_iter_mut().for_each(|x| if let Right(r) = x { *r = -*r; });
660     /// assert_eq!(right, Right(vec![0, -1, -2]));
661     ///
662     /// ```
factor_iter_mut( &mut self, ) -> IterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter> where for<'a> &'a mut L: IntoIterator, for<'a> &'a mut R: IntoIterator,663     pub fn factor_iter_mut(
664         &mut self,
665     ) -> IterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter>
666     where
667         for<'a> &'a mut L: IntoIterator,
668         for<'a> &'a mut R: IntoIterator,
669     {
670         IterEither::new(map_either!(self, inner => inner.into_iter()))
671     }
672 
673     /// Return left value or given value
674     ///
675     /// Arguments passed to `left_or` are eagerly evaluated; if you are passing
676     /// the result of a function call, it is recommended to use
677     /// [`left_or_else`][Self::left_or_else], which is lazily evaluated.
678     ///
679     /// # Examples
680     ///
681     /// ```
682     /// # use either::*;
683     /// let left: Either<&str, &str> = Left("left");
684     /// assert_eq!(left.left_or("foo"), "left");
685     ///
686     /// let right: Either<&str, &str> = Right("right");
687     /// assert_eq!(right.left_or("left"), "left");
688     /// ```
left_or(self, other: L) -> L689     pub fn left_or(self, other: L) -> L {
690         match self {
691             Either::Left(l) => l,
692             Either::Right(_) => other,
693         }
694     }
695 
696     /// Return left or a default
697     ///
698     /// # Examples
699     ///
700     /// ```
701     /// # use either::*;
702     /// let left: Either<String, u32> = Left("left".to_string());
703     /// assert_eq!(left.left_or_default(), "left");
704     ///
705     /// let right: Either<String, u32> = Right(42);
706     /// assert_eq!(right.left_or_default(), String::default());
707     /// ```
left_or_default(self) -> L where L: Default,708     pub fn left_or_default(self) -> L
709     where
710         L: Default,
711     {
712         match self {
713             Either::Left(l) => l,
714             Either::Right(_) => L::default(),
715         }
716     }
717 
718     /// Returns left value or computes it from a closure
719     ///
720     /// # Examples
721     ///
722     /// ```
723     /// # use either::*;
724     /// let left: Either<String, u32> = Left("3".to_string());
725     /// assert_eq!(left.left_or_else(|_| unreachable!()), "3");
726     ///
727     /// let right: Either<String, u32> = Right(3);
728     /// assert_eq!(right.left_or_else(|x| x.to_string()), "3");
729     /// ```
left_or_else<F>(self, f: F) -> L where F: FnOnce(R) -> L,730     pub fn left_or_else<F>(self, f: F) -> L
731     where
732         F: FnOnce(R) -> L,
733     {
734         match self {
735             Either::Left(l) => l,
736             Either::Right(r) => f(r),
737         }
738     }
739 
740     /// Return right value or given value
741     ///
742     /// Arguments passed to `right_or` are eagerly evaluated; if you are passing
743     /// the result of a function call, it is recommended to use
744     /// [`right_or_else`][Self::right_or_else], which is lazily evaluated.
745     ///
746     /// # Examples
747     ///
748     /// ```
749     /// # use either::*;
750     /// let right: Either<&str, &str> = Right("right");
751     /// assert_eq!(right.right_or("foo"), "right");
752     ///
753     /// let left: Either<&str, &str> = Left("left");
754     /// assert_eq!(left.right_or("right"), "right");
755     /// ```
right_or(self, other: R) -> R756     pub fn right_or(self, other: R) -> R {
757         match self {
758             Either::Left(_) => other,
759             Either::Right(r) => r,
760         }
761     }
762 
763     /// Return right or a default
764     ///
765     /// # Examples
766     ///
767     /// ```
768     /// # use either::*;
769     /// let left: Either<String, u32> = Left("left".to_string());
770     /// assert_eq!(left.right_or_default(), u32::default());
771     ///
772     /// let right: Either<String, u32> = Right(42);
773     /// assert_eq!(right.right_or_default(), 42);
774     /// ```
right_or_default(self) -> R where R: Default,775     pub fn right_or_default(self) -> R
776     where
777         R: Default,
778     {
779         match self {
780             Either::Left(_) => R::default(),
781             Either::Right(r) => r,
782         }
783     }
784 
785     /// Returns right value or computes it from a closure
786     ///
787     /// # Examples
788     ///
789     /// ```
790     /// # use either::*;
791     /// let left: Either<String, u32> = Left("3".to_string());
792     /// assert_eq!(left.right_or_else(|x| x.parse().unwrap()), 3);
793     ///
794     /// let right: Either<String, u32> = Right(3);
795     /// assert_eq!(right.right_or_else(|_| unreachable!()), 3);
796     /// ```
right_or_else<F>(self, f: F) -> R where F: FnOnce(L) -> R,797     pub fn right_or_else<F>(self, f: F) -> R
798     where
799         F: FnOnce(L) -> R,
800     {
801         match self {
802             Either::Left(l) => f(l),
803             Either::Right(r) => r,
804         }
805     }
806 
807     /// Returns the left value
808     ///
809     /// # Examples
810     ///
811     /// ```
812     /// # use either::*;
813     /// let left: Either<_, ()> = Left(3);
814     /// assert_eq!(left.unwrap_left(), 3);
815     /// ```
816     ///
817     /// # Panics
818     ///
819     /// When `Either` is a `Right` value
820     ///
821     /// ```should_panic
822     /// # use either::*;
823     /// let right: Either<(), _> = Right(3);
824     /// right.unwrap_left();
825     /// ```
unwrap_left(self) -> L where R: core::fmt::Debug,826     pub fn unwrap_left(self) -> L
827     where
828         R: core::fmt::Debug,
829     {
830         match self {
831             Either::Left(l) => l,
832             Either::Right(r) => {
833                 panic!("called `Either::unwrap_left()` on a `Right` value: {:?}", r)
834             }
835         }
836     }
837 
838     /// Returns the right value
839     ///
840     /// # Examples
841     ///
842     /// ```
843     /// # use either::*;
844     /// let right: Either<(), _> = Right(3);
845     /// assert_eq!(right.unwrap_right(), 3);
846     /// ```
847     ///
848     /// # Panics
849     ///
850     /// When `Either` is a `Left` value
851     ///
852     /// ```should_panic
853     /// # use either::*;
854     /// let left: Either<_, ()> = Left(3);
855     /// left.unwrap_right();
856     /// ```
unwrap_right(self) -> R where L: core::fmt::Debug,857     pub fn unwrap_right(self) -> R
858     where
859         L: core::fmt::Debug,
860     {
861         match self {
862             Either::Right(r) => r,
863             Either::Left(l) => panic!("called `Either::unwrap_right()` on a `Left` value: {:?}", l),
864         }
865     }
866 
867     /// Returns the left value
868     ///
869     /// # Examples
870     ///
871     /// ```
872     /// # use either::*;
873     /// let left: Either<_, ()> = Left(3);
874     /// assert_eq!(left.expect_left("value was Right"), 3);
875     /// ```
876     ///
877     /// # Panics
878     ///
879     /// When `Either` is a `Right` value
880     ///
881     /// ```should_panic
882     /// # use either::*;
883     /// let right: Either<(), _> = Right(3);
884     /// right.expect_left("value was Right");
885     /// ```
expect_left(self, msg: &str) -> L where R: core::fmt::Debug,886     pub fn expect_left(self, msg: &str) -> L
887     where
888         R: core::fmt::Debug,
889     {
890         match self {
891             Either::Left(l) => l,
892             Either::Right(r) => panic!("{}: {:?}", msg, r),
893         }
894     }
895 
896     /// Returns the right value
897     ///
898     /// # Examples
899     ///
900     /// ```
901     /// # use either::*;
902     /// let right: Either<(), _> = Right(3);
903     /// assert_eq!(right.expect_right("value was Left"), 3);
904     /// ```
905     ///
906     /// # Panics
907     ///
908     /// When `Either` is a `Left` value
909     ///
910     /// ```should_panic
911     /// # use either::*;
912     /// let left: Either<_, ()> = Left(3);
913     /// left.expect_right("value was Right");
914     /// ```
expect_right(self, msg: &str) -> R where L: core::fmt::Debug,915     pub fn expect_right(self, msg: &str) -> R
916     where
917         L: core::fmt::Debug,
918     {
919         match self {
920             Either::Right(r) => r,
921             Either::Left(l) => panic!("{}: {:?}", msg, l),
922         }
923     }
924 
925     /// Convert the contained value into `T`
926     ///
927     /// # Examples
928     ///
929     /// ```
930     /// # use either::*;
931     /// // Both u16 and u32 can be converted to u64.
932     /// let left: Either<u16, u32> = Left(3u16);
933     /// assert_eq!(left.either_into::<u64>(), 3u64);
934     /// let right: Either<u16, u32> = Right(7u32);
935     /// assert_eq!(right.either_into::<u64>(), 7u64);
936     /// ```
either_into<T>(self) -> T where L: Into<T>, R: Into<T>,937     pub fn either_into<T>(self) -> T
938     where
939         L: Into<T>,
940         R: Into<T>,
941     {
942         match self {
943             Either::Left(l) => l.into(),
944             Either::Right(r) => r.into(),
945         }
946     }
947 }
948 
949 impl<L, R> Either<Option<L>, Option<R>> {
950     /// Factors out `None` from an `Either` of [`Option`].
951     ///
952     /// ```
953     /// use either::*;
954     /// let left: Either<_, Option<String>> = Left(Some(vec![0]));
955     /// assert_eq!(left.factor_none(), Some(Left(vec![0])));
956     ///
957     /// let right: Either<Option<Vec<u8>>, _> = Right(Some(String::new()));
958     /// assert_eq!(right.factor_none(), Some(Right(String::new())));
959     /// ```
960     // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
961     // #[doc(alias = "transpose")]
factor_none(self) -> Option<Either<L, R>>962     pub fn factor_none(self) -> Option<Either<L, R>> {
963         match self {
964             Left(l) => l.map(Either::Left),
965             Right(r) => r.map(Either::Right),
966         }
967     }
968 }
969 
970 impl<L, R, E> Either<Result<L, E>, Result<R, E>> {
971     /// Factors out a homogenous type from an `Either` of [`Result`].
972     ///
973     /// Here, the homogeneous type is the `Err` type of the [`Result`].
974     ///
975     /// ```
976     /// use either::*;
977     /// let left: Either<_, Result<String, u32>> = Left(Ok(vec![0]));
978     /// assert_eq!(left.factor_err(), Ok(Left(vec![0])));
979     ///
980     /// let right: Either<Result<Vec<u8>, u32>, _> = Right(Ok(String::new()));
981     /// assert_eq!(right.factor_err(), Ok(Right(String::new())));
982     /// ```
983     // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
984     // #[doc(alias = "transpose")]
factor_err(self) -> Result<Either<L, R>, E>985     pub fn factor_err(self) -> Result<Either<L, R>, E> {
986         match self {
987             Left(l) => l.map(Either::Left),
988             Right(r) => r.map(Either::Right),
989         }
990     }
991 }
992 
993 impl<T, L, R> Either<Result<T, L>, Result<T, R>> {
994     /// Factors out a homogenous type from an `Either` of [`Result`].
995     ///
996     /// Here, the homogeneous type is the `Ok` type of the [`Result`].
997     ///
998     /// ```
999     /// use either::*;
1000     /// let left: Either<_, Result<u32, String>> = Left(Err(vec![0]));
1001     /// assert_eq!(left.factor_ok(), Err(Left(vec![0])));
1002     ///
1003     /// let right: Either<Result<u32, Vec<u8>>, _> = Right(Err(String::new()));
1004     /// assert_eq!(right.factor_ok(), Err(Right(String::new())));
1005     /// ```
1006     // TODO(MSRV): doc(alias) was stabilized in Rust 1.48
1007     // #[doc(alias = "transpose")]
factor_ok(self) -> Result<T, Either<L, R>>1008     pub fn factor_ok(self) -> Result<T, Either<L, R>> {
1009         match self {
1010             Left(l) => l.map_err(Either::Left),
1011             Right(r) => r.map_err(Either::Right),
1012         }
1013     }
1014 }
1015 
1016 impl<T, L, R> Either<(T, L), (T, R)> {
1017     /// Factor out a homogeneous type from an either of pairs.
1018     ///
1019     /// Here, the homogeneous type is the first element of the pairs.
1020     ///
1021     /// ```
1022     /// use either::*;
1023     /// let left: Either<_, (u32, String)> = Left((123, vec![0]));
1024     /// assert_eq!(left.factor_first().0, 123);
1025     ///
1026     /// let right: Either<(u32, Vec<u8>), _> = Right((123, String::new()));
1027     /// assert_eq!(right.factor_first().0, 123);
1028     /// ```
factor_first(self) -> (T, Either<L, R>)1029     pub fn factor_first(self) -> (T, Either<L, R>) {
1030         match self {
1031             Left((t, l)) => (t, Left(l)),
1032             Right((t, r)) => (t, Right(r)),
1033         }
1034     }
1035 }
1036 
1037 impl<T, L, R> Either<(L, T), (R, T)> {
1038     /// Factor out a homogeneous type from an either of pairs.
1039     ///
1040     /// Here, the homogeneous type is the second element of the pairs.
1041     ///
1042     /// ```
1043     /// use either::*;
1044     /// let left: Either<_, (String, u32)> = Left((vec![0], 123));
1045     /// assert_eq!(left.factor_second().1, 123);
1046     ///
1047     /// let right: Either<(Vec<u8>, u32), _> = Right((String::new(), 123));
1048     /// assert_eq!(right.factor_second().1, 123);
1049     /// ```
factor_second(self) -> (Either<L, R>, T)1050     pub fn factor_second(self) -> (Either<L, R>, T) {
1051         match self {
1052             Left((l, t)) => (Left(l), t),
1053             Right((r, t)) => (Right(r), t),
1054         }
1055     }
1056 }
1057 
1058 impl<T> Either<T, T> {
1059     /// Extract the value of an either over two equivalent types.
1060     ///
1061     /// ```
1062     /// use either::*;
1063     ///
1064     /// let left: Either<_, u32> = Left(123);
1065     /// assert_eq!(left.into_inner(), 123);
1066     ///
1067     /// let right: Either<u32, _> = Right(123);
1068     /// assert_eq!(right.into_inner(), 123);
1069     /// ```
into_inner(self) -> T1070     pub fn into_inner(self) -> T {
1071         for_both!(self, inner => inner)
1072     }
1073 
1074     /// Map `f` over the contained value and return the result in the
1075     /// corresponding variant.
1076     ///
1077     /// ```
1078     /// use either::*;
1079     ///
1080     /// let value: Either<_, i32> = Right(42);
1081     ///
1082     /// let other = value.map(|x| x * 2);
1083     /// assert_eq!(other, Right(84));
1084     /// ```
map<F, M>(self, f: F) -> Either<M, M> where F: FnOnce(T) -> M,1085     pub fn map<F, M>(self, f: F) -> Either<M, M>
1086     where
1087         F: FnOnce(T) -> M,
1088     {
1089         match self {
1090             Left(l) => Left(f(l)),
1091             Right(r) => Right(f(r)),
1092         }
1093     }
1094 }
1095 
1096 impl<L, R> Either<&L, &R> {
1097     /// Maps an `Either<&L, &R>` to an `Either<L, R>` by cloning the contents of
1098     /// either branch.
cloned(self) -> Either<L, R> where L: Clone, R: Clone,1099     pub fn cloned(self) -> Either<L, R>
1100     where
1101         L: Clone,
1102         R: Clone,
1103     {
1104         match self {
1105             Self::Left(l) => Either::Left(l.clone()),
1106             Self::Right(r) => Either::Right(r.clone()),
1107         }
1108     }
1109 
1110     /// Maps an `Either<&L, &R>` to an `Either<L, R>` by copying the contents of
1111     /// either branch.
copied(self) -> Either<L, R> where L: Copy, R: Copy,1112     pub fn copied(self) -> Either<L, R>
1113     where
1114         L: Copy,
1115         R: Copy,
1116     {
1117         match self {
1118             Self::Left(l) => Either::Left(*l),
1119             Self::Right(r) => Either::Right(*r),
1120         }
1121     }
1122 }
1123 
1124 impl<L, R> Either<&mut L, &mut R> {
1125     /// Maps an `Either<&mut L, &mut R>` to an `Either<L, R>` by cloning the contents of
1126     /// either branch.
cloned(self) -> Either<L, R> where L: Clone, R: Clone,1127     pub fn cloned(self) -> Either<L, R>
1128     where
1129         L: Clone,
1130         R: Clone,
1131     {
1132         match self {
1133             Self::Left(l) => Either::Left(l.clone()),
1134             Self::Right(r) => Either::Right(r.clone()),
1135         }
1136     }
1137 
1138     /// Maps an `Either<&mut L, &mut R>` to an `Either<L, R>` by copying the contents of
1139     /// either branch.
copied(self) -> Either<L, R> where L: Copy, R: Copy,1140     pub fn copied(self) -> Either<L, R>
1141     where
1142         L: Copy,
1143         R: Copy,
1144     {
1145         match self {
1146             Self::Left(l) => Either::Left(*l),
1147             Self::Right(r) => Either::Right(*r),
1148         }
1149     }
1150 }
1151 
1152 /// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`.
1153 impl<L, R> From<Result<R, L>> for Either<L, R> {
from(r: Result<R, L>) -> Self1154     fn from(r: Result<R, L>) -> Self {
1155         match r {
1156             Err(e) => Left(e),
1157             Ok(o) => Right(o),
1158         }
1159     }
1160 }
1161 
1162 /// Convert from `Either` to `Result` with `Right => Ok` and `Left => Err`.
1163 #[allow(clippy::from_over_into)] // From requires RFC 2451, Rust 1.41
1164 impl<L, R> Into<Result<R, L>> for Either<L, R> {
into(self) -> Result<R, L>1165     fn into(self) -> Result<R, L> {
1166         match self {
1167             Left(l) => Err(l),
1168             Right(r) => Ok(r),
1169         }
1170     }
1171 }
1172 
1173 /// `Either<L, R>` is a future if both `L` and `R` are futures.
1174 impl<L, R> Future for Either<L, R>
1175 where
1176     L: Future,
1177     R: Future<Output = L::Output>,
1178 {
1179     type Output = L::Output;
1180 
poll( self: Pin<&mut Self>, cx: &mut core::task::Context<'_>, ) -> core::task::Poll<Self::Output>1181     fn poll(
1182         self: Pin<&mut Self>,
1183         cx: &mut core::task::Context<'_>,
1184     ) -> core::task::Poll<Self::Output> {
1185         for_both!(self.as_pin_mut(), inner => inner.poll(cx))
1186     }
1187 }
1188 
1189 #[cfg(any(test, feature = "use_std"))]
1190 /// `Either<L, R>` implements `Read` if both `L` and `R` do.
1191 ///
1192 /// Requires crate feature `"use_std"`
1193 impl<L, R> Read for Either<L, R>
1194 where
1195     L: Read,
1196     R: Read,
1197 {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>1198     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1199         for_both!(*self, ref mut inner => inner.read(buf))
1200     }
1201 
read_exact(&mut self, buf: &mut [u8]) -> io::Result<()>1202     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
1203         for_both!(*self, ref mut inner => inner.read_exact(buf))
1204     }
1205 
read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize>1206     fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
1207         for_both!(*self, ref mut inner => inner.read_to_end(buf))
1208     }
1209 
read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize>1210     fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
1211         for_both!(*self, ref mut inner => inner.read_to_string(buf))
1212     }
1213 }
1214 
1215 #[cfg(any(test, feature = "use_std"))]
1216 /// `Either<L, R>` implements `Seek` if both `L` and `R` do.
1217 ///
1218 /// Requires crate feature `"use_std"`
1219 impl<L, R> Seek for Either<L, R>
1220 where
1221     L: Seek,
1222     R: Seek,
1223 {
seek(&mut self, pos: SeekFrom) -> io::Result<u64>1224     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1225         for_both!(*self, ref mut inner => inner.seek(pos))
1226     }
1227 }
1228 
1229 #[cfg(any(test, feature = "use_std"))]
1230 /// Requires crate feature `"use_std"`
1231 impl<L, R> BufRead for Either<L, R>
1232 where
1233     L: BufRead,
1234     R: BufRead,
1235 {
fill_buf(&mut self) -> io::Result<&[u8]>1236     fn fill_buf(&mut self) -> io::Result<&[u8]> {
1237         for_both!(*self, ref mut inner => inner.fill_buf())
1238     }
1239 
consume(&mut self, amt: usize)1240     fn consume(&mut self, amt: usize) {
1241         for_both!(*self, ref mut inner => inner.consume(amt))
1242     }
1243 
read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize>1244     fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
1245         for_both!(*self, ref mut inner => inner.read_until(byte, buf))
1246     }
1247 
read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize>1248     fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
1249         for_both!(*self, ref mut inner => inner.read_line(buf))
1250     }
1251 }
1252 
1253 #[cfg(any(test, feature = "use_std"))]
1254 /// `Either<L, R>` implements `Write` if both `L` and `R` do.
1255 ///
1256 /// Requires crate feature `"use_std"`
1257 impl<L, R> Write for Either<L, R>
1258 where
1259     L: Write,
1260     R: Write,
1261 {
write(&mut self, buf: &[u8]) -> io::Result<usize>1262     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1263         for_both!(*self, ref mut inner => inner.write(buf))
1264     }
1265 
write_all(&mut self, buf: &[u8]) -> io::Result<()>1266     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1267         for_both!(*self, ref mut inner => inner.write_all(buf))
1268     }
1269 
write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()>1270     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
1271         for_both!(*self, ref mut inner => inner.write_fmt(fmt))
1272     }
1273 
flush(&mut self) -> io::Result<()>1274     fn flush(&mut self) -> io::Result<()> {
1275         for_both!(*self, ref mut inner => inner.flush())
1276     }
1277 }
1278 
1279 impl<L, R, Target> AsRef<Target> for Either<L, R>
1280 where
1281     L: AsRef<Target>,
1282     R: AsRef<Target>,
1283 {
as_ref(&self) -> &Target1284     fn as_ref(&self) -> &Target {
1285         for_both!(*self, ref inner => inner.as_ref())
1286     }
1287 }
1288 
1289 macro_rules! impl_specific_ref_and_mut {
1290     ($t:ty, $($attr:meta),* ) => {
1291         $(#[$attr])*
1292         impl<L, R> AsRef<$t> for Either<L, R>
1293             where L: AsRef<$t>, R: AsRef<$t>
1294         {
1295             fn as_ref(&self) -> &$t {
1296                 for_both!(*self, ref inner => inner.as_ref())
1297             }
1298         }
1299 
1300         $(#[$attr])*
1301         impl<L, R> AsMut<$t> for Either<L, R>
1302             where L: AsMut<$t>, R: AsMut<$t>
1303         {
1304             fn as_mut(&mut self) -> &mut $t {
1305                 for_both!(*self, ref mut inner => inner.as_mut())
1306             }
1307         }
1308     };
1309 }
1310 
1311 impl_specific_ref_and_mut!(str,);
1312 impl_specific_ref_and_mut!(
1313     ::std::path::Path,
1314     cfg(feature = "use_std"),
1315     doc = "Requires crate feature `use_std`."
1316 );
1317 impl_specific_ref_and_mut!(
1318     ::std::ffi::OsStr,
1319     cfg(feature = "use_std"),
1320     doc = "Requires crate feature `use_std`."
1321 );
1322 impl_specific_ref_and_mut!(
1323     ::std::ffi::CStr,
1324     cfg(feature = "use_std"),
1325     doc = "Requires crate feature `use_std`."
1326 );
1327 
1328 impl<L, R, Target> AsRef<[Target]> for Either<L, R>
1329 where
1330     L: AsRef<[Target]>,
1331     R: AsRef<[Target]>,
1332 {
as_ref(&self) -> &[Target]1333     fn as_ref(&self) -> &[Target] {
1334         for_both!(*self, ref inner => inner.as_ref())
1335     }
1336 }
1337 
1338 impl<L, R, Target> AsMut<Target> for Either<L, R>
1339 where
1340     L: AsMut<Target>,
1341     R: AsMut<Target>,
1342 {
as_mut(&mut self) -> &mut Target1343     fn as_mut(&mut self) -> &mut Target {
1344         for_both!(*self, ref mut inner => inner.as_mut())
1345     }
1346 }
1347 
1348 impl<L, R, Target> AsMut<[Target]> for Either<L, R>
1349 where
1350     L: AsMut<[Target]>,
1351     R: AsMut<[Target]>,
1352 {
as_mut(&mut self) -> &mut [Target]1353     fn as_mut(&mut self) -> &mut [Target] {
1354         for_both!(*self, ref mut inner => inner.as_mut())
1355     }
1356 }
1357 
1358 impl<L, R> Deref for Either<L, R>
1359 where
1360     L: Deref,
1361     R: Deref<Target = L::Target>,
1362 {
1363     type Target = L::Target;
1364 
deref(&self) -> &Self::Target1365     fn deref(&self) -> &Self::Target {
1366         for_both!(*self, ref inner => &**inner)
1367     }
1368 }
1369 
1370 impl<L, R> DerefMut for Either<L, R>
1371 where
1372     L: DerefMut,
1373     R: DerefMut<Target = L::Target>,
1374 {
deref_mut(&mut self) -> &mut Self::Target1375     fn deref_mut(&mut self) -> &mut Self::Target {
1376         for_both!(*self, ref mut inner => &mut *inner)
1377     }
1378 }
1379 
1380 #[cfg(any(test, feature = "use_std"))]
1381 /// `Either` implements `Error` if *both* `L` and `R` implement it.
1382 ///
1383 /// Requires crate feature `"use_std"`
1384 impl<L, R> Error for Either<L, R>
1385 where
1386     L: Error,
1387     R: Error,
1388 {
source(&self) -> Option<&(dyn Error + 'static)>1389     fn source(&self) -> Option<&(dyn Error + 'static)> {
1390         for_both!(*self, ref inner => inner.source())
1391     }
1392 
1393     #[allow(deprecated)]
description(&self) -> &str1394     fn description(&self) -> &str {
1395         for_both!(*self, ref inner => inner.description())
1396     }
1397 
1398     #[allow(deprecated)]
cause(&self) -> Option<&dyn Error>1399     fn cause(&self) -> Option<&dyn Error> {
1400         for_both!(*self, ref inner => inner.cause())
1401     }
1402 }
1403 
1404 impl<L, R> fmt::Display for Either<L, R>
1405 where
1406     L: fmt::Display,
1407     R: fmt::Display,
1408 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1409     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410         for_both!(*self, ref inner => inner.fmt(f))
1411     }
1412 }
1413 
1414 #[test]
basic()1415 fn basic() {
1416     let mut e = Left(2);
1417     let r = Right(2);
1418     assert_eq!(e, Left(2));
1419     e = r;
1420     assert_eq!(e, Right(2));
1421     assert_eq!(e.left(), None);
1422     assert_eq!(e.right(), Some(2));
1423     assert_eq!(e.as_ref().right(), Some(&2));
1424     assert_eq!(e.as_mut().right(), Some(&mut 2));
1425 }
1426 
1427 #[test]
macros()1428 fn macros() {
1429     use std::string::String;
1430 
1431     fn a() -> Either<u32, u32> {
1432         let x: u32 = try_left!(Right(1337u32));
1433         Left(x * 2)
1434     }
1435     assert_eq!(a(), Right(1337));
1436 
1437     fn b() -> Either<String, &'static str> {
1438         Right(try_right!(Left("foo bar")))
1439     }
1440     assert_eq!(b(), Left(String::from("foo bar")));
1441 }
1442 
1443 #[test]
deref()1444 fn deref() {
1445     use std::string::String;
1446 
1447     fn is_str(_: &str) {}
1448     let value: Either<String, &str> = Left(String::from("test"));
1449     is_str(&*value);
1450 }
1451 
1452 #[test]
iter()1453 fn iter() {
1454     let x = 3;
1455     let mut iter = match x {
1456         3 => Left(0..10),
1457         _ => Right(17..),
1458     };
1459 
1460     assert_eq!(iter.next(), Some(0));
1461     assert_eq!(iter.count(), 9);
1462 }
1463 
1464 #[test]
seek()1465 fn seek() {
1466     use std::io;
1467 
1468     let use_empty = false;
1469     let mut mockdata = [0x00; 256];
1470     for i in 0..256 {
1471         mockdata[i] = i as u8;
1472     }
1473 
1474     let mut reader = if use_empty {
1475         // Empty didn't impl Seek until Rust 1.51
1476         Left(io::Cursor::new([]))
1477     } else {
1478         Right(io::Cursor::new(&mockdata[..]))
1479     };
1480 
1481     let mut buf = [0u8; 16];
1482     assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1483     assert_eq!(buf, mockdata[..buf.len()]);
1484 
1485     // the first read should advance the cursor and return the next 16 bytes thus the `ne`
1486     assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1487     assert_ne!(buf, mockdata[..buf.len()]);
1488 
1489     // if the seek operation fails it should read 16..31 instead of 0..15
1490     reader.seek(io::SeekFrom::Start(0)).unwrap();
1491     assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1492     assert_eq!(buf, mockdata[..buf.len()]);
1493 }
1494 
1495 #[test]
read_write()1496 fn read_write() {
1497     use std::io;
1498 
1499     let use_stdio = false;
1500     let mockdata = [0xff; 256];
1501 
1502     let mut reader = if use_stdio {
1503         Left(io::stdin())
1504     } else {
1505         Right(&mockdata[..])
1506     };
1507 
1508     let mut buf = [0u8; 16];
1509     assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1510     assert_eq!(&buf, &mockdata[..buf.len()]);
1511 
1512     let mut mockbuf = [0u8; 256];
1513     let mut writer = if use_stdio {
1514         Left(io::stdout())
1515     } else {
1516         Right(&mut mockbuf[..])
1517     };
1518 
1519     let buf = [1u8; 16];
1520     assert_eq!(writer.write(&buf).unwrap(), buf.len());
1521 }
1522 
1523 #[test]
error()1524 fn error() {
1525     let invalid_utf8 = b"\xff";
1526     #[allow(invalid_from_utf8)]
1527     let res = if let Err(error) = ::std::str::from_utf8(invalid_utf8) {
1528         Err(Left(error))
1529     } else if let Err(error) = "x".parse::<i32>() {
1530         Err(Right(error))
1531     } else {
1532         Ok(())
1533     };
1534     assert!(res.is_err());
1535     #[allow(deprecated)]
1536     res.unwrap_err().description(); // make sure this can be called
1537 }
1538 
1539 /// A helper macro to check if AsRef and AsMut are implemented for a given type.
1540 macro_rules! check_t {
1541     ($t:ty) => {{
1542         fn check_ref<T: AsRef<$t>>() {}
1543         fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>>() {
1544             check_ref::<Either<T1, T2>>()
1545         }
1546         fn check_mut<T: AsMut<$t>>() {}
1547         fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>>() {
1548             check_mut::<Either<T1, T2>>()
1549         }
1550     }};
1551 }
1552 
1553 // This "unused" method is here to ensure that compilation doesn't fail on given types.
_unsized_ref_propagation()1554 fn _unsized_ref_propagation() {
1555     check_t!(str);
1556 
1557     fn check_array_ref<T: AsRef<[Item]>, Item>() {}
1558     fn check_array_mut<T: AsMut<[Item]>, Item>() {}
1559 
1560     fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, Item>() {
1561         check_array_ref::<Either<T1, T2>, _>()
1562     }
1563 
1564     fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, Item>() {
1565         check_array_mut::<Either<T1, T2>, _>()
1566     }
1567 }
1568 
1569 // This "unused" method is here to ensure that compilation doesn't fail on given types.
1570 #[cfg(feature = "use_std")]
_unsized_std_propagation()1571 fn _unsized_std_propagation() {
1572     check_t!(::std::path::Path);
1573     check_t!(::std::ffi::OsStr);
1574     check_t!(::std::ffi::CStr);
1575 }
1576