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