Coverage Report

Created: 2026-05-16 06:45

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