libeither/
either.rs

1// Copyright (c) 2018 libeither developers
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9//! Either struct
10
11use crate::error::{Error, Result};
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14use std::convert::TryInto;
15use std::fmt;
16use std::io::{self, BufRead, Read, Write};
17
18/// A struct representing either a left value, or a right value.
19#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
20#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
21pub struct Either<L, R> {
22    /// The left value in the struct.
23    left: Option<L>,
24    /// The right value in the struct.
25    right: Option<R>,
26}
27
28impl<L, R> Either<L, R> {
29    /// Create an `Either` with the left value populated.
30    pub fn new_left(val: L) -> Self {
31        Self {
32            left: Some(val),
33            right: None,
34        }
35    }
36
37    /// Create an `Either` with the right value populated.
38    pub fn new_right(val: R) -> Self {
39        Self {
40            left: None,
41            right: Some(val),
42        }
43    }
44
45    /// Extract the left value from the `Either`.
46    /// This consumes the either in the process.
47    ///
48    /// ```
49    /// # use libeither::Either;
50    /// #
51    /// let left: Either<u16, u16> = Either::new_left(10);
52    /// assert_eq!(left.left(), Some(10));
53    ///
54    /// let right: Either<u16, u16> = Either::new_right(10);
55    /// assert!(right.left().is_none());
56    pub fn left(self) -> Option<L> {
57        self.left
58    }
59
60    /// Extract the left value from the `Either`.
61    /// This consumes the either in the process.
62    /// If this is performed on a `Right` variant, an
63    /// error returned.
64    ///
65    /// # Errors
66    ///
67    /// ```
68    /// # use libeither::{Either, Result};
69    /// #
70    /// # fn main() -> Result<()> {
71    /// let left: Either<u16, u16> = Either::new_left(10);
72    /// assert_eq!(left.left_safe()?, 10);
73    ///
74    /// let right: Either<u16, u16> = Either::new_right(10);
75    /// assert!(right.left_safe().is_err());
76    /// # Ok(())
77    /// # }
78    pub fn left_safe(self) -> Result<L> {
79        self.left.ok_or_else(Error::extract_left)
80    }
81
82    /// Extract the right value from the `Either`.
83    /// This consumes the either in the process.
84    ///
85    /// ```
86    /// # use libeither::Either;
87    /// #
88    /// let right: Either<u16, u16> = Either::new_right(10);
89    /// assert_eq!(right.right(), Some(10));
90    ///
91    /// let left: Either<u16, u16> = Either::new_left(10);
92    /// assert!(left.right().is_none());
93    pub fn right(self) -> Option<R> {
94        self.right
95    }
96
97    /// Extract the right value from the `Either`.
98    /// This consumes the either in the process.
99    /// If this is performed on a `Left` variant, an
100    /// error returned.
101    ///
102    /// # Errors
103    ///
104    /// ```
105    /// # use libeither::{Either, Result};
106    /// #
107    /// # fn main() -> Result<()> {
108    /// let right: Either<u16, u16> = Either::new_right(10);
109    /// assert_eq!(right.right_safe()?, 10);
110    ///
111    /// let left: Either<u16, u16> = Either::new_left(10);
112    /// assert!(left.right_safe().is_err());
113    /// # Ok(())
114    /// # }
115    pub fn right_safe(self) -> Result<R> {
116        self.right.ok_or_else(Error::extract_right)
117    }
118
119    /// Check if this `Either` is the left variant.
120    ///
121    /// ```
122    /// # use libeither::Either;
123    /// #
124    /// let left: Either<&str, &str> = Either::new_left("lefty");
125    /// assert!(left.is_left());
126    /// assert!(!left.is_right());
127    /// ```
128    pub fn is_left(&self) -> bool {
129        self.left.is_some()
130    }
131
132    /// Check if this `Either` is the right variant.
133    ///
134    /// ```
135    /// # use libeither::Either;
136    /// #
137    /// let right: Either<&str, &str> = Either::new_right("righty");
138    /// assert!(right.is_right());
139    /// assert!(!right.is_left());
140    /// ```
141    pub fn is_right(&self) -> bool {
142        self.right.is_some()
143    }
144
145    /// Extract a reference to the left value.
146    ///
147    /// # Errors
148    ///
149    /// ```
150    /// # use libeither::{Either, Result};
151    /// #
152    /// # fn main() -> Result<()> {
153    /// let left: Either<&str, &str> = Either::new_left("lefty");
154    /// assert_eq!(left.left_ref()?, &"lefty");
155    /// #   Ok(())
156    /// # }
157    /// ```
158    pub fn left_ref(&self) -> Result<&L> {
159        self.left.as_ref().ok_or_else(Error::extract_left)
160    }
161
162    /// Extract a reference to the right value.
163    ///
164    /// # Errors
165    ///
166    /// ```
167    /// # use libeither::{Either, Result};
168    /// #
169    /// # fn main() -> Result<()> {
170    /// let right: Either<&str, &str> = Either::new_right("righty");
171    /// assert_eq!(right.right_ref()?, &"righty");
172    /// #   Ok(())
173    /// # }
174    /// ```
175    pub fn right_ref(&self) -> Result<&R> {
176        self.right.as_ref().ok_or_else(Error::extract_right)
177    }
178
179    /// Extract a mutable reference to the left value.
180    ///
181    /// # Errors
182    ///
183    /// ```
184    /// # use libeither::{Either, Result};
185    /// #
186    /// # fn main() -> Result<()> {
187    /// let mut left: Either<&str, &str> = Either::new_left("lefty");
188    /// assert_eq!(left.left_ref()?, &"lefty");
189    /// *(left.left_mut()?) = "left handed";
190    /// assert_eq!(left.left_ref()?, &"left handed");
191    /// #   Ok(())
192    /// # }
193    /// ```
194    pub fn left_mut(&mut self) -> Result<&mut L> {
195        self.left.as_mut().ok_or_else(Error::extract_left)
196    }
197
198    /// Extract a mutable reference to the right value.
199    ///
200    /// # Errors
201    ///
202    /// ```
203    /// # use libeither::{Either, Result};
204    /// #
205    /// # fn main() -> Result<()> {
206    /// let mut right: Either<&str, &str> = Either::new_right("righty");
207    /// assert_eq!(right.right_ref()?, &"righty");
208    /// *(right.right_mut()?) = "right handed";
209    /// assert_eq!(right.right_ref()?, &"right handed");
210    /// #   Ok(())
211    /// # }
212    /// ```
213    pub fn right_mut(&mut self) -> Result<&mut R> {
214        self.right.as_mut().ok_or_else(Error::extract_right)
215    }
216
217    /// Convert `Either<L, R>` to `Either<R, L>`
218    ///
219    /// # Errors
220    ///
221    /// ```
222    /// # use libeither::{Either, Result};
223    /// #
224    /// # fn main() -> Result<()> {
225    /// let left: Either<&str, &str> = Either::new_left("lefty");
226    /// let right = left.flip()?;
227    /// assert!(right.is_right());
228    /// assert_eq!(right.right_ref()?, &"lefty");
229    /// #   Ok(())
230    /// # }
231    /// ```
232    pub fn flip(self) -> Result<Either<R, L>> {
233        if let Some(l) = self.left {
234            Ok(Either::new_right(l))
235        } else if let Some(r) = self.right {
236            Ok(Either::new_left(r))
237        } else {
238            Err(Error::invalid())
239        }
240    }
241
242    /// Apply the function `f` on the `Left` value, returning the result
243    /// in a `Left`. If this is applied to a `Right`, the `Right` is
244    /// returned.
245    ///
246    /// # Errors
247    ///
248    /// ```
249    /// # use libeither::{Either, Result};
250    /// #
251    /// # fn main() -> Result<()> {
252    /// let left: Either<u8, u8> = Either::new_left(10);
253    /// let mapped_left = left.map_left(|x| x * 10)?;
254    /// assert!(mapped_left.is_left());
255    /// assert_eq!(mapped_left.left_ref()?, &100);
256    /// #   Ok(())
257    /// # }
258    /// ```
259    pub fn map_left<F, FL>(self, f: F) -> Result<Either<FL, R>>
260    where
261        F: FnOnce(L) -> FL,
262    {
263        if let Some(l) = self.left {
264            Ok(Either::new_left(f(l)))
265        } else if let Some(r) = self.right {
266            Ok(Either::new_right(r))
267        } else {
268            Err(Error::invalid())
269        }
270    }
271
272    /// Apply the function `f` on the `Right` value, returning the result
273    /// in a `Right`.  If this is applied to a `Left`, the `Left` is
274    /// returned.
275    ///
276    /// # Errors
277    ///
278    /// ```
279    /// # use libeither::{Either, Result};
280    /// #
281    /// # fn main() -> Result<()> {
282    /// let right: Either<u8, u8> = Either::new_right(10);
283    /// let mapped_right = right.map_right(|x| x * 10)?;
284    /// assert!(mapped_right.is_right());
285    /// assert_eq!(mapped_right.right_ref()?, &100);
286    /// #   Ok(())
287    /// # }
288    /// ```
289    pub fn map_right<F, FR>(self, f: F) -> Result<Either<L, FR>>
290    where
291        F: FnOnce(R) -> FR,
292    {
293        if let Some(l) = self.left {
294            Ok(Either::new_left(l))
295        } else if let Some(r) = self.right {
296            Ok(Either::new_right(f(r)))
297        } else {
298            Err(Error::invalid())
299        }
300    }
301
302    /// If the variant is a `Left`, apply the function `fl` on the `Left` value,
303    /// returning the result `Left(fl(l))`.  If the variant is a `Right` value,
304    /// apply the function `fr` on the `Right` value, returning the result
305    /// `Right(fr(r))`.  If the varian is invalid, return an error.
306    ///
307    /// # Errors
308    ///
309    /// ```
310    /// # use libeither::{Either, Result};
311    /// #
312    /// # fn main() -> Result<()> {
313    /// let left: Either<u8, u8> = Either::new_left(10);
314    /// let mapped = left.map_left_or_right(|x| x * 10, |y| y * 5)?;
315    /// assert!(mapped.is_left());
316    /// assert_eq!(mapped.left_ref()?, &100);
317    ///
318    /// let flipped = left.flip()?;
319    /// let mapped = flipped.map_left_or_right(|x| x * 10, |y| y * 5)?;
320    /// assert!(mapped.is_right());
321    /// assert_eq!(mapped.right_ref()?, &50);
322    /// #   Ok(())
323    /// # }
324    /// ```
325    pub fn map_left_or_right<FL, FR, RL, RR>(self, fl: FL, fr: FR) -> Result<Either<RL, RR>>
326    where
327        FL: FnOnce(L) -> RL,
328        FR: FnOnce(R) -> RR,
329    {
330        if let Some(l) = self.left {
331            Ok(Either::new_left(fl(l)))
332        } else if let Some(r) = self.right {
333            Ok(Either::new_right(fr(r)))
334        } else {
335            Err(Error::invalid())
336        }
337    }
338
339    /// Apply the function `f` on the value `l` in the `Left` variant if it
340    /// is present and return `Left(f(l))`. Otherwise, returns the `Right`
341    /// variant. If the `Either` is invalid, this function will return an
342    /// `Error` result.
343    ///
344    /// # Errors
345    ///
346    /// ```
347    /// # use libeither::{Either, Result};
348    /// #
349    /// # fn main() -> Result<()> {
350    /// let left: Either<u16, u16> = Either::new_left(10);
351    /// let and_then_left: Either<u16, _> = left
352    ///     .and_then_left(|x| Either::new_left(x * 10))?
353    ///     .and_then_left(|x: u16| Either::new_left(x * 10))?;
354    /// assert!(and_then_left.is_left());
355    /// assert_eq!(and_then_left.left_ref()?, &1000);
356    ///
357    /// let right: Either<u16, u16> = Either::new_right(5);
358    /// let not_a_left: Either<_, u16> = right
359    ///     .and_then_left(|x| Either::new_left(x * 10))?
360    ///     .and_then_left(|x: u16| Either::new_left(x * 10))?;
361    /// assert!(not_a_left.is_right());
362    /// assert_eq!(not_a_left.right_ref()?, &5);
363    /// #   Ok(())
364    /// # }
365    pub fn and_then_left<F, S>(self, f: F) -> Result<Either<S, R>>
366    where
367        F: FnOnce(L) -> Either<S, R>,
368    {
369        if let Some(l) = self.left {
370            Ok(f(l))
371        } else if let Some(right) = self.right {
372            Ok(Either::new_right(right))
373        } else {
374            Err(Error::invalid())
375        }
376    }
377
378    /// Apply the function `f` on the value `r` in the `Right` variant if it
379    /// is present and return `Right(f(r))`. Otherwise, returns the `Left`
380    /// variant.  If the `Either` is invalid, this function will return an
381    /// `Error` result.
382    ///
383    ///
384    /// # Errors
385    ///
386    /// ```
387    /// # use libeither::{Either, Result};
388    /// #
389    /// # fn main() -> Result<()> {
390    /// let right: Either<u16, u16> = Either::new_right(10);
391    /// let and_then_right: Either<u16, u16> = right
392    ///     .and_then_right(|x| Either::new_right(x * 10))?
393    ///     .and_then_right(|x: u16| Either::new_right(x * 10))?;
394    /// assert!(and_then_right.is_right());
395    /// assert_eq!(and_then_right.right_ref()?, &1000);
396    /// #   Ok(())
397    /// # }
398    pub fn and_then_right<F, S>(self, f: F) -> Result<Either<L, S>>
399    where
400        F: FnOnce(R) -> Either<L, S>,
401    {
402        if let Some(l) = self.left {
403            Ok(Either::new_left(l))
404        } else if let Some(r) = self.right {
405            Ok(f(r))
406        } else {
407            Err(Error::invalid())
408        }
409    }
410
411    /// Convert the inners to iters
412    ///
413    /// # Errors
414    ///
415    #[allow(clippy::should_implement_trait)]
416    pub fn into_iter(self) -> Result<Either<L::IntoIter, R::IntoIter>>
417    where
418        L: IntoIterator,
419        R: IntoIterator<Item = L::Item>,
420    {
421        if let Some(l) = self.left {
422            Ok(Either::new_left(l.into_iter()))
423        } else if let Some(r) = self.right {
424            Ok(Either::new_right(r.into_iter()))
425        } else {
426            Err(Error::invalid())
427        }
428    }
429}
430
431impl<L, R> From<std::result::Result<L, R>> for Either<L, R> {
432    fn from(r: std::result::Result<L, R>) -> Self {
433        match r {
434            Ok(o) => Self::new_left(o),
435            Err(e) => Self::new_right(e),
436        }
437    }
438}
439
440impl<L, R> TryInto<std::result::Result<L, R>> for Either<L, R> {
441    type Error = Error;
442
443    fn try_into(self) -> Result<std::result::Result<L, R>> {
444        if let Some(l) = self.left {
445            Ok(Ok(l))
446        } else if let Some(r) = self.right {
447            Ok(Err(r))
448        } else {
449            Err(Error::invalid())
450        }
451    }
452}
453
454macro_rules! either {
455    ($either:expr, $pattern:pat => $result:expr) => {
456        if let Some($pattern) = $either.left {
457            $result
458        } else if let Some($pattern) = $either.right {
459            $result
460        }
461    };
462}
463
464impl<L, R, A> Extend<A> for Either<L, R>
465where
466    L: Extend<A>,
467    R: Extend<A>,
468{
469    fn extend<T>(&mut self, iter: T)
470    where
471        T: IntoIterator<Item = A>,
472    {
473        either!(*self, ref mut inner => inner.extend(iter));
474    }
475}
476
477macro_rules! either_else {
478    ($either:expr, $pattern:pat => $result:expr, $else_exp:expr) => {
479        if let Some($pattern) = $either.left {
480            $result
481        } else if let Some($pattern) = $either.right {
482            $result
483        } else {
484            $else_exp
485        }
486    };
487}
488
489impl<L, R> Iterator for Either<L, R>
490where
491    L: Iterator,
492    R: Iterator<Item = L::Item>,
493{
494    type Item = L::Item;
495
496    fn next(&mut self) -> Option<Self::Item> {
497        either_else!(*self, ref mut inner => inner.next(), None)
498    }
499
500    fn size_hint(&self) -> (usize, Option<usize>) {
501        either_else!(self, ref inner => inner.size_hint(), (0, None))
502    }
503
504    fn fold<Acc, G>(self, init: Acc, f: G) -> Acc
505    where
506        G: FnMut(Acc, Self::Item) -> Acc,
507    {
508        either_else!(self, inner => inner.fold(init, f), init)
509    }
510
511    fn count(self) -> usize {
512        either_else!(self, inner => inner.count(), 0)
513    }
514
515    fn last(self) -> Option<Self::Item> {
516        either_else!(self, inner => inner.last(), None)
517    }
518
519    fn nth(&mut self, n: usize) -> Option<Self::Item> {
520        either_else!(*self, ref mut inner => inner.nth(n), None)
521    }
522
523    fn all<F>(&mut self, f: F) -> bool
524    where
525        F: FnMut(Self::Item) -> bool,
526    {
527        either_else!(*self, ref mut inner => inner.all(f), false)
528    }
529}
530
531impl<L, R> DoubleEndedIterator for Either<L, R>
532where
533    L: DoubleEndedIterator,
534    R: DoubleEndedIterator<Item = L::Item>,
535{
536    fn next_back(&mut self) -> Option<Self::Item> {
537        either_else!(*self, ref mut inner => inner.next_back(), None)
538    }
539}
540
541fn io_err(msg: &str) -> io::Error {
542    io::Error::new(io::ErrorKind::Other, msg)
543}
544
545impl<L, R> Read for Either<L, R>
546where
547    L: Read,
548    R: Read,
549{
550    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
551        either_else!(*self, ref mut inner => inner.read(buf), Err(io_err("Invalid Either (Read)")))
552    }
553
554    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
555        either_else!(*self, ref mut inner => inner.read_to_end(buf), Err(io_err("Invalid Either (Read)")))
556    }
557}
558
559impl<L, R> BufRead for Either<L, R>
560where
561    L: BufRead,
562    R: BufRead,
563{
564    fn fill_buf(&mut self) -> io::Result<&[u8]> {
565        either_else!(*self, ref mut inner => inner.fill_buf(), Err(io_err("Invalid Either (BufRead)")))
566    }
567
568    fn consume(&mut self, amt: usize) {
569        either!(*self, ref mut inner => inner.consume(amt));
570    }
571}
572
573impl<L, R> Write for Either<L, R>
574where
575    L: Write,
576    R: Write,
577{
578    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
579        either_else!(*self, ref mut inner => inner.write(buf), Err(io_err("Invalid Either (Write)")))
580    }
581
582    fn flush(&mut self) -> io::Result<()> {
583        either_else!(*self, ref mut inner => inner.flush(), Err(io_err("Invalid Either (Write)")))
584    }
585}
586
587impl<L, R> std::error::Error for Either<L, R>
588where
589    L: std::error::Error,
590    R: std::error::Error,
591{
592    fn cause(&self) -> Option<&dyn std::error::Error> {
593        either_else!(self, ref inner => inner.source(), None)
594    }
595}
596
597impl<L, R> fmt::Display for Either<L, R>
598where
599    L: fmt::Display,
600    R: fmt::Display,
601{
602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603        either_else!(self, ref inner => inner.fmt(f), Err(fmt::Error))
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::{io_err, Either};
610    use crate::error::Result;
611    use std::convert::TryInto;
612    use std::io::{self, Cursor, Read, Write};
613
614    fn invalid<'a>() -> Either<&'a str, &'a str> {
615        Either {
616            left: None,
617            right: None,
618        }
619    }
620
621    fn lefty<'a>() -> Either<&'a str, &'a str> {
622        Either::new_left("lefty")
623    }
624
625    fn righty<'a>() -> Either<&'a str, &'a str> {
626        Either::new_right("righty")
627    }
628
629    #[test]
630    fn io_err_works() {
631        assert_eq!(
632            format!("{}", io_err("test")),
633            format!("{}", io::Error::new(io::ErrorKind::Other, "test"))
634        );
635    }
636
637    #[test]
638    fn make_left() {
639        let left = lefty();
640        assert!(left.is_left());
641        assert!(!left.is_right());
642    }
643
644    #[test]
645    fn make_right() {
646        let right = righty();
647        assert!(right.is_right());
648        assert!(!right.is_left());
649    }
650
651    #[test]
652    fn left_ref() -> Result<()> {
653        assert_eq!(lefty().left_ref()?, &"lefty");
654        Ok(())
655    }
656
657    #[test]
658    fn right_ref_on_left() {
659        assert!(
660            lefty().right_ref().is_err(),
661            "right_ref on Left should not work!"
662        );
663    }
664
665    #[test]
666    fn right_ref() -> Result<()> {
667        assert_eq!(righty().right_ref()?, &"righty");
668        Ok(())
669    }
670
671    #[test]
672    fn left_ref_on_right() {
673        assert!(
674            righty().left_ref().is_err(),
675            "left_ref on Right should not work!"
676        );
677    }
678
679    #[test]
680    fn left_ref_mut() -> Result<()> {
681        let mut left = lefty();
682        assert_eq!(left.left_ref()?, &"lefty");
683        *(left.left_mut()?) = "left handed";
684        assert_eq!(left.left_ref()?, &"left handed");
685        Ok(())
686    }
687
688    #[test]
689    fn left_ref_mut_invalid() -> Result<()> {
690        let mut invalid = invalid();
691        assert!(invalid.left_mut().is_err());
692        Ok(())
693    }
694
695    #[test]
696    fn right_mut_on_left() {
697        assert!(
698            lefty().right_mut().is_err(),
699            "right_mut on Left should not work!"
700        );
701    }
702
703    #[test]
704    fn right_ref_mut() -> Result<()> {
705        let mut right = righty();
706        assert_eq!(right.right_ref()?, &"righty");
707        *(right.right_mut()?) = "right handed";
708        assert_eq!(right.right_ref()?, &"right handed");
709        Ok(())
710    }
711
712    #[test]
713    fn right_ref_mut_invalid() -> Result<()> {
714        let mut invalid = invalid();
715        assert!(invalid.right_mut().is_err());
716        Ok(())
717    }
718
719    #[test]
720    fn left_mut_on_right() {
721        assert!(
722            righty().left_mut().is_err(),
723            "left_mut on Right should not work!"
724        );
725    }
726
727    #[test]
728    fn flip() -> Result<()> {
729        let mut left = lefty();
730        let right = left.flip()?;
731        assert!(right.is_right());
732        assert_eq!(right.right_ref()?, &"lefty");
733        left = right.flip()?;
734        assert!(left.is_left());
735        assert_eq!(left.left_ref()?, &"lefty");
736        Ok(())
737    }
738
739    #[test]
740    fn flip_invalid() -> Result<()> {
741        let invalid: Either<&str, &str> = Either {
742            left: None,
743            right: None,
744        };
745        assert!(invalid.flip().is_err());
746        Ok(())
747    }
748
749    #[test]
750    fn map_left() -> Result<()> {
751        let left: Either<u8, u8> = Either::new_left(10);
752        let mapped_left = left.map_left(|x| x * 10)?;
753        assert!(mapped_left.is_left());
754        assert_eq!(mapped_left.left_ref()?, &100);
755        Ok(())
756    }
757
758    #[test]
759    fn map_left_invalid() -> Result<()> {
760        let invalid = invalid();
761        assert!(invalid.map_left(ToString::to_string).is_err());
762        Ok(())
763    }
764
765    #[test]
766    fn map_left_on_right() -> Result<()> {
767        let right: Either<u8, u8> = Either::new_right(10);
768        let mapped_right = right.map_left(|x| x * 10)?;
769        assert_eq!(right, mapped_right);
770        Ok(())
771    }
772
773    #[test]
774    fn map_right() -> Result<()> {
775        let right: Either<u8, u8> = Either::new_right(10);
776        let mapped_right = right.map_right(|x| x * 10)?;
777        assert!(mapped_right.is_right());
778        assert_eq!(mapped_right.right_ref()?, &100);
779        Ok(())
780    }
781
782    #[test]
783    fn map_right_invalid() -> Result<()> {
784        let invalid = invalid();
785        assert!(invalid.map_right(ToString::to_string).is_err());
786        Ok(())
787    }
788
789    #[test]
790    fn map_right_on_left() -> Result<()> {
791        let left: Either<u8, u8> = Either::new_left(10);
792        let mapped_left = left.map_right(|x| x * 10)?;
793        assert_eq!(left, mapped_left);
794        Ok(())
795    }
796
797    #[test]
798    fn map_right_or_left_on_left() -> Result<()> {
799        let left: Either<u8, u8> = Either::new_left(10);
800        let mapped = left.map_left_or_right(|l| l * 10, |r| r * 5)?;
801        assert_eq!(mapped.left_ref()?, &100);
802        Ok(())
803    }
804
805    #[test]
806    fn and_then_left() -> Result<()> {
807        let left: Either<u16, u16> = Either::new_left(10);
808        let and_then_left: Either<u16, u16> = left
809            .and_then_left(|x| Either::new_left(x * 10))?
810            .and_then_left(|x: u16| Either::new_left(x * 10))?;
811        assert!(and_then_left.is_left());
812        assert_eq!(and_then_left.left_ref()?, &1000);
813        Ok(())
814    }
815
816    #[test]
817    fn and_then_left_on_right() -> Result<()> {
818        let right: Either<u8, u8> = Either::new_right(10);
819        let outcome = right.and_then_left(|x| Either::new_left(x * 10));
820        assert!(outcome.is_ok());
821        assert_eq!(outcome?, right);
822        Ok(())
823    }
824
825    #[test]
826    fn and_then_left_invalid() -> Result<()> {
827        let invalid = invalid();
828        assert!(invalid
829            .and_then_left(|x| Either::new_left(x.len()))
830            .is_err());
831        Ok(())
832    }
833
834    #[test]
835    fn and_then_right() -> Result<()> {
836        let right: Either<u16, u16> = Either::new_right(10);
837        let and_then_right: Either<u16, u16> = right
838            .and_then_right(|x| Either::new_right(x * 10))?
839            .and_then_right(|x| Either::new_right(x * 10))?;
840        assert!(and_then_right.is_right());
841        assert_eq!(and_then_right.right_ref()?, &1000);
842        Ok(())
843    }
844
845    #[test]
846    fn and_then_right_on_left() -> Result<()> {
847        let left: Either<u8, u8> = Either::new_left(10);
848        let outcome = left.and_then_right(|x| Either::new_right(x * 10));
849        assert!(outcome.is_ok());
850        assert_eq!(outcome?, left);
851        Ok(())
852    }
853
854    #[test]
855    fn and_then_right_invalid() -> Result<()> {
856        let invalid = invalid();
857        assert!(invalid
858            .and_then_right(|x| Either::new_right(x.len()))
859            .is_err());
860        Ok(())
861    }
862
863    #[test]
864    fn from_ok_result() -> Result<()> {
865        let result: std::result::Result<&str, &str> = Ok("ok");
866        let left = Either::from(result);
867        assert!(left.is_left());
868        assert_eq!(left.left_ref()?, &"ok");
869        Ok(())
870    }
871
872    #[test]
873    fn from_err_result() -> Result<()> {
874        let err: std::result::Result<&str, &str> = Err("err");
875        let right = Either::from(err);
876        assert!(right.is_right());
877        assert_eq!(right.right_ref()?, &"err");
878        Ok(())
879    }
880
881    #[test]
882    fn try_into_left_result() -> Result<()> {
883        let left = lefty();
884        let result: std::result::Result<&str, &str> = Either::try_into(left)?;
885        assert!(result.is_ok());
886        assert_eq!(result.unwrap(), "lefty");
887        Ok(())
888    }
889
890    #[test]
891    fn try_into_right_result() -> Result<()> {
892        let right = righty();
893        let result: std::result::Result<&str, &str> = Either::try_into(right)?;
894        assert!(result.is_err());
895        assert_eq!(result, Err("righty"));
896        Ok(())
897    }
898
899    #[test]
900    fn try_into_invalid() -> Result<()> {
901        let invalid = invalid();
902        let result: Result<std::result::Result<&str, &str>> = Either::try_into(invalid);
903        assert!(result.is_err());
904        Ok(())
905    }
906
907    #[test]
908    fn either_left_read() -> Result<()> {
909        let left_cursor = Cursor::new(vec![1, 2, 3, 4, 5]);
910        let mut left: Either<Cursor<Vec<u8>>, Cursor<Vec<u8>>> = Either::new_left(left_cursor);
911        let mut left_buf = [0_u8; 5];
912        assert_eq!(left.read(&mut left_buf)?, left_buf.len());
913        assert_eq!(left_buf, &vec![1, 2, 3, 4, 5][..]);
914        Ok(())
915    }
916
917    #[test]
918    fn either_right_read() -> Result<()> {
919        let right_cursor = Cursor::new(vec![10, 9, 8, 7, 6]);
920        let mut right: Either<Cursor<Vec<u8>>, Cursor<Vec<u8>>> = Either::new_right(right_cursor);
921        let mut right_buf = [0_u8; 5];
922        assert_eq!(right.read(&mut right_buf)?, right_buf.len());
923        assert_eq!(right_buf, &vec![10, 9, 8, 7, 6][..]);
924        Ok(())
925    }
926
927    #[test]
928    fn either_left_write() -> Result<()> {
929        let left_buf = Vec::new();
930        let hello = b"hello";
931
932        let mut left: Either<Vec<u8>, Vec<u8>> = Either::new_left(left_buf);
933        assert_eq!(left.write(hello)?, 5);
934        assert_eq!(&left.left_ref()?[..], b"hello");
935        Ok(())
936    }
937
938    #[test]
939    fn either_right_write() -> Result<()> {
940        let right_buf = Vec::new();
941        let hello = b"hello";
942
943        let mut right: Either<Vec<u8>, Vec<u8>> = Either::new_right(right_buf);
944        assert_eq!(right.write(hello)?, 5);
945        assert_eq!(&right.right_ref()?[..], b"hello");
946        Ok(())
947    }
948
949    #[test]
950    fn either_left_iter() -> Result<()> {
951        let left: Either<Vec<u32>, Vec<u32>> = Either::new_left(vec![1, 2, 3, 4, 5]);
952        let mut right: Either<Vec<u32>, Vec<u32>> = Either::new_right(vec![5, 4, 3, 2, 1]);
953        right.extend(left.into_iter()?);
954        assert_eq!(right.right_ref()?, &vec![5, 4, 3, 2, 1, 1, 2, 3, 4, 5]);
955        Ok(())
956    }
957
958    #[test]
959    fn either_right_iter() -> Result<()> {
960        let mut left: Either<Vec<u32>, Vec<u32>> = Either::new_left(vec![1, 2, 3, 4, 5]);
961        let right: Either<Vec<u32>, Vec<u32>> = Either::new_right(vec![5, 4, 3, 2, 1]);
962        left.extend(right.into_iter()?);
963        assert_eq!(left.left_ref()?, &vec![1, 2, 3, 4, 5, 5, 4, 3, 2, 1]);
964        Ok(())
965    }
966
967    #[test]
968    fn invalid_into_iter() -> Result<()> {
969        let invalid: Either<Vec<u32>, Vec<u32>> = Either {
970            left: None,
971            right: None,
972        };
973        assert!(invalid.into_iter().is_err());
974        Ok(())
975    }
976
977    #[test]
978    #[cfg(feature = "serde")]
979    fn serialize_json_left() -> Result<()> {
980        let left = lefty();
981        let json = serde_json::to_string(&left)?;
982        assert_eq!(json, r#"{"left":"lefty","right":null}"#);
983        Ok(())
984    }
985
986    #[test]
987    #[cfg(feature = "serde")]
988    fn serialize_toml_left() -> Result<()> {
989        let left = lefty();
990        let toml = toml::to_string(&left)?;
991        assert_eq!(
992            toml,
993            r#"left = "lefty"
994"#
995        );
996        Ok(())
997    }
998
999    #[test]
1000    #[cfg(feature = "serde")]
1001    fn serialize_json_right() -> Result<()> {
1002        let right = righty();
1003        let json = serde_json::to_string(&right)?;
1004        assert_eq!(json, r#"{"left":null,"right":"righty"}"#);
1005        Ok(())
1006    }
1007
1008    #[test]
1009    #[cfg(feature = "serde")]
1010    fn serialize_toml_right() -> Result<()> {
1011        let right = righty();
1012        let toml = toml::to_string(&right)?;
1013        assert_eq!(
1014            toml,
1015            r#"right = "righty"
1016"#
1017        );
1018        Ok(())
1019    }
1020
1021    #[test]
1022    #[cfg(feature = "serde")]
1023    fn deserialize_json_left() -> Result<()> {
1024        let json = r#"{"left":"lefty","right":null}"#;
1025        let left: Either<&str, &str> = serde_json::from_str(&json)?;
1026        assert!(left.is_left());
1027        assert_eq!(left.left_ref()?, &"lefty");
1028        Ok(())
1029    }
1030
1031    #[test]
1032    #[cfg(feature = "serde")]
1033    fn deserialize_toml_left() -> Result<()> {
1034        let toml = r#"left = "lefty"
1035"#;
1036        let left: Either<&str, &str> = toml::from_str(&toml)?;
1037        assert!(left.is_left());
1038        assert_eq!(left.left_ref()?, &"lefty");
1039        Ok(())
1040    }
1041
1042    #[test]
1043    #[cfg(feature = "serde")]
1044    fn deserialize_json_right() -> Result<()> {
1045        let json = r#"{"left":null,"right":"righty"}"#;
1046        let right: Either<&str, &str> = serde_json::from_str(&json)?;
1047        assert!(right.is_right());
1048        assert_eq!(right.right_ref()?, &"righty");
1049        Ok(())
1050    }
1051
1052    #[test]
1053    #[cfg(feature = "serde")]
1054    fn deserialize_toml_right() -> Result<()> {
1055        let toml = r#"right = "righty"
1056"#;
1057        let right: Either<&str, &str> = toml::from_str(&toml)?;
1058        assert!(right.is_right());
1059        assert_eq!(right.right_ref()?, &"righty");
1060        Ok(())
1061    }
1062}