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 #![cfg_attr(all(not(test), not(feature = "use_std")), no_std)]
17 #[cfg(all(not(test), not(feature = "use_std")))]
18 extern crate core as std;
19 
20 #[cfg(feature = "serde")]
21 #[macro_use]
22 extern crate serde;
23 
24 #[cfg(feature = "serde")]
25 pub mod serde_untagged;
26 
27 #[cfg(feature = "serde")]
28 pub mod serde_untagged_optional;
29 
30 use std::convert::{AsMut, AsRef};
31 use std::fmt;
32 use std::iter;
33 use std::ops::Deref;
34 use std::ops::DerefMut;
35 
36 #[cfg(any(test, feature = "use_std"))]
37 use std::error::Error;
38 #[cfg(any(test, feature = "use_std"))]
39 use std::io::{self, BufRead, Read, Write};
40 
41 pub use Either::{Left, Right};
42 
43 /// The enum `Either` with variants `Left` and `Right` is a general purpose
44 /// sum type with two cases.
45 ///
46 /// The `Either` type is symmetric and treats its variants the same way, without
47 /// preference.
48 /// (For representing success or error, use the regular `Result` enum instead.)
49 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
50 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
51 pub enum Either<L, R> {
52     /// A value of type `L`.
53     Left(L),
54     /// A value of type `R`.
55     Right(R),
56 }
57 
58 macro_rules! either {
59     ($value:expr, $pattern:pat => $result:expr) => {
60         match $value {
61             Either::Left($pattern) => $result,
62             Either::Right($pattern) => $result,
63         }
64     };
65 }
66 
67 /// Macro for unwrapping the left side of an `Either`, which fails early
68 /// with the opposite side. Can only be used in functions that return
69 /// `Either` because of the early return of `Right` that it provides.
70 ///
71 /// See also `try_right!` for its dual, which applies the same just to the
72 /// right side.
73 ///
74 /// # Example
75 ///
76 /// ```
77 /// #[macro_use] extern crate either;
78 /// use either::{Either, Left, Right};
79 ///
80 /// fn twice(wrapper: Either<u32, &str>) -> Either<u32, &str> {
81 ///     let value = try_left!(wrapper);
82 ///     Left(value * 2)
83 /// }
84 ///
85 /// fn main() {
86 ///     assert_eq!(twice(Left(2)), Left(4));
87 ///     assert_eq!(twice(Right("ups")), Right("ups"));
88 /// }
89 /// ```
90 #[macro_export]
91 macro_rules! try_left {
92     ($expr:expr) => {
93         match $expr {
94             $crate::Left(val) => val,
95             $crate::Right(err) => return $crate::Right(::std::convert::From::from(err)),
96         }
97     };
98 }
99 
100 /// Dual to `try_left!`, see its documentation for more information.
101 #[macro_export]
102 macro_rules! try_right {
103     ($expr:expr) => {
104         match $expr {
105             $crate::Left(err) => return $crate::Left(::std::convert::From::from(err)),
106             $crate::Right(val) => val,
107         }
108     };
109 }
110 
111 impl<L, R> Either<L, R> {
112     /// Return true if the value is the `Left` variant.
113     ///
114     /// ```
115     /// use either::*;
116     ///
117     /// let values = [Left(1), Right("the right value")];
118     /// assert_eq!(values[0].is_left(), true);
119     /// assert_eq!(values[1].is_left(), false);
120     /// ```
is_left(&self) -> bool121     pub fn is_left(&self) -> bool {
122         match *self {
123             Left(_) => true,
124             Right(_) => false,
125         }
126     }
127 
128     /// Return true if the value is the `Right` variant.
129     ///
130     /// ```
131     /// use either::*;
132     ///
133     /// let values = [Left(1), Right("the right value")];
134     /// assert_eq!(values[0].is_right(), false);
135     /// assert_eq!(values[1].is_right(), true);
136     /// ```
is_right(&self) -> bool137     pub fn is_right(&self) -> bool {
138         !self.is_left()
139     }
140 
141     /// Convert the left side of `Either<L, R>` to an `Option<L>`.
142     ///
143     /// ```
144     /// use either::*;
145     ///
146     /// let left: Either<_, ()> = Left("some value");
147     /// assert_eq!(left.left(),  Some("some value"));
148     ///
149     /// let right: Either<(), _> = Right(321);
150     /// assert_eq!(right.left(), None);
151     /// ```
left(self) -> Option<L>152     pub fn left(self) -> Option<L> {
153         match self {
154             Left(l) => Some(l),
155             Right(_) => None,
156         }
157     }
158 
159     /// Convert the right side of `Either<L, R>` to an `Option<R>`.
160     ///
161     /// ```
162     /// use either::*;
163     ///
164     /// let left: Either<_, ()> = Left("some value");
165     /// assert_eq!(left.right(),  None);
166     ///
167     /// let right: Either<(), _> = Right(321);
168     /// assert_eq!(right.right(), Some(321));
169     /// ```
right(self) -> Option<R>170     pub fn right(self) -> Option<R> {
171         match self {
172             Left(_) => None,
173             Right(r) => Some(r),
174         }
175     }
176 
177     /// Convert `&Either<L, R>` to `Either<&L, &R>`.
178     ///
179     /// ```
180     /// use either::*;
181     ///
182     /// let left: Either<_, ()> = Left("some value");
183     /// assert_eq!(left.as_ref(), Left(&"some value"));
184     ///
185     /// let right: Either<(), _> = Right("some value");
186     /// assert_eq!(right.as_ref(), Right(&"some value"));
187     /// ```
as_ref(&self) -> Either<&L, &R>188     pub fn as_ref(&self) -> Either<&L, &R> {
189         match *self {
190             Left(ref inner) => Left(inner),
191             Right(ref inner) => Right(inner),
192         }
193     }
194 
195     /// Convert `&mut Either<L, R>` to `Either<&mut L, &mut R>`.
196     ///
197     /// ```
198     /// use either::*;
199     ///
200     /// fn mutate_left(value: &mut Either<u32, u32>) {
201     ///     if let Some(l) = value.as_mut().left() {
202     ///         *l = 999;
203     ///     }
204     /// }
205     ///
206     /// let mut left = Left(123);
207     /// let mut right = Right(123);
208     /// mutate_left(&mut left);
209     /// mutate_left(&mut right);
210     /// assert_eq!(left, Left(999));
211     /// assert_eq!(right, Right(123));
212     /// ```
as_mut(&mut self) -> Either<&mut L, &mut R>213     pub fn as_mut(&mut self) -> Either<&mut L, &mut R> {
214         match *self {
215             Left(ref mut inner) => Left(inner),
216             Right(ref mut inner) => Right(inner),
217         }
218     }
219 
220     /// Convert `Either<L, R>` to `Either<R, L>`.
221     ///
222     /// ```
223     /// use either::*;
224     ///
225     /// let left: Either<_, ()> = Left(123);
226     /// assert_eq!(left.flip(), Right(123));
227     ///
228     /// let right: Either<(), _> = Right("some value");
229     /// assert_eq!(right.flip(), Left("some value"));
230     /// ```
flip(self) -> Either<R, L>231     pub fn flip(self) -> Either<R, L> {
232         match self {
233             Left(l) => Right(l),
234             Right(r) => Left(r),
235         }
236     }
237 
238     /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the
239     /// result in `Left`.
240     ///
241     /// ```
242     /// use either::*;
243     ///
244     /// let left: Either<_, u32> = Left(123);
245     /// assert_eq!(left.map_left(|x| x * 2), Left(246));
246     ///
247     /// let right: Either<u32, _> = Right(123);
248     /// assert_eq!(right.map_left(|x| x * 2), Right(123));
249     /// ```
map_left<F, M>(self, f: F) -> Either<M, R> where F: FnOnce(L) -> M,250     pub fn map_left<F, M>(self, f: F) -> Either<M, R>
251     where
252         F: FnOnce(L) -> M,
253     {
254         match self {
255             Left(l) => Left(f(l)),
256             Right(r) => Right(r),
257         }
258     }
259 
260     /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the
261     /// result in `Right`.
262     ///
263     /// ```
264     /// use either::*;
265     ///
266     /// let left: Either<_, u32> = Left(123);
267     /// assert_eq!(left.map_right(|x| x * 2), Left(123));
268     ///
269     /// let right: Either<u32, _> = Right(123);
270     /// assert_eq!(right.map_right(|x| x * 2), Right(246));
271     /// ```
map_right<F, S>(self, f: F) -> Either<L, S> where F: FnOnce(R) -> S,272     pub fn map_right<F, S>(self, f: F) -> Either<L, S>
273     where
274         F: FnOnce(R) -> S,
275     {
276         match self {
277             Left(l) => Left(l),
278             Right(r) => Right(f(r)),
279         }
280     }
281 
282     /// Apply one of two functions depending on contents, unifying their result. If the value is
283     /// `Left(L)` then the first function `f` is applied; if it is `Right(R)` then the second
284     /// function `g` is applied.
285     ///
286     /// ```
287     /// use either::*;
288     ///
289     /// fn square(n: u32) -> i32 { (n * n) as i32 }
290     /// fn negate(n: i32) -> i32 { -n }
291     ///
292     /// let left: Either<u32, i32> = Left(4);
293     /// assert_eq!(left.either(square, negate), 16);
294     ///
295     /// let right: Either<u32, i32> = Right(-4);
296     /// assert_eq!(right.either(square, negate), 4);
297     /// ```
either<F, G, T>(self, f: F, g: G) -> T where F: FnOnce(L) -> T, G: FnOnce(R) -> T,298     pub fn either<F, G, T>(self, f: F, g: G) -> T
299     where
300         F: FnOnce(L) -> T,
301         G: FnOnce(R) -> T,
302     {
303         match self {
304             Left(l) => f(l),
305             Right(r) => g(r),
306         }
307     }
308 
309     /// Like `either`, but provide some context to whichever of the
310     /// functions ends up being called.
311     ///
312     /// ```
313     /// // In this example, the context is a mutable reference
314     /// use either::*;
315     ///
316     /// let mut result = Vec::new();
317     ///
318     /// let values = vec![Left(2), Right(2.7)];
319     ///
320     /// for value in values {
321     ///     value.either_with(&mut result,
322     ///                       |ctx, integer| ctx.push(integer),
323     ///                       |ctx, real| ctx.push(f64::round(real) as i32));
324     /// }
325     ///
326     /// assert_eq!(result, vec![2, 3]);
327     /// ```
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,328     pub fn either_with<Ctx, F, G, T>(self, ctx: Ctx, f: F, g: G) -> T
329     where
330         F: FnOnce(Ctx, L) -> T,
331         G: FnOnce(Ctx, R) -> T,
332     {
333         match self {
334             Left(l) => f(ctx, l),
335             Right(r) => g(ctx, r),
336         }
337     }
338 
339     /// Apply the function `f` on the value in the `Left` variant if it is present.
340     ///
341     /// ```
342     /// use either::*;
343     ///
344     /// let left: Either<_, u32> = Left(123);
345     /// assert_eq!(left.left_and_then::<_,()>(|x| Right(x * 2)), Right(246));
346     ///
347     /// let right: Either<u32, _> = Right(123);
348     /// assert_eq!(right.left_and_then(|x| Right::<(), _>(x * 2)), Right(123));
349     /// ```
left_and_then<F, S>(self, f: F) -> Either<S, R> where F: FnOnce(L) -> Either<S, R>,350     pub fn left_and_then<F, S>(self, f: F) -> Either<S, R>
351     where
352         F: FnOnce(L) -> Either<S, R>,
353     {
354         match self {
355             Left(l) => f(l),
356             Right(r) => Right(r),
357         }
358     }
359 
360     /// Apply the function `f` on the value in the `Right` variant if it is present.
361     ///
362     /// ```
363     /// use either::*;
364     ///
365     /// let left: Either<_, u32> = Left(123);
366     /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123));
367     ///
368     /// let right: Either<u32, _> = Right(123);
369     /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246));
370     /// ```
right_and_then<F, S>(self, f: F) -> Either<L, S> where F: FnOnce(R) -> Either<L, S>,371     pub fn right_and_then<F, S>(self, f: F) -> Either<L, S>
372     where
373         F: FnOnce(R) -> Either<L, S>,
374     {
375         match self {
376             Left(l) => Left(l),
377             Right(r) => f(r),
378         }
379     }
380 
381     /// Convert the inner value to an iterator.
382     ///
383     /// ```
384     /// use either::*;
385     ///
386     /// let left: Either<_, Vec<u32>> = Left(vec![1, 2, 3, 4, 5]);
387     /// let mut right: Either<Vec<u32>, _> = Right(vec![]);
388     /// right.extend(left.into_iter());
389     /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5]));
390     /// ```
into_iter(self) -> Either<L::IntoIter, R::IntoIter> where L: IntoIterator, R: IntoIterator<Item = L::Item>,391     pub fn into_iter(self) -> Either<L::IntoIter, R::IntoIter>
392     where
393         L: IntoIterator,
394         R: IntoIterator<Item = L::Item>,
395     {
396         match self {
397             Left(l) => Left(l.into_iter()),
398             Right(r) => Right(r.into_iter()),
399         }
400     }
401 
402     /// Return left value or given value
403     ///
404     /// Arguments passed to `left_or` are eagerly evaluated; if you are passing
405     /// the result of a function call, it is recommended to use [`left_or_else`],
406     /// which is lazily evaluated.
407     ///
408     /// [`left_or_else`]: #method.left_or_else
409     ///
410     /// # Examples
411     ///
412     /// ```
413     /// # use either::*;
414     /// let left: Either<&str, &str> = Left("left");
415     /// assert_eq!(left.left_or("foo"), "left");
416     ///
417     /// let right: Either<&str, &str> = Right("right");
418     /// assert_eq!(right.left_or("left"), "left");
419     /// ```
left_or(self, other: L) -> L420     pub fn left_or(self, other: L) -> L {
421         match self {
422             Either::Left(l) => l,
423             Either::Right(_) => other,
424         }
425     }
426 
427     /// Return left or a default
428     ///
429     /// # Examples
430     ///
431     /// ```
432     /// # use either::*;
433     /// let left: Either<String, u32> = Left("left".to_string());
434     /// assert_eq!(left.left_or_default(), "left");
435     ///
436     /// let right: Either<String, u32> = Right(42);
437     /// assert_eq!(right.left_or_default(), String::default());
438     /// ```
left_or_default(self) -> L where L: Default,439     pub fn left_or_default(self) -> L
440     where
441         L: Default,
442     {
443         match self {
444             Either::Left(l) => l,
445             Either::Right(_) => L::default(),
446         }
447     }
448 
449     /// Returns left value or computes it from a closure
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// # use either::*;
455     /// let left: Either<String, u32> = Left("3".to_string());
456     /// assert_eq!(left.left_or_else(|_| unreachable!()), "3");
457     ///
458     /// let right: Either<String, u32> = Right(3);
459     /// assert_eq!(right.left_or_else(|x| x.to_string()), "3");
460     /// ```
left_or_else<F>(self, f: F) -> L where F: FnOnce(R) -> L,461     pub fn left_or_else<F>(self, f: F) -> L
462     where
463         F: FnOnce(R) -> L,
464     {
465         match self {
466             Either::Left(l) => l,
467             Either::Right(r) => f(r),
468         }
469     }
470 
471     /// Return right value or given value
472     ///
473     /// Arguments passed to `right_or` are eagerly evaluated; if you are passing
474     /// the result of a function call, it is recommended to use [`right_or_else`],
475     /// which is lazily evaluated.
476     ///
477     /// [`right_or_else`]: #method.right_or_else
478     ///
479     /// # Examples
480     ///
481     /// ```
482     /// # use either::*;
483     /// let right: Either<&str, &str> = Right("right");
484     /// assert_eq!(right.right_or("foo"), "right");
485     ///
486     /// let left: Either<&str, &str> = Left("left");
487     /// assert_eq!(left.right_or("right"), "right");
488     /// ```
right_or(self, other: R) -> R489     pub fn right_or(self, other: R) -> R {
490         match self {
491             Either::Left(_) => other,
492             Either::Right(r) => r,
493         }
494     }
495 
496     /// Return right or a default
497     ///
498     /// # Examples
499     ///
500     /// ```
501     /// # use either::*;
502     /// let left: Either<String, u32> = Left("left".to_string());
503     /// assert_eq!(left.right_or_default(), u32::default());
504     ///
505     /// let right: Either<String, u32> = Right(42);
506     /// assert_eq!(right.right_or_default(), 42);
507     /// ```
right_or_default(self) -> R where R: Default,508     pub fn right_or_default(self) -> R
509     where
510         R: Default,
511     {
512         match self {
513             Either::Left(_) => R::default(),
514             Either::Right(r) => r,
515         }
516     }
517 
518     /// Returns right value or computes it from a closure
519     ///
520     /// # Examples
521     ///
522     /// ```
523     /// # use either::*;
524     /// let left: Either<String, u32> = Left("3".to_string());
525     /// assert_eq!(left.right_or_else(|x| x.parse().unwrap()), 3);
526     ///
527     /// let right: Either<String, u32> = Right(3);
528     /// assert_eq!(right.right_or_else(|_| unreachable!()), 3);
529     /// ```
right_or_else<F>(self, f: F) -> R where F: FnOnce(L) -> R,530     pub fn right_or_else<F>(self, f: F) -> R
531     where
532         F: FnOnce(L) -> R,
533     {
534         match self {
535             Either::Left(l) => f(l),
536             Either::Right(r) => r,
537         }
538     }
539 
540     /// Returns the left value
541     ///
542     /// # Examples
543     ///
544     /// ```
545     /// # use either::*;
546     /// let left: Either<_, ()> = Left(3);
547     /// assert_eq!(left.unwrap_left(), 3);
548     /// ```
549     ///
550     /// # Panics
551     ///
552     /// When `Either` is a `Right` value
553     ///
554     /// ```should_panic
555     /// # use either::*;
556     /// let right: Either<(), _> = Right(3);
557     /// right.unwrap_left();
558     /// ```
unwrap_left(self) -> L where R: std::fmt::Debug,559     pub fn unwrap_left(self) -> L
560     where
561         R: std::fmt::Debug,
562     {
563         match self {
564             Either::Left(l) => l,
565             Either::Right(r) => {
566                 panic!("called `Either::unwrap_left()` on a `Right` value: {:?}", r)
567             }
568         }
569     }
570 
571     /// Returns the right value
572     ///
573     /// # Examples
574     ///
575     /// ```
576     /// # use either::*;
577     /// let right: Either<(), _> = Right(3);
578     /// assert_eq!(right.unwrap_right(), 3);
579     /// ```
580     ///
581     /// # Panics
582     ///
583     /// When `Either` is a `Left` value
584     ///
585     /// ```should_panic
586     /// # use either::*;
587     /// let left: Either<_, ()> = Left(3);
588     /// left.unwrap_right();
589     /// ```
unwrap_right(self) -> R where L: std::fmt::Debug,590     pub fn unwrap_right(self) -> R
591     where
592         L: std::fmt::Debug,
593     {
594         match self {
595             Either::Right(r) => r,
596             Either::Left(l) => panic!("called `Either::unwrap_right()` on a `Left` value: {:?}", l),
597         }
598     }
599 
600     /// Returns the left value
601     ///
602     /// # Examples
603     ///
604     /// ```
605     /// # use either::*;
606     /// let left: Either<_, ()> = Left(3);
607     /// assert_eq!(left.expect_left("value was Right"), 3);
608     /// ```
609     ///
610     /// # Panics
611     ///
612     /// When `Either` is a `Right` value
613     ///
614     /// ```should_panic
615     /// # use either::*;
616     /// let right: Either<(), _> = Right(3);
617     /// right.expect_left("value was Right");
618     /// ```
expect_left(self, msg: &str) -> L where R: std::fmt::Debug,619     pub fn expect_left(self, msg: &str) -> L
620     where
621         R: std::fmt::Debug,
622     {
623         match self {
624             Either::Left(l) => l,
625             Either::Right(r) => panic!("{}: {:?}", msg, r),
626         }
627     }
628 
629     /// Returns the right value
630     ///
631     /// # Examples
632     ///
633     /// ```
634     /// # use either::*;
635     /// let right: Either<(), _> = Right(3);
636     /// assert_eq!(right.expect_right("value was Left"), 3);
637     /// ```
638     ///
639     /// # Panics
640     ///
641     /// When `Either` is a `Left` value
642     ///
643     /// ```should_panic
644     /// # use either::*;
645     /// let left: Either<_, ()> = Left(3);
646     /// left.expect_right("value was Right");
647     /// ```
expect_right(self, msg: &str) -> R where L: std::fmt::Debug,648     pub fn expect_right(self, msg: &str) -> R
649     where
650         L: std::fmt::Debug,
651     {
652         match self {
653             Either::Right(r) => r,
654             Either::Left(l) => panic!("{}: {:?}", msg, l),
655         }
656     }
657 }
658 
659 impl<T, L, R> Either<(T, L), (T, R)> {
660     /// Factor out a homogeneous type from an either of pairs.
661     ///
662     /// Here, the homogeneous type is the first element of the pairs.
663     ///
664     /// ```
665     /// use either::*;
666     /// let left: Either<_, (u32, String)> = Left((123, vec![0]));
667     /// assert_eq!(left.factor_first().0, 123);
668     ///
669     /// let right: Either<(u32, Vec<u8>), _> = Right((123, String::new()));
670     /// assert_eq!(right.factor_first().0, 123);
671     /// ```
factor_first(self) -> (T, Either<L, R>)672     pub fn factor_first(self) -> (T, Either<L, R>) {
673         match self {
674             Left((t, l)) => (t, Left(l)),
675             Right((t, r)) => (t, Right(r)),
676         }
677     }
678 }
679 
680 impl<T, L, R> Either<(L, T), (R, T)> {
681     /// Factor out a homogeneous type from an either of pairs.
682     ///
683     /// Here, the homogeneous type is the second element of the pairs.
684     ///
685     /// ```
686     /// use either::*;
687     /// let left: Either<_, (String, u32)> = Left((vec![0], 123));
688     /// assert_eq!(left.factor_second().1, 123);
689     ///
690     /// let right: Either<(Vec<u8>, u32), _> = Right((String::new(), 123));
691     /// assert_eq!(right.factor_second().1, 123);
692     /// ```
factor_second(self) -> (Either<L, R>, T)693     pub fn factor_second(self) -> (Either<L, R>, T) {
694         match self {
695             Left((l, t)) => (Left(l), t),
696             Right((r, t)) => (Right(r), t),
697         }
698     }
699 }
700 
701 impl<T> Either<T, T> {
702     /// Extract the value of an either over two equivalent types.
703     ///
704     /// ```
705     /// use either::*;
706     ///
707     /// let left: Either<_, u32> = Left(123);
708     /// assert_eq!(left.into_inner(), 123);
709     ///
710     /// let right: Either<u32, _> = Right(123);
711     /// assert_eq!(right.into_inner(), 123);
712     /// ```
into_inner(self) -> T713     pub fn into_inner(self) -> T {
714         either!(self, inner => inner)
715     }
716 
717     /// Map `f` over the contained value and return the result in the
718     /// corresponding variant.
719     ///
720     /// ```
721     /// use either::*;
722     ///
723     /// let value: Either<_, i32> = Right(42);
724     ///
725     /// let other = value.map(|x| x * 2);
726     /// assert_eq!(other, Right(84));
727     /// ```
map<F, M>(self, f: F) -> Either<M, M> where F: FnOnce(T) -> M,728     pub fn map<F, M>(self, f: F) -> Either<M, M>
729     where
730         F: FnOnce(T) -> M,
731     {
732         match self {
733             Left(l) => Left(f(l)),
734             Right(r) => Right(f(r)),
735         }
736     }
737 }
738 
739 /// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`.
740 impl<L, R> From<Result<R, L>> for Either<L, R> {
from(r: Result<R, L>) -> Self741     fn from(r: Result<R, L>) -> Self {
742         match r {
743             Err(e) => Left(e),
744             Ok(o) => Right(o),
745         }
746     }
747 }
748 
749 /// Convert from `Either` to `Result` with `Right => Ok` and `Left => Err`.
750 impl<L, R> Into<Result<R, L>> for Either<L, R> {
into(self) -> Result<R, L>751     fn into(self) -> Result<R, L> {
752         match self {
753             Left(l) => Err(l),
754             Right(r) => Ok(r),
755         }
756     }
757 }
758 
759 impl<L, R, A> Extend<A> for Either<L, R>
760 where
761     L: Extend<A>,
762     R: Extend<A>,
763 {
extend<T>(&mut self, iter: T) where T: IntoIterator<Item = A>,764     fn extend<T>(&mut self, iter: T)
765     where
766         T: IntoIterator<Item = A>,
767     {
768         either!(*self, ref mut inner => inner.extend(iter))
769     }
770 }
771 
772 /// `Either<L, R>` is an iterator if both `L` and `R` are iterators.
773 impl<L, R> Iterator for Either<L, R>
774 where
775     L: Iterator,
776     R: Iterator<Item = L::Item>,
777 {
778     type Item = L::Item;
779 
next(&mut self) -> Option<Self::Item>780     fn next(&mut self) -> Option<Self::Item> {
781         either!(*self, ref mut inner => inner.next())
782     }
783 
size_hint(&self) -> (usize, Option<usize>)784     fn size_hint(&self) -> (usize, Option<usize>) {
785         either!(*self, ref inner => inner.size_hint())
786     }
787 
fold<Acc, G>(self, init: Acc, f: G) -> Acc where G: FnMut(Acc, Self::Item) -> Acc,788     fn fold<Acc, G>(self, init: Acc, f: G) -> Acc
789     where
790         G: FnMut(Acc, Self::Item) -> Acc,
791     {
792         either!(self, inner => inner.fold(init, f))
793     }
794 
count(self) -> usize795     fn count(self) -> usize {
796         either!(self, inner => inner.count())
797     }
798 
last(self) -> Option<Self::Item>799     fn last(self) -> Option<Self::Item> {
800         either!(self, inner => inner.last())
801     }
802 
nth(&mut self, n: usize) -> Option<Self::Item>803     fn nth(&mut self, n: usize) -> Option<Self::Item> {
804         either!(*self, ref mut inner => inner.nth(n))
805     }
806 
collect<B>(self) -> B where B: iter::FromIterator<Self::Item>,807     fn collect<B>(self) -> B
808     where
809         B: iter::FromIterator<Self::Item>,
810     {
811         either!(self, inner => inner.collect())
812     }
813 
all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool,814     fn all<F>(&mut self, f: F) -> bool
815     where
816         F: FnMut(Self::Item) -> bool,
817     {
818         either!(*self, ref mut inner => inner.all(f))
819     }
820 }
821 
822 impl<L, R> DoubleEndedIterator for Either<L, R>
823 where
824     L: DoubleEndedIterator,
825     R: DoubleEndedIterator<Item = L::Item>,
826 {
next_back(&mut self) -> Option<Self::Item>827     fn next_back(&mut self) -> Option<Self::Item> {
828         either!(*self, ref mut inner => inner.next_back())
829     }
830 }
831 
832 impl<L, R> ExactSizeIterator for Either<L, R>
833 where
834     L: ExactSizeIterator,
835     R: ExactSizeIterator<Item = L::Item>,
836 {
837 }
838 
839 #[cfg(any(test, feature = "use_std"))]
840 /// `Either<L, R>` implements `Read` if both `L` and `R` do.
841 ///
842 /// Requires crate feature `"use_std"`
843 impl<L, R> Read for Either<L, R>
844 where
845     L: Read,
846     R: Read,
847 {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>848     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
849         either!(*self, ref mut inner => inner.read(buf))
850     }
851 
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>852     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
853         either!(*self, ref mut inner => inner.read_to_end(buf))
854     }
855 }
856 
857 #[cfg(any(test, feature = "use_std"))]
858 /// Requires crate feature `"use_std"`
859 impl<L, R> BufRead for Either<L, R>
860 where
861     L: BufRead,
862     R: BufRead,
863 {
fill_buf(&mut self) -> io::Result<&[u8]>864     fn fill_buf(&mut self) -> io::Result<&[u8]> {
865         either!(*self, ref mut inner => inner.fill_buf())
866     }
867 
consume(&mut self, amt: usize)868     fn consume(&mut self, amt: usize) {
869         either!(*self, ref mut inner => inner.consume(amt))
870     }
871 }
872 
873 #[cfg(any(test, feature = "use_std"))]
874 /// `Either<L, R>` implements `Write` if both `L` and `R` do.
875 ///
876 /// Requires crate feature `"use_std"`
877 impl<L, R> Write for Either<L, R>
878 where
879     L: Write,
880     R: Write,
881 {
write(&mut self, buf: &[u8]) -> io::Result<usize>882     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
883         either!(*self, ref mut inner => inner.write(buf))
884     }
885 
flush(&mut self) -> io::Result<()>886     fn flush(&mut self) -> io::Result<()> {
887         either!(*self, ref mut inner => inner.flush())
888     }
889 }
890 
891 impl<L, R, Target> AsRef<Target> for Either<L, R>
892 where
893     L: AsRef<Target>,
894     R: AsRef<Target>,
895 {
as_ref(&self) -> &Target896     fn as_ref(&self) -> &Target {
897         either!(*self, ref inner => inner.as_ref())
898     }
899 }
900 
901 macro_rules! impl_specific_ref_and_mut {
902     ($t:ty, $($attr:meta),* ) => {
903         $(#[$attr])*
904         impl<L, R> AsRef<$t> for Either<L, R>
905             where L: AsRef<$t>, R: AsRef<$t>
906         {
907             fn as_ref(&self) -> &$t {
908                 either!(*self, ref inner => inner.as_ref())
909             }
910         }
911 
912         $(#[$attr])*
913         impl<L, R> AsMut<$t> for Either<L, R>
914             where L: AsMut<$t>, R: AsMut<$t>
915         {
916             fn as_mut(&mut self) -> &mut $t {
917                 either!(*self, ref mut inner => inner.as_mut())
918             }
919         }
920     };
921 }
922 
923 impl_specific_ref_and_mut!(str,);
924 impl_specific_ref_and_mut!(
925     ::std::path::Path,
926     cfg(feature = "use_std"),
927     doc = "Requires crate feature `use_std`."
928 );
929 impl_specific_ref_and_mut!(
930     ::std::ffi::OsStr,
931     cfg(feature = "use_std"),
932     doc = "Requires crate feature `use_std`."
933 );
934 impl_specific_ref_and_mut!(
935     ::std::ffi::CStr,
936     cfg(feature = "use_std"),
937     doc = "Requires crate feature `use_std`."
938 );
939 
940 impl<L, R, Target> AsRef<[Target]> for Either<L, R>
941 where
942     L: AsRef<[Target]>,
943     R: AsRef<[Target]>,
944 {
as_ref(&self) -> &[Target]945     fn as_ref(&self) -> &[Target] {
946         either!(*self, ref inner => inner.as_ref())
947     }
948 }
949 
950 impl<L, R, Target> AsMut<Target> for Either<L, R>
951 where
952     L: AsMut<Target>,
953     R: AsMut<Target>,
954 {
as_mut(&mut self) -> &mut Target955     fn as_mut(&mut self) -> &mut Target {
956         either!(*self, ref mut inner => inner.as_mut())
957     }
958 }
959 
960 impl<L, R, Target> AsMut<[Target]> for Either<L, R>
961 where
962     L: AsMut<[Target]>,
963     R: AsMut<[Target]>,
964 {
as_mut(&mut self) -> &mut [Target]965     fn as_mut(&mut self) -> &mut [Target] {
966         either!(*self, ref mut inner => inner.as_mut())
967     }
968 }
969 
970 impl<L, R> Deref for Either<L, R>
971 where
972     L: Deref,
973     R: Deref<Target = L::Target>,
974 {
975     type Target = L::Target;
976 
deref(&self) -> &Self::Target977     fn deref(&self) -> &Self::Target {
978         either!(*self, ref inner => &*inner)
979     }
980 }
981 
982 impl<L, R> DerefMut for Either<L, R>
983 where
984     L: DerefMut,
985     R: DerefMut<Target = L::Target>,
986 {
deref_mut(&mut self) -> &mut Self::Target987     fn deref_mut(&mut self) -> &mut Self::Target {
988         either!(*self, ref mut inner => &mut *inner)
989     }
990 }
991 
992 #[cfg(any(test, feature = "use_std"))]
993 /// `Either` implements `Error` if *both* `L` and `R` implement it.
994 impl<L, R> Error for Either<L, R>
995 where
996     L: Error,
997     R: Error,
998 {
999     #[allow(deprecated)]
description(&self) -> &str1000     fn description(&self) -> &str {
1001         either!(*self, ref inner => inner.description())
1002     }
1003 
1004     #[allow(deprecated)]
1005     #[allow(unknown_lints, bare_trait_objects)]
cause(&self) -> Option<&Error>1006     fn cause(&self) -> Option<&Error> {
1007         either!(*self, ref inner => inner.cause())
1008     }
1009 }
1010 
1011 impl<L, R> fmt::Display for Either<L, R>
1012 where
1013     L: fmt::Display,
1014     R: fmt::Display,
1015 {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1016     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1017         either!(*self, ref inner => inner.fmt(f))
1018     }
1019 }
1020 
1021 #[test]
basic()1022 fn basic() {
1023     let mut e = Left(2);
1024     let r = Right(2);
1025     assert_eq!(e, Left(2));
1026     e = r;
1027     assert_eq!(e, Right(2));
1028     assert_eq!(e.left(), None);
1029     assert_eq!(e.right(), Some(2));
1030     assert_eq!(e.as_ref().right(), Some(&2));
1031     assert_eq!(e.as_mut().right(), Some(&mut 2));
1032 }
1033 
1034 #[test]
macros()1035 fn macros() {
1036     fn a() -> Either<u32, u32> {
1037         let x: u32 = try_left!(Right(1337u32));
1038         Left(x * 2)
1039     }
1040     assert_eq!(a(), Right(1337));
1041 
1042     fn b() -> Either<String, &'static str> {
1043         Right(try_right!(Left("foo bar")))
1044     }
1045     assert_eq!(b(), Left(String::from("foo bar")));
1046 }
1047 
1048 #[test]
deref()1049 fn deref() {
1050     fn is_str(_: &str) {}
1051     let value: Either<String, &str> = Left(String::from("test"));
1052     is_str(&*value);
1053 }
1054 
1055 #[test]
iter()1056 fn iter() {
1057     let x = 3;
1058     let mut iter = match x {
1059         3 => Left(0..10),
1060         _ => Right(17..),
1061     };
1062 
1063     assert_eq!(iter.next(), Some(0));
1064     assert_eq!(iter.count(), 9);
1065 }
1066 
1067 #[test]
read_write()1068 fn read_write() {
1069     use std::io;
1070 
1071     let use_stdio = false;
1072     let mockdata = [0xff; 256];
1073 
1074     let mut reader = if use_stdio {
1075         Left(io::stdin())
1076     } else {
1077         Right(&mockdata[..])
1078     };
1079 
1080     let mut buf = [0u8; 16];
1081     assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
1082     assert_eq!(&buf, &mockdata[..buf.len()]);
1083 
1084     let mut mockbuf = [0u8; 256];
1085     let mut writer = if use_stdio {
1086         Left(io::stdout())
1087     } else {
1088         Right(&mut mockbuf[..])
1089     };
1090 
1091     let buf = [1u8; 16];
1092     assert_eq!(writer.write(&buf).unwrap(), buf.len());
1093 }
1094 
1095 #[test]
1096 #[allow(deprecated)]
error()1097 fn error() {
1098     let invalid_utf8 = b"\xff";
1099     let res = if let Err(error) = ::std::str::from_utf8(invalid_utf8) {
1100         Err(Left(error))
1101     } else if let Err(error) = "x".parse::<i32>() {
1102         Err(Right(error))
1103     } else {
1104         Ok(())
1105     };
1106     assert!(res.is_err());
1107     res.unwrap_err().description(); // make sure this can be called
1108 }
1109 
1110 /// A helper macro to check if AsRef and AsMut are implemented for a given type.
1111 macro_rules! check_t {
1112     ($t:ty) => {{
1113         fn check_ref<T: AsRef<$t>>() {}
1114         fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>>() {
1115             check_ref::<Either<T1, T2>>()
1116         }
1117         fn check_mut<T: AsMut<$t>>() {}
1118         fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>>() {
1119             check_mut::<Either<T1, T2>>()
1120         }
1121     }};
1122 }
1123 
1124 // This "unused" method is here to ensure that compilation doesn't fail on given types.
_unsized_ref_propagation()1125 fn _unsized_ref_propagation() {
1126     check_t!(str);
1127 
1128     fn check_array_ref<T: AsRef<[Item]>, Item>() {}
1129     fn check_array_mut<T: AsMut<[Item]>, Item>() {}
1130 
1131     fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, Item>() {
1132         check_array_ref::<Either<T1, T2>, _>()
1133     }
1134 
1135     fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, Item>() {
1136         check_array_mut::<Either<T1, T2>, _>()
1137     }
1138 }
1139 
1140 // This "unused" method is here to ensure that compilation doesn't fail on given types.
1141 #[cfg(feature = "use_std")]
_unsized_std_propagation()1142 fn _unsized_std_propagation() {
1143     check_t!(::std::path::Path);
1144     check_t!(::std::ffi::OsStr);
1145     check_t!(::std::ffi::CStr);
1146 }
1147