1//! The enum [`Either`] with variants `Left` and `Right` is a general purpose
2//! sum type with two cases.
3//!
4//! [`Either`]: enum.Either.html
5//!
6//! **Crate features:**
7//!
8//! * `"use_std"`
9//! Enabled by default. Disable to make the library `#![no_std]`.
10//!
11//! * `"serde"`
12//! Disabled by default. Enable to `#[derive(Serialize, Deserialize)]` for `Either`
13//!
14
15#![doc(html_root_url = "https://docs.rs/either/1/")]
16#![no_std]
17
18#[cfg(any(test, feature = "use_std"))]
19extern crate std;
20
21#[cfg(feature = "serde")]
22pub mod serde_untagged;
23
24#[cfg(feature = "serde")]
25pub mod serde_untagged_optional;
26
27use core::convert::{AsMut, AsRef};
28use core::fmt;
29use core::future::Future;
30use core::iter;
31use core::ops::Deref;
32use core::ops::DerefMut;
33use core::pin::Pin;
34
35#[cfg(any(test, feature = "use_std"))]
36use std::error::Error;
37#[cfg(any(test, feature = "use_std"))]
38use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
39
40pub use crate::Either::{Left, Right};
41
42/// The enum `Either` with variants `Left` and `Right` is a general purpose
43/// sum type with two cases.
44///
45/// The `Either` type is symmetric and treats its variants the same way, without
46/// preference.
47/// (For representing success or error, use the regular `Result` enum instead.)
48#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
49#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
50pub enum Either<L, R> {
51 /// A value of type `L`.
52 Left(L),
53 /// A value of type `R`.
54 Right(R),
55}
56
57/// Evaluate the provided expression for both [`Either::Left`] and [`Either::Right`].
58///
59/// This macro is useful in cases where both sides of [`Either`] can be interacted with
60/// in the same way even though the don't share the same type.
61///
62/// Syntax: `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)`
63///
64/// # Example
65///
66/// ```
67/// use either::Either;
68///
69/// fn length(owned_or_borrowed: Either<String, &'static str>) -> usize {
70/// either::for_both!(owned_or_borrowed, s => s.len())
71/// }
72///
73/// fn main() {
74/// let borrowed = Either::Right("Hello world!");
75/// let owned = Either::Left("Hello world!".to_owned());
76///
77/// assert_eq!(length(borrowed), 12);
78/// assert_eq!(length(owned), 12);
79/// }
80/// ```
81#[macro_export]
82macro_rules! for_both {
83 ($value:expr, $pattern:pat => $result:expr) => {
84 match $value {
85 $crate::Either::Left($pattern) => $result,
86 $crate::Either::Right($pattern) => $result,
87 }
88 };
89}
90
91/// Macro for unwrapping the left side of an `Either`, which fails early
92/// with the opposite side. Can only be used in functions that return
93/// `Either` because of the early return of `Right` that it provides.
94///
95/// See also `try_right!` for its dual, which applies the same just to the
96/// right side.
97///
98/// # Example
99///
100/// ```
101/// use either::{Either, Left, Right};
102///
103/// fn twice(wrapper: Either<u32, &str>) -> Either<u32, &str> {
104/// let value = either::try_left!(wrapper);
105/// Left(value * 2)
106/// }
107///
108/// fn main() {
109/// assert_eq!(twice(Left(2)), Left(4));
110/// assert_eq!(twice(Right("ups")), Right("ups"));
111/// }
112/// ```
113#[macro_export]
114macro_rules! try_left {
115 ($expr:expr) => {
116 match $expr {
117 $crate::Left(val) => val,
118 $crate::Right(err) => return $crate::Right(::core::convert::From::from(err)),
119 }
120 };
121}
122
123/// Dual to `try_left!`, see its documentation for more information.
124#[macro_export]
125macro_rules! try_right {
126 ($expr:expr) => {
127 match $expr {
128 $crate::Left(err) => return $crate::Left(::core::convert::From::from(err)),
129 $crate::Right(val) => val,
130 }
131 };
132}
133
134impl<L: Clone, R: Clone> Clone for Either<L, R> {
135 fn clone(&self) -> Self {
136 match self {
137 Left(inner) => Left(inner.clone()),
138 Right(inner) => Right(inner.clone()),
139 }
140 }
141
142 fn clone_from(&mut self, source: &Self) {
143 match (self, source) {
144 (Left(dest), Left(source)) => dest.clone_from(source),
145 (Right(dest), Right(source)) => dest.clone_from(source),
146 (dest, source) => *dest = source.clone(),
147 }
148 }
149}
150
151impl<L, R> Either<L, R> {
152 /// Return true if the value is the `Left` variant.
153 ///
154 /// ```
155 /// use either::*;
156 ///
157 /// let values = [Left(1), Right("the right value")];
158 /// assert_eq!(values[0].is_left(), true);
159 /// assert_eq!(values[1].is_left(), false);
160 /// ```
161 pub fn is_left(&self) -> bool {
162 match *self {
163 Left(_) => true,
164 Right(_) => false,
165 }
166 }
167
168 /// Return true if the value is the `Right` variant.
169 ///
170 /// ```
171 /// use either::*;
172 ///
173 /// let values = [Left(1), Right("the right value")];
174 /// assert_eq!(values[0].is_right(), false);
175 /// assert_eq!(values[1].is_right(), true);
176 /// ```
177 pub fn is_right(&self) -> bool {
178 !self.is_left()
179 }
180
181 /// Convert the left side of `Either<L, R>` to an `Option<L>`.
182 ///
183 /// ```
184 /// use either::*;
185 ///
186 /// let left: Either<_, ()> = Left("some value");
187 /// assert_eq!(left.left(), Some("some value"));
188 ///
189 /// let right: Either<(), _> = Right(321);
190 /// assert_eq!(right.left(), None);
191 /// ```
192 pub fn left(self) -> Option<L> {
193 match self {
194 Left(l) => Some(l),
195 Right(_) => None,
196 }
197 }
198
199 /// Convert the right side of `Either<L, R>` to an `Option<R>`.
200 ///
201 /// ```
202 /// use either::*;
203 ///
204 /// let left: Either<_, ()> = Left("some value");
205 /// assert_eq!(left.right(), None);
206 ///
207 /// let right: Either<(), _> = Right(321);
208 /// assert_eq!(right.right(), Some(321));
209 /// ```
210 pub fn right(self) -> Option<R> {
211 match self {
212 Left(_) => None,
213 Right(r) => Some(r),
214 }
215 }
216
217 /// Convert `&Either<L, R>` to `Either<&L, &R>`.
218 ///
219 /// ```
220 /// use either::*;
221 ///
222 /// let left: Either<_, ()> = Left("some value");
223 /// assert_eq!(left.as_ref(), Left(&"some value"));
224 ///
225 /// let right: Either<(), _> = Right("some value");
226 /// assert_eq!(right.as_ref(), Right(&"some value"));
227 /// ```
228 pub fn as_ref(&self) -> Either<&L, &R> {
229 match *self {
230 Left(ref inner) => Left(inner),
231 Right(ref inner) => Right(inner),
232 }
233 }
234
235 /// Convert `&mut Either<L, R>` to `Either<&mut L, &mut R>`.
236 ///
237 /// ```
238 /// use either::*;
239 ///
240 /// fn mutate_left(value: &mut Either<u32, u32>) {
241 /// if let Some(l) = value.as_mut().left() {
242 /// *l = 999;
243 /// }
244 /// }
245 ///
246 /// let mut left = Left(123);
247 /// let mut right = Right(123);
248 /// mutate_left(&mut left);
249 /// mutate_left(&mut right);
250 /// assert_eq!(left, Left(999));
251 /// assert_eq!(right, Right(123));
252 /// ```
253 pub fn as_mut(&mut self) -> Either<&mut L, &mut R> {
254 match *self {
255 Left(ref mut inner) => Left(inner),
256 Right(ref mut inner) => Right(inner),
257 }
258 }
259
260 /// Convert `Pin<&Either<L, R>>` to `Either<Pin<&L>, Pin<&R>>`,
261 /// pinned projections of the inner variants.
262 pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>> {
263 // SAFETY: We can use `new_unchecked` because the `inner` parts are
264 // guaranteed to be pinned, as they come from `self` which is pinned.
265 unsafe {
266 match *Pin::get_ref(self) {
267 Left(ref inner) => Left(Pin::new_unchecked(inner)),
268 Right(ref inner) => Right(Pin::new_unchecked(inner)),
269 }
270 }
271 }
272
273 /// Convert `Pin<&mut Either<L, R>>` to `Either<Pin<&mut L>, Pin<&mut R>>`,
274 /// pinned projections of the inner variants.
275 pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>> {
276 // SAFETY: `get_unchecked_mut` is fine because we don't move anything.
277 // We can use `new_unchecked` because the `inner` parts are guaranteed
278 // to be pinned, as they come from `self` which is pinned, and we never
279 // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We
280 // also don't have an implementation of `Drop`, nor manual `Unpin`.
281 unsafe {
282 match *Pin::get_unchecked_mut(self) {
283 Left(ref mut inner) => Left(Pin::new_unchecked(inner)),
284 Right(ref mut inner) => Right(Pin::new_unchecked(inner)),
285 }
286 }
287 }
288
289 /// Convert `Either<L, R>` to `Either<R, L>`.
290 ///
291 /// ```
292 /// use either::*;
293 ///
294 /// let left: Either<_, ()> = Left(123);
295 /// assert_eq!(left.flip(), Right(123));
296 ///
297 /// let right: Either<(), _> = Right("some value");
298 /// assert_eq!(right.flip(), Left("some value"));
299 /// ```
300 pub fn flip(self) -> Either<R, L> {
301 match self {
302 Left(l) => Right(l),
303 Right(r) => Left(r),
304 }
305 }
306
307 /// Apply the function `f` on the value in the `Left` variant if it is present rewrapping the
308 /// result in `Left`.
309 ///
310 /// ```
311 /// use either::*;
312 ///
313 /// let left: Either<_, u32> = Left(123);
314 /// assert_eq!(left.map_left(|x| x * 2), Left(246));
315 ///
316 /// let right: Either<u32, _> = Right(123);
317 /// assert_eq!(right.map_left(|x| x * 2), Right(123));
318 /// ```
319 pub fn map_left<F, M>(self, f: F) -> Either<M, R>
320 where
321 F: FnOnce(L) -> M,
322 {
323 match self {
324 Left(l) => Left(f(l)),
325 Right(r) => Right(r),
326 }
327 }
328
329 /// Apply the function `f` on the value in the `Right` variant if it is present rewrapping the
330 /// result in `Right`.
331 ///
332 /// ```
333 /// use either::*;
334 ///
335 /// let left: Either<_, u32> = Left(123);
336 /// assert_eq!(left.map_right(|x| x * 2), Left(123));
337 ///
338 /// let right: Either<u32, _> = Right(123);
339 /// assert_eq!(right.map_right(|x| x * 2), Right(246));
340 /// ```
341 pub fn map_right<F, S>(self, f: F) -> Either<L, S>
342 where
343 F: FnOnce(R) -> S,
344 {
345 match self {
346 Left(l) => Left(l),
347 Right(r) => Right(f(r)),
348 }
349 }
350
351 /// Apply 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 pub fn map_either<F, G, M, S>(self, f: F, g: G) -> Either<M, S>
369 where
370 F: FnOnce(L) -> M,
371 G: FnOnce(R) -> S,
372 {
373 match self {
374 Left(l) => Left(f(l)),
375 Right(r) => Right(g(r)),
376 }
377 }
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 pub fn map_either_with<Ctx, F, G, M, S>(self, ctx: Ctx, f: F, g: G) -> Either<M, S>
400 where
401 F: FnOnce(Ctx, L) -> M,
402 G: FnOnce(Ctx, R) -> S,
403 {
404 match self {
405 Left(l) => Left(f(ctx, l)),
406 Right(r) => Right(g(ctx, r)),
407 }
408 }
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 pub fn either<F, G, T>(self, f: F, g: G) -> T
427 where
428 F: FnOnce(L) -> T,
429 G: FnOnce(R) -> T,
430 {
431 match self {
432 Left(l) => f(l),
433 Right(r) => g(r),
434 }
435 }
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 pub fn either_with<Ctx, F, G, T>(self, ctx: Ctx, f: F, g: G) -> T
457 where
458 F: FnOnce(Ctx, L) -> T,
459 G: FnOnce(Ctx, R) -> T,
460 {
461 match self {
462 Left(l) => f(ctx, l),
463 Right(r) => g(ctx, r),
464 }
465 }
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 pub fn left_and_then<F, S>(self, f: F) -> Either<S, R>
479 where
480 F: FnOnce(L) -> Either<S, R>,
481 {
482 match self {
483 Left(l) => f(l),
484 Right(r) => Right(r),
485 }
486 }
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 pub fn right_and_then<F, S>(self, f: F) -> Either<L, S>
500 where
501 F: FnOnce(R) -> Either<L, S>,
502 {
503 match self {
504 Left(l) => Left(l),
505 Right(r) => f(r),
506 }
507 }
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 pub fn into_iter(self) -> Either<L::IntoIter, R::IntoIter>
521 where
522 L: IntoIterator,
523 R: IntoIterator<Item = L::Item>,
524 {
525 match self {
526 Left(l) => Left(l.into_iter()),
527 Right(r) => Right(r.into_iter()),
528 }
529 }
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 pub fn left_or(self, other: L) -> L {
550 match self {
551 Either::Left(l) => l,
552 Either::Right(_) => other,
553 }
554 }
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 pub fn left_or_default(self) -> L
569 where
570 L: Default,
571 {
572 match self {
573 Either::Left(l) => l,
574 Either::Right(_) => L::default(),
575 }
576 }
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 pub fn left_or_else<F>(self, f: F) -> L
591 where
592 F: FnOnce(R) -> L,
593 {
594 match self {
595 Either::Left(l) => l,
596 Either::Right(r) => f(r),
597 }
598 }
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 pub fn right_or(self, other: R) -> R {
619 match self {
620 Either::Left(_) => other,
621 Either::Right(r) => r,
622 }
623 }
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 pub fn right_or_default(self) -> R
638 where
639 R: Default,
640 {
641 match self {
642 Either::Left(_) => R::default(),
643 Either::Right(r) => r,
644 }
645 }
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 pub fn right_or_else<F>(self, f: F) -> R
660 where
661 F: FnOnce(L) -> R,
662 {
663 match self {
664 Either::Left(l) => f(l),
665 Either::Right(r) => r,
666 }
667 }
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 pub fn unwrap_left(self) -> L
689 where
690 R: core::fmt::Debug,
691 {
692 match self {
693 Either::Left(l) => l,
694 Either::Right(r) => {
695 panic!("called `Either::unwrap_left()` on a `Right` value: {:?}", r)
696 }
697 }
698 }
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 pub fn unwrap_right(self) -> R
720 where
721 L: core::fmt::Debug,
722 {
723 match self {
724 Either::Right(r) => r,
725 Either::Left(l) => panic!("called `Either::unwrap_right()` on a `Left` value: {:?}", l),
726 }
727 }
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 pub fn expect_left(self, msg: &str) -> L
749 where
750 R: core::fmt::Debug,
751 {
752 match self {
753 Either::Left(l) => l,
754 Either::Right(r) => panic!("{}: {:?}", msg, r),
755 }
756 }
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 pub fn expect_right(self, msg: &str) -> R
778 where
779 L: core::fmt::Debug,
780 {
781 match self {
782 Either::Right(r) => r,
783 Either::Left(l) => panic!("{}: {:?}", msg, l),
784 }
785 }
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 pub fn either_into<T>(self) -> T
800 where
801 L: Into<T>,
802 R: Into<T>,
803 {
804 match self {
805 Either::Left(l) => l.into(),
806 Either::Right(r) => r.into(),
807 }
808 }
809}
810
811impl<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 pub fn factor_none(self) -> Option<Either<L, R>> {
825 match self {
826 Left(l) => l.map(Either::Left),
827 Right(r) => r.map(Either::Right),
828 }
829 }
830}
831
832impl<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 pub fn factor_err(self) -> Result<Either<L, R>, E> {
848 match self {
849 Left(l) => l.map(Either::Left),
850 Right(r) => r.map(Either::Right),
851 }
852 }
853}
854
855impl<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 pub fn factor_ok(self) -> Result<T, Either<L, R>> {
871 match self {
872 Left(l) => l.map_err(Either::Left),
873 Right(r) => r.map_err(Either::Right),
874 }
875 }
876}
877
878impl<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 pub fn factor_first(self) -> (T, Either<L, R>) {
892 match self {
893 Left((t, l)) => (t, Left(l)),
894 Right((t, r)) => (t, Right(r)),
895 }
896 }
897}
898
899impl<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 pub fn factor_second(self) -> (Either<L, R>, T) {
913 match self {
914 Left((l, t)) => (Left(l), t),
915 Right((r, t)) => (Right(r), t),
916 }
917 }
918}
919
920impl<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 pub fn into_inner(self) -> T {
933 for_both!(self, inner => inner)
934 }
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 pub fn map<F, M>(self, f: F) -> Either<M, M>
948 where
949 F: FnOnce(T) -> M,
950 {
951 match self {
952 Left(l) => Left(f(l)),
953 Right(r) => Right(f(r)),
954 }
955 }
956}
957
958/// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`.
959impl<L, R> From<Result<R, L>> for Either<L, R> {
960 fn from(r: Result<R, L>) -> Self {
961 match r {
962 Err(e) => Left(e),
963 Ok(o) => Right(o),
964 }
965 }
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
970impl<L, R> Into<Result<R, L>> for Either<L, R> {
971 fn into(self) -> Result<R, L> {
972 match self {
973 Left(l) => Err(l),
974 Right(r) => Ok(r),
975 }
976 }
977}
978
979impl<L, R, A> Extend<A> for Either<L, R>
980where
981 L: Extend<A>,
982 R: Extend<A>,
983{
984 fn extend<T>(&mut self, iter: T)
985 where
986 T: IntoIterator<Item = A>,
987 {
988 for_both!(*self, ref mut inner => inner.extend(iter))
989 }
990}
991
992/// `Either<L, R>` is an iterator if both `L` and `R` are iterators.
993impl<L, R> Iterator for Either<L, R>
994where
995 L: Iterator,
996 R: Iterator<Item = L::Item>,
997{
998 type Item = L::Item;
999
1000 fn next(&mut self) -> Option<Self::Item> {
1001 for_both!(*self, ref mut inner => inner.next())
1002 }
1003
1004 fn size_hint(&self) -> (usize, Option<usize>) {
1005 for_both!(*self, ref inner => inner.size_hint())
1006 }
1007
1008 fn fold<Acc, G>(self, init: Acc, f: G) -> Acc
1009 where
1010 G: FnMut(Acc, Self::Item) -> Acc,
1011 {
1012 for_both!(self, inner => inner.fold(init, f))
1013 }
1014
1015 fn for_each<F>(self, f: F)
1016 where
1017 F: FnMut(Self::Item),
1018 {
1019 for_both!(self, inner => inner.for_each(f))
1020 }
1021
1022 fn count(self) -> usize {
1023 for_both!(self, inner => inner.count())
1024 }
1025
1026 fn last(self) -> Option<Self::Item> {
1027 for_both!(self, inner => inner.last())
1028 }
1029
1030 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1031 for_both!(*self, ref mut inner => inner.nth(n))
1032 }
1033
1034 fn collect<B>(self) -> B
1035 where
1036 B: iter::FromIterator<Self::Item>,
1037 {
1038 for_both!(self, inner => inner.collect())
1039 }
1040
1041 fn partition<B, F>(self, f: F) -> (B, B)
1042 where
1043 B: Default + Extend<Self::Item>,
1044 F: FnMut(&Self::Item) -> bool,
1045 {
1046 for_both!(self, inner => inner.partition(f))
1047 }
1048
1049 fn all<F>(&mut self, f: F) -> bool
1050 where
1051 F: FnMut(Self::Item) -> bool,
1052 {
1053 for_both!(*self, ref mut inner => inner.all(f))
1054 }
1055
1056 fn any<F>(&mut self, f: F) -> bool
1057 where
1058 F: FnMut(Self::Item) -> bool,
1059 {
1060 for_both!(*self, ref mut inner => inner.any(f))
1061 }
1062
1063 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
1064 where
1065 P: FnMut(&Self::Item) -> bool,
1066 {
1067 for_both!(*self, ref mut inner => inner.find(predicate))
1068 }
1069
1070 fn find_map<B, F>(&mut self, f: F) -> Option<B>
1071 where
1072 F: FnMut(Self::Item) -> Option<B>,
1073 {
1074 for_both!(*self, ref mut inner => inner.find_map(f))
1075 }
1076
1077 fn position<P>(&mut self, predicate: P) -> Option<usize>
1078 where
1079 P: FnMut(Self::Item) -> bool,
1080 {
1081 for_both!(*self, ref mut inner => inner.position(predicate))
1082 }
1083}
1084
1085impl<L, R> DoubleEndedIterator for Either<L, R>
1086where
1087 L: DoubleEndedIterator,
1088 R: DoubleEndedIterator<Item = L::Item>,
1089{
1090 fn next_back(&mut self) -> Option<Self::Item> {
1091 for_both!(*self, ref mut inner => inner.next_back())
1092 }
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 fn rfold<Acc, G>(self, init: Acc, f: G) -> Acc
1100 where
1101 G: FnMut(Acc, Self::Item) -> Acc,
1102 {
1103 for_both!(self, inner => inner.rfold(init, f))
1104 }
1105
1106 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
1107 where
1108 P: FnMut(&Self::Item) -> bool,
1109 {
1110 for_both!(*self, ref mut inner => inner.rfind(predicate))
1111 }
1112}
1113
1114impl<L, R> ExactSizeIterator for Either<L, R>
1115where
1116 L: ExactSizeIterator,
1117 R: ExactSizeIterator<Item = L::Item>,
1118{
1119 fn len(&self) -> usize {
1120 for_both!(*self, ref inner => inner.len())
1121 }
1122}
1123
1124impl<L, R> iter::FusedIterator for Either<L, R>
1125where
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.
1132impl<L, R> Future for Either<L, R>
1133where
1134 L: Future,
1135 R: Future<Output = L::Output>,
1136{
1137 type Output = L::Output;
1138
1139 fn poll(
1140 self: Pin<&mut Self>,
1141 cx: &mut core::task::Context<'_>,
1142 ) -> core::task::Poll<Self::Output> {
1143 for_both!(self.as_pin_mut(), inner => inner.poll(cx))
1144 }
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"`
1151impl<L, R> Read for Either<L, R>
1152where
1153 L: Read,
1154 R: Read,
1155{
1156 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1157 for_both!(*self, ref mut inner => inner.read(buf))
1158 }
1159
1160 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
1161 for_both!(*self, ref mut inner => inner.read_exact(buf))
1162 }
1163
1164 fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
1165 for_both!(*self, ref mut inner => inner.read_to_end(buf))
1166 }
1167
1168 fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
1169 for_both!(*self, ref mut inner => inner.read_to_string(buf))
1170 }
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"`
1177impl<L, R> Seek for Either<L, R>
1178where
1179 L: Seek,
1180 R: Seek,
1181{
1182 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1183 for_both!(*self, ref mut inner => inner.seek(pos))
1184 }
1185}
1186
1187#[cfg(any(test, feature = "use_std"))]
1188/// Requires crate feature `"use_std"`
1189impl<L, R> BufRead for Either<L, R>
1190where
1191 L: BufRead,
1192 R: BufRead,
1193{
1194 fn fill_buf(&mut self) -> io::Result<&[u8]> {
1195 for_both!(*self, ref mut inner => inner.fill_buf())
1196 }
1197
1198 fn consume(&mut self, amt: usize) {
1199 for_both!(*self, ref mut inner => inner.consume(amt))
1200 }
1201
1202 fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> io::Result<usize> {
1203 for_both!(*self, ref mut inner => inner.read_until(byte, buf))
1204 }
1205
1206 fn read_line(&mut self, buf: &mut std::string::String) -> io::Result<usize> {
1207 for_both!(*self, ref mut inner => inner.read_line(buf))
1208 }
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"`
1215impl<L, R> Write for Either<L, R>
1216where
1217 L: Write,
1218 R: Write,
1219{
1220 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1221 for_both!(*self, ref mut inner => inner.write(buf))
1222 }
1223
1224 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1225 for_both!(*self, ref mut inner => inner.write_all(buf))
1226 }
1227
1228 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
1229 for_both!(*self, ref mut inner => inner.write_fmt(fmt))
1230 }
1231
1232 fn flush(&mut self) -> io::Result<()> {
1233 for_both!(*self, ref mut inner => inner.flush())
1234 }
1235}
1236
1237impl<L, R, Target> AsRef<Target> for Either<L, R>
1238where
1239 L: AsRef<Target>,
1240 R: AsRef<Target>,
1241{
1242 fn as_ref(&self) -> &Target {
1243 for_both!(*self, ref inner => inner.as_ref())
1244 }
1245}
1246
1247macro_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 fn as_ref(&self) -> &$t {
1254 for_both!(*self, ref inner => inner.as_ref())
1255 }
1256 }
1257
1258 $(#[$attr])*
1259 impl<L, R> AsMut<$t> for Either<L, R>
1260 where L: AsMut<$t>, R: AsMut<$t>
1261 {
1262 fn as_mut(&mut self) -> &mut $t {
1263 for_both!(*self, ref mut inner => inner.as_mut())
1264 }
1265 }
1266 };
1267}
1268
1269impl_specific_ref_and_mut!(str,);
1270impl_specific_ref_and_mut!(
1271 ::std::path::Path,
1272 cfg(feature = "use_std"),
1273 doc = "Requires crate feature `use_std`."
1274);
1275impl_specific_ref_and_mut!(
1276 ::std::ffi::OsStr,
1277 cfg(feature = "use_std"),
1278 doc = "Requires crate feature `use_std`."
1279);
1280impl_specific_ref_and_mut!(
1281 ::std::ffi::CStr,
1282 cfg(feature = "use_std"),
1283 doc = "Requires crate feature `use_std`."
1284);
1285
1286impl<L, R, Target> AsRef<[Target]> for Either<L, R>
1287where
1288 L: AsRef<[Target]>,
1289 R: AsRef<[Target]>,
1290{
1291 fn as_ref(&self) -> &[Target] {
1292 for_both!(*self, ref inner => inner.as_ref())
1293 }
1294}
1295
1296impl<L, R, Target> AsMut<Target> for Either<L, R>
1297where
1298 L: AsMut<Target>,
1299 R: AsMut<Target>,
1300{
1301 fn as_mut(&mut self) -> &mut Target {
1302 for_both!(*self, ref mut inner => inner.as_mut())
1303 }
1304}
1305
1306impl<L, R, Target> AsMut<[Target]> for Either<L, R>
1307where
1308 L: AsMut<[Target]>,
1309 R: AsMut<[Target]>,
1310{
1311 fn as_mut(&mut self) -> &mut [Target] {
1312 for_both!(*self, ref mut inner => inner.as_mut())
1313 }
1314}
1315
1316impl<L, R> Deref for Either<L, R>
1317where
1318 L: Deref,
1319 R: Deref<Target = L::Target>,
1320{
1321 type Target = L::Target;
1322
1323 fn deref(&self) -> &Self::Target {
1324 for_both!(*self, ref inner => &**inner)
1325 }
1326}
1327
1328impl<L, R> DerefMut for Either<L, R>
1329where
1330 L: DerefMut,
1331 R: DerefMut<Target = L::Target>,
1332{
1333 fn deref_mut(&mut self) -> &mut Self::Target {
1334 for_both!(*self, ref mut inner => &mut *inner)
1335 }
1336}
1337
1338#[cfg(any(test, feature = "use_std"))]
1339/// `Either` implements `Error` if *both* `L` and `R` implement it.
1340impl<L, R> Error for Either<L, R>
1341where
1342 L: Error,
1343 R: Error,
1344{
1345 fn source(&self) -> Option<&(dyn Error + 'static)> {
1346 for_both!(*self, ref inner => inner.source())
1347 }
1348
1349 #[allow(deprecated)]
1350 fn description(&self) -> &str {
1351 for_both!(*self, ref inner => inner.description())
1352 }
1353
1354 #[allow(deprecated)]
1355 fn cause(&self) -> Option<&dyn Error> {
1356 for_both!(*self, ref inner => inner.cause())
1357 }
1358}
1359
1360impl<L, R> fmt::Display for Either<L, R>
1361where
1362 L: fmt::Display,
1363 R: fmt::Display,
1364{
1365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1366 for_both!(*self, ref inner => inner.fmt(f))
1367 }
1368}
1369
1370#[test]
1371fn 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]
1384fn 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]
1400fn 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]
1409fn 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]
1421fn 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]
1452fn 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)]
1481fn 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.
1495macro_rules! check_t {
1496 ($t:ty) => {{
1497 fn check_ref<T: AsRef<$t>>() {}
1498 fn propagate_ref<T1: AsRef<$t>, T2: AsRef<$t>>() {
1499 check_ref::<Either<T1, T2>>()
1500 }
1501 fn check_mut<T: AsMut<$t>>() {}
1502 fn propagate_mut<T1: AsMut<$t>, T2: AsMut<$t>>() {
1503 check_mut::<Either<T1, T2>>()
1504 }
1505 }};
1506}
1507
1508// This "unused" method is here to ensure that compilation doesn't fail on given types.
1509fn _unsized_ref_propagation() {
1510 check_t!(str);
1511
1512 fn check_array_ref<T: AsRef<[Item]>, Item>() {}
1513 fn check_array_mut<T: AsMut<[Item]>, Item>() {}
1514
1515 fn propagate_array_ref<T1: AsRef<[Item]>, T2: AsRef<[Item]>, Item>() {
1516 check_array_ref::<Either<T1, T2>, _>()
1517 }
1518
1519 fn propagate_array_mut<T1: AsMut<[Item]>, T2: AsMut<[Item]>, Item>() {
1520 check_array_mut::<Either<T1, T2>, _>()
1521 }
1522}
1523
1524// This "unused" method is here to ensure that compilation doesn't fail on given types.
1525#[cfg(feature = "use_std")]
1526fn _unsized_std_propagation() {
1527 check_t!(::std::path::Path);
1528 check_t!(::std::ffi::OsStr);
1529 check_t!(::std::ffi::CStr);
1530}
1531