1//! The enum [`Either`] with variants `Left` and `Right` is a general purpose 2//! sum type with two cases. 3//! 4//! [`Either`]: enum.Either.html 5//! 6//! **Crate features:** 7//! 8//! * `"use_std"` 9//! Enabled by default. Disable to make the library `#![no_std]`. 10//! 11//! * `"serde"` 12//! Disabled by default. Enable to `#[derive(Serialize, Deserialize)]` for `Either` 13//! 14 15#![doc(html_root_url = "https://docs.rs/either/1/")] 16#![no_std] 17 18#[cfg(any(test, feature = "use_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::iter; 31use core::ops::Deref; 32use core::ops::DerefMut; 33use core::pin::Pin; 34 35#[cfg(any(test, feature = "use_std"))] 36use std::error::Error; 37#[cfg(any(test, feature = "use_std"))] 38use std::io::{self, BufRead, Read, Seek, SeekFrom, Write}; 39 40pub use crate::Either::{Left, Right}; 41 42/// The enum `Either` with variants `Left` and `Right` is a general purpose 43/// sum type with two cases. 44/// 45/// The `Either` type is symmetric and treats its variants the same way, without 46/// preference. 47/// (For representing success or error, use the regular `Result` enum instead.) 48#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 49#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 50pub enum Either<L, R> { 51 /// A value of type `L`. 52 Left(L), 53 /// A value of type `R`. 54 Right(R), 55} 56 57/// Evaluate the provided expression for both [`Either::Left`] and [`Either::Right`]. 58/// 59/// This macro is useful in cases where both sides of [`Either`] can be interacted with 60/// in the same way even though the don't share the same type. 61/// 62/// Syntax: `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)` 63/// 64/// # Example 65/// 66/// ``` 67/// use either::Either; 68/// 69/// fn length(owned_or_borrowed: Either<String, &'static str>) -> usize { 70/// either::for_both!(owned_or_borrowed, s => s.len()) 71/// } 72/// 73/// fn main() { 74/// let borrowed = Either::Right("Hello world!"); 75/// let owned = Either::Left("Hello world!".to_owned()); 76/// 77/// assert_eq!(length(borrowed), 12); 78/// assert_eq!(length(owned), 12); 79/// } 80/// ``` 81#[macro_export] 82macro_rules! for_both { 83 ($value:expr, $pattern:pat => $result:expr) => { 84 match $value { 85 $crate::Either::Left($pattern) => $result, 86 $crate::Either::Right($pattern) => $result, 87 } 88 }; 89} 90 91/// Macro for unwrapping the left side of an `Either`, which fails early 92/// with the opposite side. Can only be used in functions that return 93/// `Either` because of the early return of `Right` that it provides. 94/// 95/// See also `try_right!` for its dual, which applies the same just to the 96/// right side. 97/// 98/// # Example 99/// 100/// ``` 101/// use either::{Either, Left, Right}; 102/// 103/// fn twice(wrapper: Either<u32, &str>) -> Either<u32, &str> { 104/// let value = either::try_left!(wrapper); 105/// Left(value * 2) 106/// } 107/// 108/// fn main() { 109/// assert_eq!(twice(Left(2)), Left(4)); 110/// assert_eq!(twice(Right("ups")), Right("ups")); 111/// } 112/// ``` 113#[macro_export] 114macro_rules! try_left { 115 ($expr:expr) => { 116 match $expr { 117 $crate::Left(val) => val, 118 $crate::Right(err) => return $crate::Right(::core::convert::From::from(err)), 119 } 120 }; 121} 122 123/// Dual to `try_left!`, see its documentation for more information. 124#[macro_export] 125macro_rules! try_right { 126 ($expr:expr) => { 127 match $expr { 128 $crate::Left(err) => return $crate::Left(::core::convert::From::from(err)), 129 $crate::Right(val) => val, 130 } 131 }; 132} 133 134impl<L: Clone, R: Clone> Clone for Either<L, R> { 135 fn clone(&self) -> Self { 136 match self { 137 Left(inner) => Left(inner.clone()), 138 Right(inner) => Right(inner.clone()), 139 } 140 } 141 142 fn clone_from(&mut self, source: &Self) { 143 match (self, source) { 144 (Left(dest), Left(source)) => dest.clone_from(source), 145 (Right(dest), Right(source)) => dest.clone_from(source), 146 (dest, source) => *dest = source.clone(), 147 } 148 } 149} 150 151impl<L, R> Either<L, R> { 152 /// Return true if the value is the `Left` variant. 153 /// 154 /// ``` 155 /// use either::*; 156 /// 157 /// let values = [Left(1), Right("the right value")]; 158 /// assert_eq!(values[0].is_left(), true); 159 /// assert_eq!(values[1].is_left(), false); 160 /// ``` 161 pub fn is_left(&self) -> bool { 162 match *self { 163 Left(_) => true, 164 Right(_) => false, 165 } 166 } 167 168 /// Return true if the value is the `Right` variant. 169 /// 170 /// ``` 171 /// use either::*; 172 /// 173 /// let values = [Left(1), Right("the right value")]; 174 /// assert_eq!(values[0].is_right(), false); 175 /// assert_eq!(values[1].is_right(), true); 176 /// ``` 177 pub fn is_right(&self) -> bool { 178 !self.is_left() 179 } 180 181 /// Convert the left side of `Either<L, R>` to an `Option<L>`. 182 /// 183 /// ``` 184 /// use either::*; 185 /// 186 /// let left: Either<_, ()> = Left("some value"); 187 /// assert_eq!(left.left(), Some("some value")); 188 /// 189 /// let right: Either<(), _> = Right(321); 190 /// assert_eq!(right.left(), None); 191 /// ``` 192 pub fn left(self) -> Option<L> { 193 match self { 194 Left(l) => Some(l), 195 Right(_) => None, 196 } 197 } 198 199 /// Convert the right side of `Either<L, R>` to an `Option<R>`. 200 /// 201 /// ``` 202 /// use either::*; 203 /// 204 /// let left: Either<_, ()> = Left("some value"); 205 /// assert_eq!(left.right(), None); 206 /// 207 /// let right: Either<(), _> = Right(321); 208 /// assert_eq!(right.right(), Some(321)); 209 /// ``` 210 pub fn right(self) -> Option<R> { 211 match self { 212 Left(_) => None, 213 Right(r) => Some(r), 214 } 215 } 216 217 /// Convert `&Either<L, R>` to `Either<&L, &R>`. 218 /// 219 /// ``` 220 /// use either::*; 221 /// 222 /// let left: Either<_, ()> = Left("some value"); 223 /// assert_eq!(left.as_ref(), Left(&"some value")); 224 /// 225 /// let right: Either<(), _> = Right("some value"); 226 /// assert_eq!(right.as_ref(), Right(&"some value")); 227 /// ``` 228 pub fn as_ref(&self) -> Either<&L, &R> { 229 match *self { 230 Left(ref inner) => Left(inner), 231 Right(ref inner) => Right(inner), 232 } 233 } 234 235 /// Convert `&mut Either<L, R>` to `Either<&mut L, &mut R>`. 236 /// 237 /// ``` 238 /// use either::*; 239 /// 240 /// fn mutate_left(value: &mut Either<u32, u32>) { 241 /// if let Some(l) = value.as_mut().left() { 242 /// *l = 999; 243 /// } 244 /// } 245 /// 246 /// let mut left = Left(123); 247 /// let mut right = Right(123); 248 /// mutate_left(&mut left); 249 /// mutate_left(&mut right); 250 /// assert_eq!(left, Left(999)); 251 /// assert_eq!(right, Right(123)); 252 /// ``` 253 pub fn as_mut(&mut self) -> Either<&mut L, &mut R> { 254 match *self { 255 Left(ref mut inner) => Left(inner), 256 Right(ref mut inner) => Right(inner), 257 } 258 } 259 260 /// Convert `Pin<&Either<L, R>>` to `Either<Pin<&L>, Pin<&R>>`, 261 /// pinned projections of the inner variants. 262 pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>> { 263 // SAFETY: We can use `new_unchecked` because the `inner` parts are 264 // guaranteed to be pinned, as they come from `self` which is pinned. 265 unsafe { 266 match *Pin::get_ref(self) { 267 Left(ref inner) => Left(Pin::new_unchecked(inner)), 268 Right(ref inner) => Right(Pin::new_unchecked(inner)), 269 } 270 } 271 } 272 273 /// Convert `Pin<&mut Either<L, R>>` to `Either<Pin<&mut L>, Pin<&mut R>>`, 274 /// pinned projections of the inner variants. 275 pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>> { 276 // SAFETY: `get_unchecked_mut` is fine because we don't move anything. 277 // We can use `new_unchecked` because the `inner` parts are guaranteed 278 // to be pinned, as they come from `self` which is pinned, and we never 279 // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We 280 // also don't have an implementation of `Drop`, nor manual `Unpin`. 281 unsafe { 282 match *Pin::get_unchecked_mut(self) { 283 Left(ref mut inner) => Left(Pin::new_unchecked(inner)), 284 Right(ref mut inner) => Right(Pin::new_unchecked(inner)), 285 } 286 } 287 } 288 289 /// Convert `Either<L, R>` to `Either<R, L>`. 290 /// 291 /// ``` 292 /// use either::*; 293 /// 294 /// let left: Either<_, ()> = Left(123); 295 /// assert_eq!(left.flip(), Right(123)); 296 /// 297 /// let right: Either<(), _> = Right("some value"); 298 /// assert_eq!(right.flip(), Left("some value")); 299 /// ``` 300 pub fn flip(self) -> Either<R, L> { 301 match self { 302 Left(l) => Right(l), 303 Right(r) => Left(r), 304 } 305 } 306 307 /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the 308 /// result in `Left`. 309 /// 310 /// ``` 311 /// use either::*; 312 /// 313 /// let left: Either<_, u32> = Left(123); 314 /// assert_eq!(left.map_left(|x| x * 2), Left(246)); 315 /// 316 /// let right: Either<u32, _> = Right(123); 317 /// assert_eq!(right.map_left(|x| x * 2), Right(123)); 318 /// ``` 319 pub fn map_left<F, M>(self, f: F) -> Either<M, R> 320 where 321 F: FnOnce(L) -> M, 322 { 323 match self { 324 Left(l) => Left(f(l)), 325 Right(r) => Right(r), 326 } 327 } 328 329 /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the 330 /// result in `Right`. 331 /// 332 /// ``` 333 /// use either::*; 334 /// 335 /// let left: Either<_, u32> = Left(123); 336 /// assert_eq!(left.map_right(|x| x * 2), Left(123)); 337 /// 338 /// let right: Either<u32, _> = Right(123); 339 /// assert_eq!(right.map_right(|x| x * 2), Right(246)); 340 /// ``` 341 pub fn map_right<F, S>(self, f: F) -> Either<L, S> 342 where 343 F: FnOnce(R) -> S, 344 { 345 match self { 346 Left(l) => Left(l), 347 Right(r) => Right(f(r)), 348 } 349 } 350 351 /// Apply one of two functions depending on contents, unifying their result. If the value is 352 /// `Left(L)` then the first function `f` is applied; if it is `Right(R)` then the second 353 /// function `g` is applied. 354 /// 355 /// ``` 356 /// use either::*; 357 /// 358 /// fn square(n: u32) -> i32 { (n * n) as i32 } 359 /// fn negate(n: i32) -> i32 { -n } 360 /// 361 /// let left: Either<u32, i32> = Left(4); 362 /// assert_eq!(left.either(square, negate), 16); 363 /// 364 /// let right: Either<u32, i32> = Right(-4); 365 /// assert_eq!(right.either(square, negate), 4); 366 /// ``` 367 pub fn either<F, G, T>(self, f: F, g: G) -> T 368 where 369 F: FnOnce(L) -> T, 370 G: FnOnce(R) -> T, 371 { 372 match self { 373 Left(l) => f(l), 374 Right(r) => g(r), 375 } 376 } 377 378 /// Like `either`, but provide some context to whichever of the 379 /// functions ends up being called. 380 /// 381 /// ``` 382 /// // In this example, the context is a mutable reference 383 /// use either::*; 384 /// 385 /// let mut result = Vec::new(); 386 /// 387 /// let values = vec![Left(2), Right(2.7)]; 388 /// 389 /// for value in values { 390 /// value.either_with(&mut result, 391 /// |ctx, integer| ctx.push(integer), 392 /// |ctx, real| ctx.push(f64::round(real) as i32)); 393 /// } 394 /// 395 /// assert_eq!(result, vec![2, 3]); 396 /// ``` 397 pub fn either_with<Ctx, F, G, T>(self, ctx: Ctx, f: F, g: G) -> T 398 where 399 F: FnOnce(Ctx, L) -> T, 400 G: FnOnce(Ctx, R) -> T, 401 { 402 match self { 403 Left(l) => f(ctx, l), 404 Right(r) => g(ctx, r), 405 } 406 } 407 408 /// Apply the function `f` on the value in the `Left` variant if it is present. 409 /// 410 /// ``` 411 /// use either::*; 412 /// 413 /// let left: Either<_, u32> = Left(123); 414 /// assert_eq!(left.left_and_then::<_,()>(|x| Right(x * 2)), Right(246)); 415 /// 416 /// let right: Either<u32, _> = Right(123); 417 /// assert_eq!(right.left_and_then(|x| Right::<(), _>(x * 2)), Right(123)); 418 /// ``` 419 pub fn left_and_then<F, S>(self, f: F) -> Either<S, R> 420 where 421 F: FnOnce(L) -> Either<S, R>, 422 { 423 match self { 424 Left(l) => f(l), 425 Right(r) => Right(r), 426 } 427 } 428 429 /// Apply the function `f` on the value in the `Right` variant if it is present. 430 /// 431 /// ``` 432 /// use either::*; 433 /// 434 /// let left: Either<_, u32> = Left(123); 435 /// assert_eq!(left.right_and_then(|x| Right(x * 2)), Left(123)); 436 /// 437 /// let right: Either<u32, _> = Right(123); 438 /// assert_eq!(right.right_and_then(|x| Right(x * 2)), Right(246)); 439 /// ``` 440 pub fn right_and_then<F, S>(self, f: F) -> Either<L, S> 441 where 442 F: FnOnce(R) -> Either<L, S>, 443 { 444 match self { 445 Left(l) => Left(l), 446 Right(r) => f(r), 447 } 448 } 449 450 /// Convert the inner value to an iterator. 451 /// 452 /// ``` 453 /// use either::*; 454 /// 455 /// let left: Either<_, Vec<u32>> = Left(vec![1, 2, 3, 4, 5]); 456 /// let mut right: Either<Vec<u32>, _> = Right(vec![]); 457 /// right.extend(left.into_iter()); 458 /// assert_eq!(right, Right(vec![1, 2, 3, 4, 5])); 459 /// ``` 460 #[allow(clippy::should_implement_trait)] 461 pub fn into_iter(self) -> Either<L::IntoIter, R::IntoIter> 462 where 463 L: IntoIterator, 464 R: IntoIterator<Item = L::Item>, 465 { 466 match self { 467 Left(l) => Left(l.into_iter()), 468 Right(r) => Right(r.into_iter()), 469 } 470 } 471 472 /// Return left value or given value 473 /// 474 /// Arguments passed to `left_or` are eagerly evaluated; if you are passing 475 /// the result of a function call, it is recommended to use [`left_or_else`], 476 /// which is lazily evaluated. 477 /// 478 /// [`left_or_else`]: #method.left_or_else 479 /// 480 /// # Examples 481 /// 482 /// ``` 483 /// # use either::*; 484 /// let left: Either<&str, &str> = Left("left"); 485 /// assert_eq!(left.left_or("foo"), "left"); 486 /// 487 /// let right: Either<&str, &str> = Right("right"); 488 /// assert_eq!(right.left_or("left"), "left"); 489 /// ``` 490 pub fn left_or(self, other: L) -> L { 491 match self { 492 Either::Left(l) => l, 493 Either::Right(_) => other, 494 } 495 } 496 497 /// Return left or a default 498 /// 499 /// # Examples 500 /// 501 /// ``` 502 /// # use either::*; 503 /// let left: Either<String, u32> = Left("left".to_string()); 504 /// assert_eq!(left.left_or_default(), "left"); 505 /// 506 /// let right: Either<String, u32> = Right(42); 507 /// assert_eq!(right.left_or_default(), String::default()); 508 /// ``` 509 pub fn left_or_default(self) -> L 510 where 511 L: Default, 512 { 513 match self { 514 Either::Left(l) => l, 515 Either::Right(_) => L::default(), 516 } 517 } 518 519 /// Returns left value or computes it from a closure 520 /// 521 /// # Examples 522 /// 523 /// ``` 524 /// # use either::*; 525 /// let left: Either<String, u32> = Left("3".to_string()); 526 /// assert_eq!(left.left_or_else(|_| unreachable!()), "3"); 527 /// 528 /// let right: Either<String, u32> = Right(3); 529 /// assert_eq!(right.left_or_else(|x| x.to_string()), "3"); 530 /// ``` 531 pub fn left_or_else<F>(self, f: F) -> L 532 where 533 F: FnOnce(R) -> L, 534 { 535 match self { 536 Either::Left(l) => l, 537 Either::Right(r) => f(r), 538 } 539 } 540 541 /// Return right value or given value 542 /// 543 /// Arguments passed to `right_or` are eagerly evaluated; if you are passing 544 /// the result of a function call, it is recommended to use [`right_or_else`], 545 /// which is lazily evaluated. 546 /// 547 /// [`right_or_else`]: #method.right_or_else 548 /// 549 /// # Examples 550 /// 551 /// ``` 552 /// # use either::*; 553 /// let right: Either<&str, &str> = Right("right"); 554 /// assert_eq!(right.right_or("foo"), "right"); 555 /// 556 /// let left: Either<&str, &str> = Left("left"); 557 /// assert_eq!(left.right_or("right"), "right"); 558 /// ``` 559 pub fn right_or(self, other: R) -> R { 560 match self { 561 Either::Left(_) => other, 562 Either::Right(r) => r, 563 } 564 } 565 566 /// Return right or a default 567 /// 568 /// # Examples 569 /// 570 /// ``` 571 /// # use either::*; 572 /// let left: Either<String, u32> = Left("left".to_string()); 573 /// assert_eq!(left.right_or_default(), u32::default()); 574 /// 575 /// let right: Either<String, u32> = Right(42); 576 /// assert_eq!(right.right_or_default(), 42); 577 /// ``` 578 pub fn right_or_default(self) -> R 579 where 580 R: Default, 581 { 582 match self { 583 Either::Left(_) => R::default(), 584 Either::Right(r) => r, 585 } 586 } 587 588 /// Returns right value or computes it from a closure 589 /// 590 /// # Examples 591 /// 592 /// ``` 593 /// # use either::*; 594 /// let left: Either<String, u32> = Left("3".to_string()); 595 /// assert_eq!(left.right_or_else(|x| x.parse().unwrap()), 3); 596 /// 597 /// let right: Either<String, u32> = Right(3); 598 /// assert_eq!(right.right_or_else(|_| unreachable!()), 3); 599 /// ``` 600 pub fn right_or_else<F>(self, f: F) -> R 601 where 602 F: FnOnce(L) -> R, 603 { 604 match self { 605 Either::Left(l) => f(l), 606 Either::Right(r) => r, 607 } 608 } 609 610 /// Returns the left value 611 /// 612 /// # Examples 613 /// 614 /// ``` 615 /// # use either::*; 616 /// let left: Either<_, ()> = Left(3); 617 /// assert_eq!(left.unwrap_left(), 3); 618 /// ``` 619 /// 620 /// # Panics 621 /// 622 /// When `Either` is a `Right` value 623 /// 624 /// ```should_panic 625 /// # use either::*; 626 /// let right: Either<(), _> = Right(3); 627 /// right.unwrap_left(); 628 /// ``` 629 pub fn unwrap_left(self) -> L 630 where 631 R: core::fmt::Debug, 632 { 633 match self { 634 Either::Left(l) => l, 635 Either::Right(r) => { 636 panic!("called `Either::unwrap_left()` on a `Right` value: {:?}", r) 637 } 638 } 639 } 640 641 /// Returns the right value 642 /// 643 /// # Examples 644 /// 645 /// ``` 646 /// # use either::*; 647 /// let right: Either<(), _> = Right(3); 648 /// assert_eq!(right.unwrap_right(), 3); 649 /// ``` 650 /// 651 /// # Panics 652 /// 653 /// When `Either` is a `Left` value 654 /// 655 /// ```should_panic 656 /// # use either::*; 657 /// let left: Either<_, ()> = Left(3); 658 /// left.unwrap_right(); 659 /// ``` 660 pub fn unwrap_right(self) -> R 661 where 662 L: core::fmt::Debug, 663 { 664 match self { 665 Either::Right(r) => r, 666 Either::Left(l) => panic!("called `Either::unwrap_right()` on a `Left` value: {:?}", l), 667 } 668 } 669 670 /// Returns the left value 671 /// 672 /// # Examples 673 /// 674 /// ``` 675 /// # use either::*; 676 /// let left: Either<_, ()> = Left(3); 677 /// assert_eq!(left.expect_left("value was Right"), 3); 678 /// ``` 679 /// 680 /// # Panics 681 /// 682 /// When `Either` is a `Right` value 683 /// 684 /// ```should_panic 685 /// # use either::*; 686 /// let right: Either<(), _> = Right(3); 687 /// right.expect_left("value was Right"); 688 /// ``` 689 pub fn expect_left(self, msg: &str) -> L 690 where 691 R: core::fmt::Debug, 692 { 693 match self { 694 Either::Left(l) => l, 695 Either::Right(r) => panic!("{}: {:?}", msg, r), 696 } 697 } 698 699 /// Returns the right value 700 /// 701 /// # Examples 702 /// 703 /// ``` 704 /// # use either::*; 705 /// let right: Either<(), _> = Right(3); 706 /// assert_eq!(right.expect_right("value was Left"), 3); 707 /// ``` 708 /// 709 /// # Panics 710 /// 711 /// When `Either` is a `Left` value 712 /// 713 /// ```should_panic 714 /// # use either::*; 715 /// let left: Either<_, ()> = Left(3); 716 /// left.expect_right("value was Right"); 717 /// ``` 718 pub fn expect_right(self, msg: &str) -> R 719 where 720 L: core::fmt::Debug, 721 { 722 match self { 723 Either::Right(r) => r, 724 Either::Left(l) => panic!("{}: {:?}", msg, l), 725 } 726 } 727 728 /// Convert the contained value into `T` 729 /// 730 /// # Examples 731 /// 732 /// ``` 733 /// # use either::*; 734 /// // Both u16 and u32 can be converted to u64. 735 /// let left: Either<u16, u32> = Left(3u16); 736 /// assert_eq!(left.either_into::<u64>(), 3u64); 737 /// let right: Either<u16, u32> = Right(7u32); 738 /// assert_eq!(right.either_into::<u64>(), 7u64); 739 /// ``` 740 pub fn either_into<T>(self) -> T 741 where 742 L: Into<T>, 743 R: Into<T>, 744 { 745 match self { 746 Either::Left(l) => l.into(), 747 Either::Right(r) => r.into(), 748 } 749 } 750} 751 752impl<L, R> Either<Option<L>, Option<R>> { 753 /// Factors out `None` from an `Either` of [`Option`]. 754 /// 755 /// ``` 756 /// use either::*; 757 /// let left: Either<_, Option<String>> = Left(Some(vec![0])); 758 /// assert_eq!(left.factor_none(), Some(Left(vec![0]))); 759 /// 760 /// let right: Either<Option<Vec<u8>>, _> = Right(Some(String::new())); 761 /// assert_eq!(right.factor_none(), Some(Right(String::new()))); 762 /// ``` 763 // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 764 // #[doc(alias = "transpose")] 765 pub fn factor_none(self) -> Option<Either<L, R>> { 766 match self { 767 Left(l) => l.map(Either::Left), 768 Right(r) => r.map(Either::Right), 769 } 770 } 771} 772 773impl<L, R, E> Either<Result<L, E>, Result<R, E>> { 774 /// Factors out a homogenous type from an `Either` of [`Result`]. 775 /// 776 /// Here, the homogeneous type is the `Err` type of the [`Result`]. 777 /// 778 /// ``` 779 /// use either::*; 780 /// let left: Either<_, Result<String, u32>> = Left(Ok(vec![0])); 781 /// assert_eq!(left.factor_err(), Ok(Left(vec![0]))); 782 /// 783 /// let right: Either<Result<Vec<u8>, u32>, _> = Right(Ok(String::new())); 784 /// assert_eq!(right.factor_err(), Ok(Right(String::new()))); 785 /// ``` 786 // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 787 // #[doc(alias = "transpose")] 788 pub fn factor_err(self) -> Result<Either<L, R>, E> { 789 match self { 790 Left(l) => l.map(Either::Left), 791 Right(r) => r.map(Either::Right), 792 } 793 } 794} 795 796impl<T, L, R> Either<Result<T, L>, Result<T, R>> { 797 /// Factors out a homogenous type from an `Either` of [`Result`]. 798 /// 799 /// Here, the homogeneous type is the `Ok` type of the [`Result`]. 800 /// 801 /// ``` 802 /// use either::*; 803 /// let left: Either<_, Result<u32, String>> = Left(Err(vec![0])); 804 /// assert_eq!(left.factor_ok(), Err(Left(vec![0]))); 805 /// 806 /// let right: Either<Result<u32, Vec<u8>>, _> = Right(Err(String::new())); 807 /// assert_eq!(right.factor_ok(), Err(Right(String::new()))); 808 /// ``` 809 // TODO(MSRV): doc(alias) was stabilized in Rust 1.48 810 // #[doc(alias = "transpose")] 811 pub fn factor_ok(self) -> Result<T, Either<L, R>> { 812 match self { 813 Left(l) => l.map_err(Either::Left), 814 Right(r) => r.map_err(Either::Right), 815 } 816 } 817} 818 819impl<T, L, R> Either<(T, L), (T, R)> { 820 /// Factor out a homogeneous type from an either of pairs. 821 /// 822 /// Here, the homogeneous type is the first element of the pairs. 823 /// 824 /// ``` 825 /// use either::*; 826 /// let left: Either<_, (u32, String)> = Left((123, vec![0])); 827 /// assert_eq!(left.factor_first().0, 123); 828 /// 829 /// let right: Either<(u32, Vec<u8>), _> = Right((123, String::new())); 830 /// assert_eq!(right.factor_first().0, 123); 831 /// ``` 832 pub fn factor_first(self) -> (T, Either<L, R>) { 833 match self { 834 Left((t, l)) => (t, Left(l)), 835 Right((t, r)) => (t, Right(r)), 836 } 837 } 838} 839 840impl<T, L, R> Either<(L, T), (R, T)> { 841 /// Factor out a homogeneous type from an either of pairs. 842 /// 843 /// Here, the homogeneous type is the second element of the pairs. 844 /// 845 /// ``` 846 /// use either::*; 847 /// let left: Either<_, (String, u32)> = Left((vec![0], 123)); 848 /// assert_eq!(left.factor_second().1, 123); 849 /// 850 /// let right: Either<(Vec<u8>, u32), _> = Right((String::new(), 123)); 851 /// assert_eq!(right.factor_second().1, 123); 852 /// ``` 853 pub fn factor_second(self) -> (Either<L, R>, T) { 854 match self { 855 Left((l, t)) => (Left(l), t), 856 Right((r, t)) => (Right(r), t), 857 } 858 } 859} 860 861impl<T> Either<T, T> { 862 /// Extract the value of an either over two equivalent types. 863 /// 864 /// ``` 865 /// use either::*; 866 /// 867 /// let left: Either<_, u32> = Left(123); 868 /// assert_eq!(left.into_inner(), 123); 869 /// 870 /// let right: Either<u32, _> = Right(123); 871 /// assert_eq!(right.into_inner(), 123); 872 /// ``` 873 pub fn into_inner(self) -> T { 874 for_both!(self, inner => inner) 875 } 876 877 /// Map `f` over the contained value and return the result in the 878 /// corresponding variant. 879 /// 880 /// ``` 881 /// use either::*; 882 /// 883 /// let value: Either<_, i32> = Right(42); 884 /// 885 /// let other = value.map(|x| x * 2); 886 /// assert_eq!(other, Right(84)); 887 /// ``` 888 pub fn map<F, M>(self, f: F) -> Either<M, M> 889 where 890 F: FnOnce(T) -> M, 891 { 892 match self { 893 Left(l) => Left(f(l)), 894 Right(r) => Right(f(r)), 895 } 896 } 897} 898 899/// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`. 900impl<L, R> From<Result<R, L>> for Either<L, R> { 901 fn from(r: Result<R, L>) -> Self { 902 match r { 903 Err(e) => Left(e), 904 Ok(o) => Right(o), 905 } 906 } 907} 908 909/// Convert from `Either` to `Result` with `Right => Ok` and `Left => Err`. 910#[allow(clippy::from_over_into)] // From requires RFC 2451, Rust 1.41 911impl<L, R> Into<Result<R, L>> for Either<L, R> { 912 fn into(self) -> Result<R, L> { 913 match self { 914 Left(l) => Err(l), 915 Right(r) => Ok(r), 916 } 917 } 918} 919 920impl<L, R, A> Extend<A> for Either<L, R> 921where 922 L: Extend<A>, 923 R: Extend<A>, 924{ 925 fn extend<T>(&mut self, iter: T) 926 where 927 T: IntoIterator<Item = A>, 928 { 929 for_both!(*self, ref mut inner => inner.extend(iter)) 930 } 931} 932 933/// `Either<L, R>` is an iterator if both `L` and `R` are iterators. 934impl<L, R> Iterator for Either<L, R> 935where 936 L: Iterator, 937 R: Iterator<Item = L::Item>, 938{ 939 type Item = L::Item; 940 941 fn next(&mut self) -> Option<Self::Item> { 942 for_both!(*self, ref mut inner => inner.next()) 943 } 944 945 fn size_hint(&self) -> (usize, Option<usize>) { 946 for_both!(*self, ref inner => inner.size_hint()) 947 } 948 949 fn fold<Acc, G>(self, init: Acc, f: G) -> Acc 950 where 951 G: FnMut(Acc, Self::Item) -> Acc, 952 { 953 for_both!(self, inner => inner.fold(init, f)) 954 } 955 956 fn for_each<F>(self, f: F) 957 where 958 F: FnMut(Self::Item), 959 { 960 for_both!(self, inner => inner.for_each(f)) 961 } 962 963 fn count(self) -> usize { 964 for_both!(self, inner => inner.count()) 965 } 966 967 fn last(self) -> Option<Self::Item> { 968 for_both!(self, inner => inner.last()) 969 } 970 971 fn nth(&mut self, n: usize) -> Option<Self::Item> { 972 for_both!(*self, ref mut inner => inner.nth(n)) 973 } 974 975 fn collect<B>(self) -> B 976 where 977 B: iter::FromIterator<Self::Item>, 978 { 979 for_both!(self, inner => inner.collect()) 980 } 981 982 fn partition<B, F>(self, f: F) -> (B, B) 983 where 984 B: Default + Extend<Self::Item>, 985 F: FnMut(&Self::Item) -> bool, 986 { 987 for_both!(self, inner => inner.partition(f)) 988 } 989 990 fn all<F>(&mut self, f: F) -> bool 991 where 992 F: FnMut(Self::Item) -> bool, 993 { 994 for_both!(*self, ref mut inner => inner.all(f)) 995 } 996 997 fn any<F>(&mut self, f: F) -> bool 998 where 999 F: FnMut(Self::Item) -> bool, 1000 { 1001 for_both!(*self, ref mut inner => inner.any(f)) 1002 } 1003 1004 fn find<P>(&mut self, predicate: P) -> Option<Self::Item> 1005 where 1006 P: FnMut(&Self::Item) -> bool, 1007 { 1008 for_both!(*self, ref mut inner => inner.find(predicate)) 1009 } 1010 1011 fn find_map<B, F>(&mut self, f: F) -> Option<B> 1012 where 1013 F: FnMut(Self::Item) -> Option<B>, 1014 { 1015 for_both!(*self, ref mut inner => inner.find_map(f)) 1016 } 1017 1018 fn position<P>(&mut self, predicate: P) -> Option<usize> 1019 where 1020 P: FnMut(Self::Item) -> bool, 1021 { 1022 for_both!(*self, ref mut inner => inner.position(predicate)) 1023 } 1024} 1025 1026impl<L, R> DoubleEndedIterator for Either<L, R> 1027where 1028 L: DoubleEndedIterator, 1029 R: DoubleEndedIterator<Item = L::Item>, 1030{ 1031 fn next_back(&mut self) -> Option<Self::Item> { 1032 for_both!(*self, ref mut inner => inner.next_back()) 1033 } 1034 1035 // TODO(MSRV): This was stabilized in Rust 1.37 1036 // fn nth_back(&mut self, n: usize) -> Option<Self::Item> { 1037 // for_both!(*self, ref mut inner => inner.nth_back(n)) 1038 // } 1039 1040 fn rfold<Acc, G>(self, init: Acc, f: G) -> Acc 1041 where 1042 G: FnMut(Acc, Self::Item) -> Acc, 1043 { 1044 for_both!(self, inner => inner.rfold(init, f)) 1045 } 1046 1047 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> 1048 where 1049 P: FnMut(&Self::Item) -> bool, 1050 { 1051 for_both!(*self, ref mut inner => inner.rfind(predicate)) 1052 } 1053} 1054 1055impl<L, R> ExactSizeIterator for Either<L, R> 1056where 1057 L: ExactSizeIterator, 1058 R: ExactSizeIterator<Item = L::Item>, 1059{ 1060 fn len(&self) -> usize { 1061 for_both!(*self, ref inner => inner.len()) 1062 } 1063} 1064 1065impl<L, R> iter::FusedIterator for Either<L, R> 1066where 1067 L: iter::FusedIterator, 1068 R: iter::FusedIterator<Item = L::Item>, 1069{ 1070} 1071 1072/// `Either<L, R>` is a future if both `L` and `R` are futures. 1073impl<L, R> Future for Either<L, R> 1074where 1075 L: Future, 1076 R: Future<Output = L::Output>, 1077{ 1078 type Output = L::Output; 1079 1080 fn poll( 1081 self: Pin<&mut Self>, 1082 cx: &mut core::task::Context<'_>, 1083 ) -> core::task::Poll<Self::Output> { 1084 for_both!(self.as_pin_mut(), inner => inner.poll(cx)) 1085 } 1086} 1087 1088#[cfg(any(test, feature = "use_std"))] 1089/// `Either<L, R>` implements `Read` if both `L` and `R` do. 1090/// 1091/// Requires crate feature `"use_std"` 1092impl<L, R> Read for Either<L, R> 1093where 1094 L: Read, 1095 R: Read, 1096{ 1097 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { 1098 for_both!(*self, ref mut inner => inner.read(buf)) 1099 } 1100 1101 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { 1102 for_both!(*self, ref mut inner => inner.read_exact(buf)) 1103 } 1104 1105 fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> { 1106 for_both!(*self, ref mut inner => inner.read_to_end(buf)) 1107 } 1108 1109 fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> { 1110 for_both!(*self, ref mut inner => inner.read_to_string(buf)) 1111 } 1112} 1113 1114#[cfg(any(test, feature = "use_std"))] 1115/// `Either<L, R>` implements `Seek` if both `L` and `R` do. 1116/// 1117/// Requires crate feature `"use_std"` 1118impl<L, R> Seek for Either<L, R> 1119where 1120 L: Seek, 1121 R: Seek, 1122{ 1123 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { 1124 for_both!(*self, ref mut inner => inner.seek(pos)) 1125 } 1126} 1127 1128#[cfg(any(test, feature = "use_std"))] 1129/// Requires crate feature `"use_std"` 1130impl<L, R> BufRead for Either<L, R> 1131where 1132 L: BufRead, 1133 R: BufRead, 1134{ 1135 fn fill_buf(&mut self) -> io::Result<&[u8]> { 1136 for_both!(*self, ref mut inner => inner.fill_buf()) 1137 } 1138 1139 fn consume(&mut self, amt: usize) { 1140 for_both!(*self, ref mut inner => inner.consume(amt)) 1141 } 1142 1143 fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> { 1144 for_both!(*self, ref mut inner => inner.read_until(byte, buf)) 1145 } 1146 1147 fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> { 1148 for_both!(*self, ref mut inner => inner.read_line(buf)) 1149 } 1150} 1151 1152#[cfg(any(test, feature = "use_std"))] 1153/// `Either<L, R>` implements `Write` if both `L` and `R` do. 1154/// 1155/// Requires crate feature `"use_std"` 1156impl<L, R> Write for Either<L, R> 1157where 1158 L: Write, 1159 R: Write, 1160{ 1161 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 1162 for_both!(*self, ref mut inner => inner.write(buf)) 1163 } 1164 1165 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { 1166 for_both!(*self, ref mut inner => inner.write_all(buf)) 1167 } 1168 1169 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { 1170 for_both!(*self, ref mut inner => inner.write_fmt(fmt)) 1171 } 1172 1173 fn flush(&mut self) -> io::Result<()> { 1174 for_both!(*self, ref mut inner => inner.flush()) 1175 } 1176} 1177 1178impl<L, R, Target> AsRef<Target> for Either<L, R> 1179where 1180 L: AsRef<Target>, 1181 R: AsRef<Target>, 1182{ 1183 fn as_ref(&self) -> &Target { 1184 for_both!(*self, ref inner => inner.as_ref()) 1185 } 1186} 1187 1188macro_rules! impl_specific_ref_and_mut { 1189 ($t:ty, $($attr:meta),* ) => { 1190 $(#[$attr])* 1191 impl<L, R> AsRef<$t> for Either<L, R> 1192 where L: AsRef<$t>, R: AsRef<$t> 1193 { 1194 fn as_ref(&self) -> &$t { 1195 for_both!(*self, ref inner => inner.as_ref()) 1196 } 1197 } 1198 1199 $(#[$attr])* 1200 impl<L, R> AsMut<$t> for Either<L, R> 1201 where L: AsMut<$t>, R: AsMut<$t> 1202 { 1203 fn as_mut(&mut self) -> &mut $t { 1204 for_both!(*self, ref mut inner => inner.as_mut()) 1205 } 1206 } 1207 }; 1208} 1209 1210impl_specific_ref_and_mut!(str,); 1211impl_specific_ref_and_mut!( 1212 ::std::path::Path, 1213 cfg(feature = "use_std"), 1214 doc = "Requires crate feature `use_std`." 1215); 1216impl_specific_ref_and_mut!( 1217 ::std::ffi::OsStr, 1218 cfg(feature = "use_std"), 1219 doc = "Requires crate feature `use_std`." 1220); 1221impl_specific_ref_and_mut!( 1222 ::std::ffi::CStr, 1223 cfg(feature = "use_std"), 1224 doc = "Requires crate feature `use_std`." 1225); 1226 1227impl<L, R, Target> AsRef<[Target]> for Either<L, R> 1228where 1229 L: AsRef<[Target]>, 1230 R: AsRef<[Target]>, 1231{ 1232 fn as_ref(&self) -> &[Target] { 1233 for_both!(*self, ref inner => inner.as_ref()) 1234 } 1235} 1236 1237impl<L, R, Target> AsMut<Target> for Either<L, R> 1238where 1239 L: AsMut<Target>, 1240 R: AsMut<Target>, 1241{ 1242 fn as_mut(&mut self) -> &mut Target { 1243 for_both!(*self, ref mut inner => inner.as_mut()) 1244 } 1245} 1246 1247impl<L, R, Target> AsMut<[Target]> for Either<L, R> 1248where 1249 L: AsMut<[Target]>, 1250 R: AsMut<[Target]>, 1251{ 1252 fn as_mut(&mut self) -> &mut [Target] { 1253 for_both!(*self, ref mut inner => inner.as_mut()) 1254 } 1255} 1256 1257impl<L, R> Deref for Either<L, R> 1258where 1259 L: Deref, 1260 R: Deref<Target = L::Target>, 1261{ 1262 type Target = L::Target; 1263 1264 fn deref(&self) -> &Self::Target { 1265 for_both!(*self, ref inner => &**inner) 1266 } 1267} 1268 1269impl<L, R> DerefMut for Either<L, R> 1270where 1271 L: DerefMut, 1272 R: DerefMut<Target = L::Target>, 1273{ 1274 fn deref_mut(&mut self) -> &mut Self::Target { 1275 for_both!(*self, ref mut inner => &mut *inner) 1276 } 1277} 1278 1279#[cfg(any(test, feature = "use_std"))] 1280/// `Either` implements `Error` if *both* `L` and `R` implement it. 1281impl<L, R> Error for Either<L, R> 1282where 1283 L: Error, 1284 R: Error, 1285{ 1286 fn source(&self) -> Option<&(dyn Error + 'static)> { 1287 for_both!(*self, ref inner => inner.source()) 1288 } 1289 1290 #[allow(deprecated)] 1291 fn description(&self) -> &str { 1292 for_both!(*self, ref inner => inner.description()) 1293 } 1294 1295 #[allow(deprecated)] 1296 fn cause(&self) -> Option<&dyn Error> { 1297 for_both!(*self, ref inner => inner.cause()) 1298 } 1299} 1300 1301impl<L, R> fmt::Display for Either<L, R> 1302where 1303 L: fmt::Display, 1304 R: fmt::Display, 1305{ 1306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1307 for_both!(*self, ref inner => inner.fmt(f)) 1308 } 1309} 1310 1311#[test] 1312fn basic() { 1313 let mut e = Left(2); 1314 let r = Right(2); 1315 assert_eq!(e, Left(2)); 1316 e = r; 1317 assert_eq!(e, Right(2)); 1318 assert_eq!(e.left(), None); 1319 assert_eq!(e.right(), Some(2)); 1320 assert_eq!(e.as_ref().right(), Some(&2)); 1321 assert_eq!(e.as_mut().right(), Some(&mut 2)); 1322} 1323 1324#[test] 1325fn macros() { 1326 use std::string::String; 1327 1328 fn a() -> Either<u32, u32> { 1329 let x: u32 = try_left!(Right(1337u32)); 1330 Left(x * 2) 1331 } 1332 assert_eq!(a(), Right(1337)); 1333 1334 fn b() -> Either<String, &'static str> { 1335 Right(try_right!(Left("foo bar"))) 1336 } 1337 assert_eq!(b(), Left(String::from("foo bar"))); 1338} 1339 1340#[test] 1341fn deref() { 1342 use std::string::String; 1343 1344 fn is_str(_: &str) {} 1345 let value: Either<String, &str> = Left(String::from("test")); 1346 is_str(&*value); 1347} 1348 1349#[test] 1350fn iter() { 1351 let x = 3; 1352 let mut iter = match x { 1353 3 => Left(0..10), 1354 _ => Right(17..), 1355 }; 1356 1357 assert_eq!(iter.next(), Some(0)); 1358 assert_eq!(iter.count(), 9); 1359} 1360 1361#[test] 1362fn seek() { 1363 use std::io; 1364 1365 let use_empty = false; 1366 let mut mockdata = [0x00; 256]; 1367 for i in 0..256 { 1368 mockdata[i] = i as u8; 1369 } 1370 1371 let mut reader = if use_empty { 1372 // Empty didn't impl Seek until Rust 1.51 1373 Left(io::Cursor::new([])) 1374 } else { 1375 Right(io::Cursor::new(&mockdata[..])) 1376 }; 1377 1378 let mut buf = [0u8; 16]; 1379 assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1380 assert_eq!(buf, mockdata[..buf.len()]); 1381 1382 // the first read should advance the cursor and return the next 16 bytes thus the `ne` 1383 assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1384 assert_ne!(buf, mockdata[..buf.len()]); 1385 1386 // if the seek operation fails it should read 16..31 instead of 0..15 1387 reader.seek(io::SeekFrom::Start(0)).unwrap(); 1388 assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1389 assert_eq!(buf, mockdata[..buf.len()]); 1390} 1391 1392#[test] 1393fn read_write() { 1394 use std::io; 1395 1396 let use_stdio = false; 1397 let mockdata = [0xff; 256]; 1398 1399 let mut reader = if use_stdio { 1400 Left(io::stdin()) 1401 } else { 1402 Right(&mockdata[..]) 1403 }; 1404 1405 let mut buf = [0u8; 16]; 1406 assert_eq!(reader.read(&mut buf).unwrap(), buf.len()); 1407 assert_eq!(&buf, &mockdata[..buf.len()]); 1408 1409 let mut mockbuf = [0u8; 256]; 1410 let mut writer = if use_stdio { 1411 Left(io::stdout()) 1412 } else { 1413 Right(&mut mockbuf[..]) 1414 }; 1415 1416 let buf = [1u8; 16]; 1417 assert_eq!(writer.write(&buf).unwrap(), buf.len()); 1418} 1419 1420#[test] 1421#[allow(deprecated)] 1422fn error() { 1423 let invalid_utf8 = b"\xff"; 1424 let res = if let Err(error) = ::std::str::from_utf8(invalid_utf8) { 1425 Err(Left(error)) 1426 } else if let Err(error) = "x".parse::<i32>() { 1427 Err(Right(error)) 1428 } else { 1429 Ok(()) 1430 }; 1431 assert!(res.is_err()); 1432 res.unwrap_err().description(); // make sure this can be called 1433} 1434 1435/// A helper macro to check if AsRef and AsMut are implemented for a given type. 1436macro_rules! check_t { 1437 ($t:ty) => {{ 1438 fn check_ref<T: AsRef<$t>>() {} 1439 fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>>() { 1440 check_ref::<Either<T1, T2>>() 1441 } 1442 fn check_mut<T: AsMut<$t>>() {} 1443 fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>>() { 1444 check_mut::<Either<T1, T2>>() 1445 } 1446 }}; 1447} 1448 1449// This "unused" method is here to ensure that compilation doesn't fail on given types. 1450fn _unsized_ref_propagation() { 1451 check_t!(str); 1452 1453 fn check_array_ref<T: AsRef<[Item]>, Item>() {} 1454 fn check_array_mut<T: AsMut<[Item]>, Item>() {} 1455 1456 fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, Item>() { 1457 check_array_ref::<Either<T1, T2>, _>() 1458 } 1459 1460 fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, Item>() { 1461 check_array_mut::<Either<T1, T2>, _>() 1462 } 1463} 1464 1465// This "unused" method is here to ensure that compilation doesn't fail on given types. 1466#[cfg(feature = "use_std")] 1467fn _unsized_std_propagation() { 1468 check_t!(::std::path::Path); 1469 check_t!(::std::ffi::OsStr); 1470 check_t!(::std::ffi::CStr); 1471} 1472