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