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