1 //! The enum [**Either**](enum.Either.html).
2 //!
3 //! **Crate features:**
4 //!
5 //! * `"use_std"`
6 //! Enabled by default. Disable to make the library `#![no_std]`.
7 //!
8 
9 #![doc(html_root_url = "https://docs.rs/either/1/")]
10 #![cfg_attr(all(not(test), not(feature = "use_std")), no_std)]
11 #[cfg(all(not(test), not(feature = "use_std")))]
12 extern crate core as std;
13 
14 use std::convert::{AsRef, AsMut};
15 use std::fmt;
16 use std::iter;
17 use std::ops::Deref;
18 use std::ops::DerefMut;
19 #[cfg(any(test, feature = "use_std"))]
20 use std::io::{self, Write, Read, BufRead};
21 #[cfg(any(test, feature = "use_std"))]
22 use std::error::Error;
23 
24 pub use Either::{Left, Right};
25 
26 /// `Either` represents an alternative holding one value out of
27 /// either of the two possible values.
28 ///
29 /// `Either` is a general purpose sum type of two parts. For representing
30 /// success or error, use the regular `Result<T, E>` instead.
31 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
32 pub enum Either<L, R> {
33     /// A value of type `L`.
34     Left(L),
35     /// A value of type `R`.
36     Right(R),
37 }
38 
39 macro_rules! either {
40     ($value:expr, $pattern:pat => $result:expr) => (
41         match $value {
42             Either::Left($pattern) => $result,
43             Either::Right($pattern) => $result,
44         }
45     )
46 }
47 
48 /// Macro for unwrapping the left side of an `Either`, which fails early
49 /// with the opposite side. Can only be used in functions that return
50 /// `Either` because of the early return of `Right` that it provides.
51 ///
52 /// See also `try_right!` for its dual, which applies the same just to the
53 /// right side.
54 ///
55 /// # Example
56 ///
57 /// ```
58 /// #[macro_use] extern crate either;
59 /// use either::{Either, Left, Right};
60 ///
61 /// fn twice(wrapper: Either<u32, &str>) -> Either<u32, &str> {
62 ///     let value = try_left!(wrapper);
63 ///     Left(value * 2)
64 /// }
65 ///
66 /// fn main() {
67 ///     assert_eq!(twice(Left(2)), Left(4));
68 ///     assert_eq!(twice(Right("ups")), Right("ups"));
69 /// }
70 /// ```
71 #[macro_export]
72 macro_rules! try_left {
73     ($expr:expr) => (
74         match $expr {
75             $crate::Left(val) => val,
76             $crate::Right(err) => return $crate::Right(::std::convert::From::from(err))
77         }
78     )
79 }
80 
81 /// Dual to `try_left!`, see its documentation for more information.
82 #[macro_export]
83 macro_rules! try_right {
84     ($expr:expr) => (
85         match $expr {
86             $crate::Left(err) => return $crate::Left(::std::convert::From::from(err)),
87             $crate::Right(val) => val
88         }
89     )
90 }
91 
92 impl<L, R> Either<L, R> {
93     /// Return true if the value is the `Left` variant.
94     ///
95     /// ```
96     /// use either::*;
97     ///
98     /// let values = [Left(1), Right("the right value")];
99     /// assert_eq!(values[0].is_left(), true);
100     /// assert_eq!(values[1].is_left(), false);
101     /// ```
is_left(&self) -> bool102     pub fn is_left(&self) -> bool {
103         match *self {
104             Left(_) => true,
105             Right(_) => false,
106         }
107     }
108 
109     /// Return true if the value is the `Right` variant.
110     ///
111     /// ```
112     /// use either::*;
113     ///
114     /// let values = [Left(1), Right("the right value")];
115     /// assert_eq!(values[0].is_right(), false);
116     /// assert_eq!(values[1].is_right(), true);
117     /// ```
is_right(&self) -> bool118     pub fn is_right(&self) -> bool {
119         !self.is_left()
120     }
121 
122     /// Convert the left side of `Either<L, R>` to an `Option<L>`.
123     ///
124     /// ```
125     /// use either::*;
126     ///
127     /// let left: Either<_, ()> = Left("some value");
128     /// assert_eq!(left.left(),  Some("some value"));
129     ///
130     /// let right: Either<(), _> = Right(321);
131     /// assert_eq!(right.left(), None);
132     /// ```
left(self) -> Option<L>133     pub fn left(self) -> Option<L> {
134         match self {
135             Left(l) => Some(l),
136             Right(_) => None,
137         }
138     }
139 
140     /// Convert the right side of `Either<L, R>` to an `Option<R>`.
141     ///
142     /// ```
143     /// use either::*;
144     ///
145     /// let left: Either<_, ()> = Left("some value");
146     /// assert_eq!(left.right(),  None);
147     ///
148     /// let right: Either<(), _> = Right(321);
149     /// assert_eq!(right.right(), Some(321));
150     /// ```
right(self) -> Option<R>151     pub fn right(self) -> Option<R> {
152         match self {
153             Left(_) => None,
154             Right(r) => Some(r),
155         }
156     }
157 
158     /// Convert `&Either<L, R>` to `Either<&L, &R>`.
159     ///
160     /// ```
161     /// use either::*;
162     ///
163     /// let left: Either<_, ()> = Left("some value");
164     /// assert_eq!(left.as_ref(), Left(&"some value"));
165     ///
166     /// let right: Either<(), _> = Right("some value");
167     /// assert_eq!(right.as_ref(), Right(&"some value"));
168     /// ```
as_ref(&self) -> Either<&L, &R>169     pub fn as_ref(&self) -> Either<&L, &R> {
170         match *self {
171             Left(ref inner) => Left(inner),
172             Right(ref inner) => Right(inner),
173         }
174     }
175 
176     /// Convert `&mut Either<L, R>` to `Either<&mut L, &mut R>`.
177     ///
178     /// ```
179     /// use either::*;
180     ///
181     /// fn mutate_left(value: &mut Either<u32, u32>) {
182     ///     if let Some(l) = value.as_mut().left() {
183     ///         *l = 999;
184     ///     }
185     /// }
186     ///
187     /// let mut left = Left(123);
188     /// let mut right = Right(123);
189     /// mutate_left(&mut left);
190     /// mutate_left(&mut right);
191     /// assert_eq!(left, Left(999));
192     /// assert_eq!(right, Right(123));
193     /// ```
as_mut(&mut self) -> Either<&mut L, &mut R>194     pub fn as_mut(&mut self) -> Either<&mut L, &mut R> {
195         match *self {
196             Left(ref mut inner) => Left(inner),
197             Right(ref mut inner) => Right(inner),
198         }
199     }
200 
201     /// Convert `Either<L, R>` to `Either<R, L>`.
202     ///
203     /// ```
204     /// use either::*;
205     ///
206     /// let left: Either<_, ()> = Left(123);
207     /// assert_eq!(left.flip(), Right(123));
208     ///
209     /// let right: Either<(), _> = Right("some value");
210     /// assert_eq!(right.flip(), Left("some value"));
211     /// ```
flip(self) -> Either<R, L>212     pub fn flip(self) -> Either<R, L> {
213         match self {
214             Left(l) => Right(l),
215             Right(r) => Left(r),
216         }
217     }
218 
219     /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the
220     /// result in `Left`.
221     ///
222     /// ```
223     /// use either::*;
224     ///
225     /// let left: Either<_, u32> = Left(123);
226     /// assert_eq!(left.map_left(|x| x * 2), Left(246));
227     ///
228     /// let right: Either<u32, _> = Right(123);
229     /// assert_eq!(right.map_left(|x| x * 2), Right(123));
230     /// ```
map_left<F, M>(self, f: F) -> Either<M, R> where F: FnOnce(L) -> M231     pub fn map_left<F, M>(self, f: F) -> Either<M, R>
232         where F: FnOnce(L) -> M
233     {
234         match self {
235             Left(l) => Left(f(l)),
236             Right(r) => Right(r),
237         }
238     }
239 
240     /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the
241     /// result in `Right`.
242     ///
243     /// ```
244     /// use either::*;
245     ///
246     /// let left: Either<_, u32> = Left(123);
247     /// assert_eq!(left.map_right(|x| x * 2), Left(123));
248     ///
249     /// let right: Either<u32, _> = Right(123);
250     /// assert_eq!(right.map_right(|x| x * 2), Right(246));
251     /// ```
map_right<F, S>(self, f: F) -> Either<L, S> where F: FnOnce(R) -> S252     pub fn map_right<F, S>(self, f: F) -> Either<L, S>
253         where F: FnOnce(R) -> S
254     {
255         match self {
256             Left(l) => Left(l),
257             Right(r) => Right(f(r)),
258         }
259     }
260 
261     /// Apply one of two functions depending on contents, unifying their result. If the value is
262     /// `Left(L)` then the first function `f` is applied; if it is `Right(R)` then the second
263     /// function `g` is applied.
264     ///
265     /// ```
266     /// use either::*;
267     ///
268     /// fn square(n: u32) -> i32 { (n * n) as i32 }
269     /// fn negate(n: i32) -> i32 { -n }
270     ///
271     /// let left: Either<u32, i32> = Left(4);
272     /// assert_eq!(left.either(square, negate), 16);
273     ///
274     /// let right: Either<u32, i32> = Right(-4);
275     /// assert_eq!(right.either(square, negate), 4);
276     /// ```
either<F, G, T>(self, f: F, g: G) -> T where F: FnOnce(L) -> T, G: FnOnce(R) -> T277     pub fn either<F, G, T>(self, f: F, g: G) -> T
278       where F: FnOnce(L) -> T,
279             G: FnOnce(R) -> T
280     {
281         match self {
282             Left(l) => f(l),
283             Right(r) => g(r),
284         }
285     }
286 
287     /// Apply the function `f` on the value in the `Left` variant if it is present.
288     ///
289     /// ```
290     /// use either::*;
291     ///
292     /// let left: Either<_, u32> = Left(123);
293     /// assert_eq!(left.left_and_then::<_,()>(|x| Right(x * 2)), Right(246));
294     ///
295     /// let right: Either<u32, _> = Right(123);
296     /// assert_eq!(right.left_and_then(|x| Right::<(), _>(x * 2)), Right(123));
297     /// ```
left_and_then<F, S>(self, f: F) -> Either<S, R> where F: FnOnce(L) -> Either<S, R>298     pub fn left_and_then<F, S>(self, f: F) -> Either<S, R>
299         where F: FnOnce(L) -> Either<S, R>
300     {
301         match self {
302             Left(l) => f(l),
303             Right(r) => Right(r),
304         }
305     }
306 
307     /// Apply the function `f` on the value in the `Right` variant if it is present.
308     ///
309     /// ```
310     /// use either::*;
311     ///
312     /// let left: Either<_, u32> = Left(123);
313     /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123));
314     ///
315     /// let right: Either<u32, _> = Right(123);
316     /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246));
317     /// ```
right_and_then<F, S>(self, f: F) -> Either<L, S> where F: FnOnce(R) -> Either<L, S>318     pub fn right_and_then<F, S>(self, f: F) -> Either<L, S>
319         where F: FnOnce(R) -> Either<L, S>
320     {
321         match self {
322             Left(l) => Left(l),
323             Right(r) => f(r),
324         }
325     }
326 }
327 
328 /// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`.
329 impl<L, R> From<Result<R, L>> for Either<L, R> {
from(r: Result<R, L>) -> Self330     fn from(r: Result<R, L>) -> Self {
331         match r {
332             Err(e) => Left(e),
333             Ok(o) => Right(o),
334         }
335     }
336 }
337 
338 /// Convert from `Either` to `Result` with `Right => Ok` and `Left => Err`.
339 impl<L, R> Into<Result<R, L>> for Either<L, R> {
into(self) -> Result<R, L>340     fn into(self) -> Result<R, L> {
341         match self {
342             Left(l) => Err(l),
343             Right(r) => Ok(r),
344         }
345     }
346 }
347 
348 impl<L, R, A> Extend<A> for Either<L, R>
349     where L: Extend<A>, R: Extend<A>
350 {
extend<T>(&mut self, iter: T) where T: IntoIterator<Item=A>351     fn extend<T>(&mut self, iter: T)
352         where T: IntoIterator<Item=A>
353     {
354         either!(*self, ref mut inner => inner.extend(iter))
355     }
356 }
357 
358 /// `Either<L, R>` is an iterator if both `L` and `R` are iterators.
359 impl<L, R> Iterator for Either<L, R>
360     where L: Iterator, R: Iterator<Item=L::Item>
361 {
362     type Item = L::Item;
363 
next(&mut self) -> Option<Self::Item>364     fn next(&mut self) -> Option<Self::Item> {
365         either!(*self, ref mut inner => inner.next())
366     }
367 
size_hint(&self) -> (usize, Option<usize>)368     fn size_hint(&self) -> (usize, Option<usize>) {
369         either!(*self, ref inner => inner.size_hint())
370     }
371 
fold<Acc, G>(self, init: Acc, f: G) -> Acc where G: FnMut(Acc, Self::Item) -> Acc,372     fn fold<Acc, G>(self, init: Acc, f: G) -> Acc
373         where G: FnMut(Acc, Self::Item) -> Acc,
374     {
375         either!(self, inner => inner.fold(init, f))
376     }
377 
count(self) -> usize378     fn count(self) -> usize {
379         either!(self, inner => inner.count())
380     }
381 
last(self) -> Option<Self::Item>382     fn last(self) -> Option<Self::Item> {
383         either!(self, inner => inner.last())
384     }
385 
nth(&mut self, n: usize) -> Option<Self::Item>386     fn nth(&mut self, n: usize) -> Option<Self::Item> {
387         either!(*self, ref mut inner => inner.nth(n))
388     }
389 
collect<B>(self) -> B where B: iter::FromIterator<Self::Item>390     fn collect<B>(self) -> B
391         where B: iter::FromIterator<Self::Item>
392     {
393         either!(self, inner => inner.collect())
394     }
395 
all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool396     fn all<F>(&mut self, f: F) -> bool
397         where F: FnMut(Self::Item) -> bool
398     {
399         either!(*self, ref mut inner => inner.all(f))
400     }
401 }
402 
403 impl<L, R> DoubleEndedIterator for Either<L, R>
404     where L: DoubleEndedIterator, R: DoubleEndedIterator<Item=L::Item>
405 {
next_back(&mut self) -> Option<Self::Item>406     fn next_back(&mut self) -> Option<Self::Item> {
407         either!(*self, ref mut inner => inner.next_back())
408     }
409 }
410 
411 impl<L, R> ExactSizeIterator for Either<L, R>
412     where L: ExactSizeIterator, R: ExactSizeIterator<Item=L::Item>
413 {
414 }
415 
416 #[cfg(any(test, feature = "use_std"))]
417 /// `Either<L, R>` implements `Read` if both `L` and `R` do.
418 ///
419 /// Requires crate feature `"use_std"`
420 impl<L, R> Read for Either<L, R>
421     where L: Read, R: Read
422 {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>423     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
424         either!(*self, ref mut inner => inner.read(buf))
425     }
426 
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>427     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
428         either!(*self, ref mut inner => inner.read_to_end(buf))
429     }
430 }
431 
432 #[cfg(any(test, feature = "use_std"))]
433 /// Requires crate feature `"use_std"`
434 impl<L, R> BufRead for Either<L, R>
435     where L: BufRead, R: BufRead
436 {
fill_buf(&mut self) -> io::Result<&[u8]>437     fn fill_buf(&mut self) -> io::Result<&[u8]> {
438         either!(*self, ref mut inner => inner.fill_buf())
439     }
440 
consume(&mut self, amt: usize)441     fn consume(&mut self, amt: usize) {
442         either!(*self, ref mut inner => inner.consume(amt))
443     }
444 }
445 
446 #[cfg(any(test, feature = "use_std"))]
447 /// `Either<L, R>` implements `Write` if both `L` and `R` do.
448 ///
449 /// Requires crate feature `"use_std"`
450 impl<L, R> Write for Either<L, R>
451     where L: Write, R: Write
452 {
write(&mut self, buf: &[u8]) -> io::Result<usize>453     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
454         either!(*self, ref mut inner => inner.write(buf))
455     }
456 
flush(&mut self) -> io::Result<()>457     fn flush(&mut self) -> io::Result<()> {
458         either!(*self, ref mut inner => inner.flush())
459     }
460 }
461 
462 impl<L, R, Target> AsRef<Target> for Either<L, R>
463     where L: AsRef<Target>, R: AsRef<Target>
464 {
as_ref(&self) -> &Target465     fn as_ref(&self) -> &Target {
466         either!(*self, ref inner => inner.as_ref())
467     }
468 }
469 
470 impl<L, R, Target> AsMut<Target> for Either<L, R>
471     where L: AsMut<Target>, R: AsMut<Target>
472 {
as_mut(&mut self) -> &mut Target473     fn as_mut(&mut self) -> &mut Target {
474         either!(*self, ref mut inner => inner.as_mut())
475     }
476 }
477 
478 impl<L, R> Deref for Either<L, R>
479     where L: Deref, R: Deref<Target=L::Target>
480 {
481     type Target = L::Target;
482 
deref(&self) -> &Self::Target483     fn deref(&self) -> &Self::Target {
484         either!(*self, ref inner => &*inner)
485     }
486 }
487 
488 impl<L, R> DerefMut for Either<L, R>
489     where L: DerefMut, R: DerefMut<Target=L::Target>
490 {
deref_mut(&mut self) -> &mut Self::Target491     fn deref_mut(&mut self) -> &mut Self::Target {
492         either!(*self, ref mut inner => &mut *inner)
493     }
494 }
495 
496 #[cfg(any(test, feature = "use_std"))]
497 /// `Either` implements `Error` if *both* `L` and `R` implement it.
498 impl<L, R> Error for Either<L, R>
499     where L: Error, R: Error
500 {
description(&self) -> &str501     fn description(&self) -> &str {
502         either!(*self, ref inner => inner.description())
503     }
504 
cause(&self) -> Option<&Error>505     fn cause(&self) -> Option<&Error> {
506         either!(*self, ref inner => inner.cause())
507     }
508 }
509 
510 impl<L, R> fmt::Display for Either<L, R>
511     where L: fmt::Display, R: fmt::Display
512 {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result513     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514         either!(*self, ref inner => inner.fmt(f))
515     }
516 }
517 
518 #[test]
basic()519 fn basic() {
520     let mut e = Left(2);
521     let r = Right(2);
522     assert_eq!(e, Left(2));
523     e = r;
524     assert_eq!(e, Right(2));
525     assert_eq!(e.left(), None);
526     assert_eq!(e.right(), Some(2));
527     assert_eq!(e.as_ref().right(), Some(&2));
528     assert_eq!(e.as_mut().right(), Some(&mut 2));
529 }
530 
531 #[test]
macros()532 fn macros() {
533     fn a() -> Either<u32, u32> {
534         let x: u32 = try_left!(Right(1337u32));
535         Left(x * 2)
536     }
537     assert_eq!(a(), Right(1337));
538 
539     fn b() -> Either<String, &'static str> {
540         Right(try_right!(Left("foo bar")))
541     }
542     assert_eq!(b(), Left(String::from("foo bar")));
543 }
544 
545 #[test]
deref()546 fn deref() {
547     fn is_str(_: &str) {}
548     let value: Either<String, &str> = Left(String::from("test"));
549     is_str(&*value);
550 }
551 
552 #[test]
iter()553 fn iter() {
554     let x = 3;
555     let mut iter = match x {
556         1...3 => Left(0..10),
557         _ => Right(17..),
558     };
559 
560     assert_eq!(iter.next(), Some(0));
561     assert_eq!(iter.count(), 9);
562 }
563 
564 #[test]
read_write()565 fn read_write() {
566     use std::io;
567 
568     let use_stdio = false;
569     let mockdata = [0xff; 256];
570 
571     let mut reader = if use_stdio {
572         Left(io::stdin())
573     } else {
574         Right(&mockdata[..])
575     };
576 
577     let mut buf = [0u8; 16];
578     assert_eq!(reader.read(&mut buf).unwrap(), buf.len());
579     assert_eq!(&buf, &mockdata[..buf.len()]);
580 
581     let mut mockbuf = [0u8; 256];
582     let mut writer = if use_stdio {
583         Left(io::stdout())
584     } else {
585         Right(&mut mockbuf[..])
586     };
587 
588     let buf = [1u8; 16];
589     assert_eq!(writer.write(&buf).unwrap(), buf.len());
590 }
591 
592 #[test]
error()593 fn error() {
594     let invalid_utf8 = b"\xff";
595     let res = || -> Result<_, Either<_, _>> {
596         try!(::std::str::from_utf8(invalid_utf8).map_err(Left));
597         try!("x".parse::<i32>().map_err(Right));
598         Ok(())
599     }();
600     assert!(res.is_err());
601     res.unwrap_err().description(); // make sure this can be called
602 }
603