either_or_both/either/mod.rs
1//! The `Either` enum
2
3macro_rules! map_each {
4 ($src:expr) => {
5 match $src {
6 Self::Left(left) => Left(left),
7 Self::Right(left) => Right(left),
8 }
9 };
10}
11
12macro_rules! each {
13 ($src:expr, $( $rest:tt )*) => {
14 match $src {
15 Self::Left(left) => left $($rest)*,
16 Self::Right(right) => right $($rest)*,
17 }
18 };
19 ($src:expr) => {
20 match $src {
21 Self::Left(left) => left,
22 Self::Right(right) => right,
23 }
24 };
25}
26
27pub mod iter;
28pub mod traits;
29
30use core::mem;
31use core::ops::{Deref, DerefMut};
32use core::pin::Pin;
33
34use iter::{InnerIterEither, SwapIterEither};
35use Either::*;
36
37use crate::iter_either::{IterEither, IterMutEither};
38use crate::EitherOrBoth;
39
40/// Represent values with two possibilities. `Either` can be either `Left` or `Right`
41#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43#[cfg_attr(feature = "serde", allow(clippy::unsafe_derive_deserialize))]
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45pub enum Either<L, R = L> {
46 /// Represent a left value
47 Left(L),
48 /// Represent a right value
49 Right(R),
50}
51
52impl<L, R> Either<L, R> {
53 ////////////////////////////////////////////////////////////////////////////////
54 // Boolish
55 ////////////////////////////////////////////////////////////////////////////////
56
57 /// Returns `true` if `Either` is a [`Left`] value.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use either_or_both::Either;
63 ///
64 /// let either = Either::<u8>::Left(1);
65 /// assert_eq!(either.is_left(), true);
66 ///
67 /// let either = Either::<u8>::Right(1);
68 /// assert_eq!(either.is_left(), false);
69 /// ```
70 #[must_use = "if you intended to assert that this is a left value, consider `.unwrap_left()` \
71 instead"]
72 #[inline]
73 pub const fn is_left(&self) -> bool {
74 matches!(self, Self::Left(_))
75 }
76
77 /// Returns `true` if `Either` is [`Left`] and the contained value matches a predicate
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// use either_or_both::Either;
83 ///
84 /// let either: Either<u8> = Either::Left(1);
85 /// assert_eq!(either.is_left_and(|l| l == 1), true);
86 ///
87 /// let either: Either<u8> = Either::Left(1);
88 /// assert_eq!(either.is_left_and(|l| l == 2), false);
89 ///
90 /// let either: Either<u8> = Either::Right(1);
91 /// assert_eq!(either.is_left_and(|l| l == 1), false);
92 /// ```
93 #[must_use]
94 #[inline]
95 pub fn is_left_and<F>(self, f: F) -> bool
96 where
97 F: FnOnce(L) -> bool,
98 {
99 match self {
100 Self::Left(left) => f(left),
101 Self::Right(_) => false,
102 }
103 }
104 /// Returns `true` if `Either` is [`Left`] or the [`Right`] value matches a predicate
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// use either_or_both::Either;
110 ///
111 /// let either: Either<u8, char> = Either::Left(1);
112 /// assert_eq!(either.is_left_or(|r| r == 'c'), true);
113 ///
114 /// let either: Either<u8, char> = Either::Right('c');
115 /// assert_eq!(either.is_left_or(|r| r == 'c'), true);
116 ///
117 /// let either: Either<u8, char> = Either::Right('c');
118 /// assert_eq!(either.is_left_or(|r| r == 'm'), false);
119 /// ```
120 #[must_use]
121 #[inline]
122 pub fn is_left_or<F>(self, f: F) -> bool
123 where
124 F: FnOnce(R) -> bool,
125 {
126 match self {
127 Self::Left(_) => true,
128 Self::Right(right) => f(right),
129 }
130 }
131
132 /// Returns `true` if `Either` is a [`Right`] value.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use either_or_both::Either;
138 ///
139 /// let either = Either::<u8, char>::Right('c');
140 /// assert_eq!(either.is_right(), true);
141 ///
142 /// let either = Either::<u8, char>::Left(1);
143 /// assert_eq!(either.is_right(), false);
144 /// ```
145 #[must_use = "if you intended to assert that this is a right value, consider `.unwrap_right()` \
146 instead"]
147 #[inline]
148 pub const fn is_right(&self) -> bool {
149 matches!(self, Self::Right(_))
150 }
151
152 /// Returns `true` if `Either` is [`Right`] and the contained value matches a
153 /// predicate
154 ///
155 /// # Examples
156 ///
157 /// ```
158 /// use either_or_both::Either;
159 ///
160 /// let either: Either<u8, char> = Either::Right('c');
161 /// assert_eq!(either.is_right_and(|r| r == 'c'), true);
162 ///
163 /// let either: Either<u8, char> = Either::Right('c');
164 /// assert_eq!(either.is_right_and(|r| r == 'm'), false);
165 ///
166 /// let either: Either<u8, char> = Either::Left(1);
167 /// assert_eq!(either.is_right_and(|r| r == 'c'), false);
168 /// ```
169 #[must_use]
170 #[inline]
171 pub fn is_right_and<F>(self, f: F) -> bool
172 where
173 F: FnOnce(R) -> bool,
174 {
175 match self {
176 Self::Right(right) => f(right),
177 Self::Left(_) => false,
178 }
179 }
180
181 /// Returns `true` if `Either` is [`Right`] or the [`Left`] value matches a predicate
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use either_or_both::Either;
187 ///
188 /// let either: Either<u8, char> = Either::Right('c');
189 /// assert_eq!(either.is_right_or(|l| l == 1), true);
190 ///
191 /// let either: Either<u8, char> = Either::Left(1);
192 /// assert_eq!(either.is_right_or(|l| l == 1), true);
193 ///
194 /// let either: Either<u8, char> = Either::Left(2);
195 /// assert_eq!(either.is_right_or(|l| l == 1), false);
196 /// ```
197 #[must_use]
198 #[inline]
199 pub fn is_right_or<F>(self, f: F) -> bool
200 where
201 F: FnOnce(L) -> bool,
202 {
203 match self {
204 Self::Right(_) => true,
205 Self::Left(left) => f(left),
206 }
207 }
208
209 ////////////////////////////////////////////////////////////////////////////////
210 // As reference conversions
211 ////////////////////////////////////////////////////////////////////////////////
212
213 /// Converts from `&Either<L, R>` to `Either<&L, &R>`.
214 ///
215 /// # Examples
216 ///
217 /// Calculate the length of the [strings] without moving the [`Strings`].
218 ///
219 /// [strings]: String
220 /// [`Strings`]: String
221 ///
222 /// ```
223 /// use either_or_both::Either;
224 ///
225 /// let text: Either<String> = Either::Left("left value".to_owned());
226 ///
227 /// // Cast `Either<String>` to `Either<&String>` and then apply a map consuming the
228 /// // result of `as_ref` instead of `text` itself
229 /// let length: Either<usize> = text.as_ref().map(String::len);
230 /// assert_eq!(length, Either::Left(10));
231 ///
232 /// println!("`text` has not been moved: {:?}", &text);
233 /// ```
234 #[allow(clippy::same_name_method)]
235 #[inline]
236 pub const fn as_ref(&self) -> Either<&L, &R> {
237 map_each!(self)
238 }
239
240 /// Converts from `&mut Either<L, R>` to `Either<&mut L, &mut R>`.
241 ///
242 /// # Examples
243 ///
244 /// ```
245 /// use either_or_both::Either;
246 ///
247 /// let mut either: Either<u8, char> = Either::Left(1);
248 ///
249 /// match either.as_mut() {
250 /// Either::Left(left) => *left = 3,
251 /// Either::Right(right) => *right = 'x',
252 /// }
253 ///
254 /// assert_eq!(either, Either::Left(3))
255 /// ```
256 #[allow(clippy::same_name_method)]
257 #[inline]
258 pub fn as_mut(&mut self) -> Either<&mut L, &mut R> {
259 map_each!(self)
260 }
261
262 /// Converts from `Either<L, R>` to `Either<&L::Target, &R::Target>`.
263 ///
264 /// This method keeps the original `Either` unchanged, while creating a new instance
265 /// that holds a reference to the original. It also coerces the inner values
266 /// through the `Deref` trait.
267 ///
268 /// ```
269 /// use either_or_both::Either;
270 ///
271 /// let values: Either<String> = Either::Left("left".to_owned());
272 /// let deref: Either<&str> = values.as_deref();
273 /// assert_eq!(deref.left(), Some("left"));
274 /// ```
275 #[inline]
276 pub fn as_deref(&self) -> Either<&<L as Deref>::Target, &<R as Deref>::Target>
277 where
278 L: Deref,
279 R: Deref,
280 {
281 self.as_ref().bimap(|l| &**l, |r| &**r)
282 }
283
284 /// Converts from `Either<L, R>` to `Either<&mut L::Target, &mut R::Target>`.
285 ///
286 /// This method keeps the original `Either` unchanged, while creating a new instance
287 /// that holds a mutable reference to the inner type's [`Deref::Target`] type.
288 ///
289 /// ```
290 /// use either_or_both::Either;
291 ///
292 /// let mut value: Either<String> = Either::Left("left".to_owned());
293 /// let upper_case: Either<&mut str> = value.as_deref_mut().map(|v| {
294 /// v.make_ascii_uppercase();
295 /// v
296 /// });
297 ///
298 /// assert_eq!(upper_case.left(), Some("LEFT".to_owned().as_mut_str()));
299 /// ```
300 #[inline]
301 pub fn as_deref_mut(&mut self) -> Either<&mut <L as Deref>::Target, &mut <R as Deref>::Target>
302 where
303 L: DerefMut,
304 R: DerefMut,
305 {
306 self.as_mut().bimap(|l| &mut **l, |r| &mut **r)
307 }
308
309 /// Converts from `Pin<&Either<L, R>>` to `Either<Pin<&L>, Pin<&R>>`.
310 #[must_use]
311 #[inline]
312 pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>> {
313 // SAFETY: `x` is guaranteed to be pinned because it comes from `self` which is pinned.
314 unsafe {
315 match Pin::get_ref(self) {
316 Self::Left(left) => Left(Pin::new_unchecked(left)),
317 Self::Right(right) => Right(Pin::new_unchecked(right)),
318 }
319 }
320 }
321
322 /// Converts from `Pin<&mut Either<L, R>>` to `Either<Pin<&mut L>, Pin<&mut R>>`.
323 #[must_use]
324 #[inline]
325 pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>> {
326 // SAFETY: `x` is guaranteed to be pinned because it comes from `self` which is pinned.
327 unsafe {
328 match Pin::get_unchecked_mut(self) {
329 Self::Left(left) => Left(Pin::new_unchecked(left)),
330 Self::Right(right) => Right(Pin::new_unchecked(right)),
331 }
332 }
333 }
334
335 ////////////////////////////////////////////////////////////////////////////////
336 // Unwrapping the contained values
337 ////////////////////////////////////////////////////////////////////////////////
338
339 /// Returns the contained left value consuming `self`.
340 ///
341 /// # Panics
342 ///
343 /// Panics with a custom panic message provided by `msg` if there is no left value
344 /// present
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// use either_or_both::Either;
350 ///
351 /// let value: Either<&str> = Either::Left("left");
352 /// assert_eq!(value.expect_left("should be left"), "left");
353 /// ```
354 ///
355 /// This example panics with the message `should be left`
356 ///
357 /// ```should_panic
358 /// use either_or_both::Either;
359 ///
360 /// let value: Either<&str> = Either::Right("right");
361 /// value.expect_left("should be left");
362 /// ```
363 #[track_caller]
364 #[inline]
365 pub fn expect_left(self, msg: &str) -> L {
366 match self {
367 Self::Left(left) => left,
368 Self::Right(_) => {
369 panic!("{msg}");
370 }
371 }
372 }
373
374 /// Returns the contained right value consuming `self`.
375 ///
376 /// # Panics
377 ///
378 /// Panics with a custom panic message provided by `msg` if there is no right value
379 /// present
380 ///
381 /// # Examples
382 ///
383 /// ```
384 /// use either_or_both::Either;
385 ///
386 /// let value: Either<&str> = Either::Right("right");
387 /// assert_eq!(value.expect_right("should be right"), "right");
388 /// ```
389 ///
390 /// The following example panics with the message `should be right`
391 ///
392 /// ```should_panic
393 /// use either_or_both::Either;
394 ///
395 /// let value: Either<&str> = Either::Left("left");
396 /// value.expect_right("should be right");
397 /// ```
398 #[track_caller]
399 #[inline]
400 pub fn expect_right(self, msg: &str) -> R {
401 match self {
402 Self::Left(_) => {
403 panic!("{msg}");
404 }
405 Self::Right(right) => right,
406 }
407 }
408
409 /// Returns the contained left value consuming `self`.
410 ///
411 /// # Panics
412 ///
413 /// Panics if `Either` is a [`Right`] variant
414 ///
415 /// # Examples
416 ///
417 /// ```
418 /// use either_or_both::Either;
419 ///
420 /// let value: Either<&str> = Either::Left("left");
421 /// assert_eq!(value.unwrap_left(), "left");
422 /// ```
423 ///
424 /// ```should_panic
425 /// use either_or_both::Either;
426 ///
427 /// let value: Either<&str> = Either::Right("right");
428 /// value.unwrap_left(); // panics
429 /// ```
430 #[track_caller]
431 #[inline]
432 pub fn unwrap_left(self) -> L {
433 self.expect_left("Called `Either::unwrap_left` on a `Right` value")
434 }
435
436 /// Returns the contained left value consuming `self`, without checking that the value
437 /// is not [`Left`].
438 ///
439 /// # SAFETY
440 ///
441 /// Calling this method on a [`Right`] variant is *[undefined behavior]*.
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// use either_or_both::Either;
447 ///
448 /// let value: Either<&str> = Either::Left("left");
449 /// assert_eq!(unsafe { value.unwrap_left_unchecked() }, "left");
450 /// ```
451 ///
452 /// The following example introduces *[undefined behavior]*
453 ///
454 /// ```no_run
455 /// use either_or_both::Either;
456 ///
457 /// let value: Either<&str> = Either::Right("right");
458 /// assert_eq!(unsafe { value.unwrap_left_unchecked() }, "left");
459 /// ```
460 ///
461 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
462 #[track_caller]
463 #[inline]
464 pub unsafe fn unwrap_left_unchecked(self) -> L {
465 match self {
466 Self::Left(left) => left,
467 // SAFETY: the safety contract must be upheld by the caller.
468 Self::Right(_) => core::hint::unreachable_unchecked(), // cov:excl-line
469 }
470 }
471
472 /// Returns the contained right value consuming `self`.
473 ///
474 /// # Panics
475 ///
476 /// Panics if `Either` is a [`Left`] variant
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use either_or_both::Either;
482 ///
483 /// let value: Either<&str> = Either::Right("right");
484 /// assert_eq!(value.unwrap_right(), "right");
485 /// ```
486 ///
487 /// ```should_panic
488 /// use either_or_both::Either;
489 ///
490 /// let value: Either<&str> = Either::Left("left");
491 /// value.unwrap_right(); // panics
492 /// ```
493 #[track_caller]
494 #[inline]
495 pub fn unwrap_right(self) -> R {
496 self.expect_right("Called `Either::unwrap_right` on a `Left` value")
497 }
498
499 /// Returns the contained right value consuming `self`, without checking that the
500 /// value is not [`Right`].
501 ///
502 /// # SAFETY
503 ///
504 /// Calling this method on a [`Left`] variant is *[undefined behavior]*.
505 ///
506 /// # Examples
507 ///
508 /// ```
509 /// use either_or_both::Either;
510 ///
511 /// let value: Either<&str> = Either::Right("right");
512 /// assert_eq!(unsafe { value.unwrap_right_unchecked() }, "right");
513 /// ```
514 ///
515 /// The following example introduces *[undefined behavior]*
516 ///
517 /// ```no_run
518 /// use either_or_both::Either;
519 ///
520 /// let value: Either<&str> = Either::Left("left");
521 /// assert_eq!(unsafe { value.unwrap_right_unchecked() }, "right");
522 /// ```
523 ///
524 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
525 #[track_caller]
526 #[inline]
527 pub unsafe fn unwrap_right_unchecked(self) -> R {
528 match self {
529 // SAFETY: the safety contract must be upheld by the caller.
530 Self::Left(_) => core::hint::unreachable_unchecked(), // cov:excl-line
531 Self::Right(right) => right,
532 }
533 }
534
535 ////////////////////////////////////////////////////////////////////////////////
536 // Getting the contained values
537 ////////////////////////////////////////////////////////////////////////////////
538
539 /// If a left value is present, return `Some` containing the value otherwise return
540 /// `None`.
541 ///
542 /// # Examples
543 ///
544 /// ```
545 /// use either_or_both::Either;
546 ///
547 /// let value: Either<u8, char> = Either::Left(1);
548 /// assert_eq!(value.left(), Some(1));
549 ///
550 /// let value: Either<u8, char> = Either::Right('c');
551 /// assert_eq!(value.left(), None);
552 /// ```
553 #[inline]
554 pub fn left(self) -> Option<L> {
555 match self {
556 Self::Left(left) => Some(left),
557 Self::Right(_) => None,
558 }
559 }
560
561 /// Returns [`Right`] if the `Either` is [`Right`] otherwise returns `other`.
562 ///
563 /// The `left_and` combinator eagerly evaluates its arguments, which can result in
564 /// unnecessary computations. When chaining operations that involve function
565 /// calls, use [`left_and_then`] instead. It evaluates the function lazily.
566 ///
567 /// # Examples
568 ///
569 /// ```
570 /// use either_or_both::Either;
571 ///
572 /// let x: Either<u8, char> = Either::Left(1);
573 /// let y: Either<&str, char> = Either::Left("left");
574 /// assert_eq!(x.left_and(y), Either::Left("left"));
575 ///
576 /// let x: Either<u8, char> = Either::Right('c');
577 /// let y: Either<&str, char> = Either::Left("left");
578 /// assert_eq!(x.left_and(y), Either::Right('c'));
579 /// ```
580 ///
581 /// [`left_and_then`]: Either::left_and_then
582 #[inline]
583 pub fn left_and<T>(self, other: Either<T, R>) -> Either<T, R> {
584 match self {
585 Self::Left(_) => other,
586 Self::Right(right) => Right(right),
587 }
588 }
589
590 /// Returns [`Right`] otherwise calls `f` with the left value and returns the result.
591 ///
592 /// # Examples
593 ///
594 /// ```
595 /// use either_or_both::Either;
596 ///
597 /// fn left_to_string(x: u8) -> Either<String, char> {
598 /// Either::Left(x.to_string())
599 /// }
600 ///
601 /// let x: Either<u8, char> = Either::Left(1);
602 /// assert_eq!(x.left_and_then(left_to_string), Either::Left(1.to_string()));
603 ///
604 /// let x: Either<u8, char> = Either::Right('c');
605 /// assert_eq!(x.left_and_then(left_to_string), Either::Right('c'));
606 /// ```
607 #[inline]
608 pub fn left_and_then<F, T>(self, f: F) -> Either<T, R>
609 where
610 F: FnOnce(L) -> Either<T, R>,
611 {
612 match self {
613 Self::Left(left) => f(left),
614 Self::Right(right) => Right(right),
615 }
616 }
617
618 /// If a left value is present, return `Some` containing the value otherwise return
619 /// `None`.
620 ///
621 /// # Examples
622 ///
623 /// ```
624 /// use either_or_both::Either;
625 ///
626 /// let value: Either<u8, char> = Either::Right('c');
627 /// assert_eq!(value.right(), Some('c'));
628 ///
629 /// let value: Either<u8, char> = Either::Left(1);
630 /// assert_eq!(value.right(), None);
631 /// ```
632 #[inline]
633 pub fn right(self) -> Option<R> {
634 match self {
635 Self::Left(_) => None,
636 Self::Right(right) => Some(right),
637 }
638 }
639
640 /// Returns [`Left`] if the `Either` is [`Left`] otherwise returns `other`.
641 ///
642 /// The `right_and` combinator eagerly evaluates its arguments, which can result in
643 /// unnecessary computations. When chaining operations that involve function
644 /// calls, use [`right_and_then`] instead. It evaluates the function lazily.
645 ///
646 /// # Examples
647 ///
648 /// ```
649 /// use either_or_both::Either;
650 ///
651 /// let x: Either<u8, char> = Either::Right('c');
652 /// let y: Either<u8, &str> = Either::Right("right");
653 /// assert_eq!(x.right_and(y), Either::Right("right"));
654 ///
655 /// let x: Either<u8, char> = Either::Left(1);
656 /// let y: Either<u8, &str> = Either::Right("right");
657 /// assert_eq!(x.right_and(y), Either::Left(1));
658 /// ```
659 ///
660 /// [`right_and_then`]: Either::right_and_then
661 #[inline]
662 pub fn right_and<T>(self, other: Either<L, T>) -> Either<L, T> {
663 match self {
664 Self::Left(left) => Left(left),
665 Self::Right(_) => other,
666 }
667 }
668
669 /// Returns [`Left`] otherwise calls `f` with the right value and returns the result.
670 ///
671 /// # Examples
672 ///
673 /// ```
674 /// use either_or_both::Either;
675 ///
676 /// fn right_to_string(x: char) -> Either<u8, String> {
677 /// Either::Right(x.to_string())
678 /// }
679 ///
680 /// let x: Either<u8, char> = Either::Right('c');
681 /// assert_eq!(
682 /// x.right_and_then(right_to_string),
683 /// Either::Right('c'.to_string())
684 /// );
685 ///
686 /// let x: Either<u8, char> = Either::Left(1);
687 /// assert_eq!(x.right_and_then(right_to_string), Either::Left(1));
688 /// ```
689 #[inline]
690 pub fn right_and_then<F, T>(self, f: F) -> Either<L, T>
691 where
692 F: FnOnce(R) -> Either<L, T>,
693 {
694 match self {
695 Self::Left(left) => Left(left),
696 Self::Right(right) => f(right),
697 }
698 }
699
700 ////////////////////////////////////////////////////////////////////////////////
701 // Iterators
702 ////////////////////////////////////////////////////////////////////////////////
703
704 /// Consumes the inner iterators and returns an iterator that yields items of type
705 /// `Either<L, R>`.
706 ///
707 ///
708 /// This iterator allows traversing inner iterators with different types
709 ///
710 /// # Examples
711 ///
712 /// ```
713 /// use either_or_both::Either;
714 ///
715 /// let x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
716 /// let mut iter = x.into_iter_swap(); // moves `x` and the iterators
717 ///
718 /// assert_eq!(iter.next(), Some(Either::Left(1)));
719 /// assert_eq!(iter.next(), Some(Either::Left(2)));
720 /// assert_eq!(iter.next(), None);
721 /// ```
722 pub fn into_iter_swap(
723 self,
724 ) -> SwapIterEither<<L as IntoIterator>::IntoIter, <R as IntoIterator>::IntoIter>
725 where
726 L: IntoIterator,
727 R: IntoIterator,
728 {
729 SwapIterEither::new(self.bimap(IntoIterator::into_iter, IntoIterator::into_iter))
730 }
731
732 /// Borrow the inner iterators and returns an iterator that yields items of type
733 /// `Either<&L, &R>`.
734 ///
735 /// This iterator allows traversing inner iterators with different types
736 ///
737 /// # Examples
738 ///
739 /// ```
740 /// use either_or_both::Either;
741 ///
742 /// let x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
743 /// let mut iter = x.iter_swap();
744 ///
745 /// assert_eq!(iter.next(), Some(Either::Left(&1)));
746 /// assert_eq!(iter.next(), Some(Either::Left(&2)));
747 /// assert_eq!(iter.next(), None);
748 ///
749 /// println!("{x:?}"); // still can access `x`
750 /// ```
751 pub fn iter_swap(
752 &self,
753 ) -> SwapIterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter>
754 where
755 for<'a> &'a L: IntoIterator,
756 for<'a> &'a R: IntoIterator,
757 {
758 SwapIterEither::new(
759 self.as_ref()
760 .bimap(IntoIterator::into_iter, IntoIterator::into_iter),
761 )
762 }
763
764 /// Mutably borrows the inner iterators returning an iterator that yields items of
765 /// type `Either<&mut L, &mut R>`.
766 ///
767 /// This iterator allows traversing inner iterators with different types
768 ///
769 /// # Examples
770 ///
771 /// ```
772 /// use either_or_both::Either;
773 ///
774 /// let mut x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
775 /// let mut iter = x.iter_swap_mut();
776 ///
777 /// assert_eq!(iter.next(), Some(Either::Left(&mut 1)));
778 /// assert_eq!(iter.next(), Some(Either::Left(&mut 2)));
779 /// assert_eq!(iter.next(), None);
780 ///
781 /// println!("{x:?}"); // still can access `x`
782 /// ```
783 pub fn iter_swap_mut(
784 &mut self,
785 ) -> SwapIterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter>
786 where
787 for<'a> &'a mut L: IntoIterator,
788 for<'a> &'a mut R: IntoIterator,
789 {
790 SwapIterEither::new(
791 self.as_mut()
792 .bimap(IntoIterator::into_iter, IntoIterator::into_iter),
793 )
794 }
795
796 ////////////////////////////////////////////////////////////////////////////////
797 // Conversions
798 ////////////////////////////////////////////////////////////////////////////////
799
800 /// Converts `Either<L, R>` to `Either<R, L>`.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use either_or_both::Either;
806 ///
807 /// let value: Either<u8, char> = Either::Left(1);
808 /// assert_eq!(value.flip(), Either::Right(1));
809 ///
810 /// let value: Either<u8, char> = Either::Right('c');
811 /// assert_eq!(value.flip(), Either::Left('c'));
812 /// ```
813 #[must_use]
814 #[inline]
815 pub fn flip(self) -> Either<R, L> {
816 match self {
817 Self::Left(left) => Right(left),
818 Self::Right(right) => Left(right),
819 }
820 }
821
822 /// Applies mapping functions to the left and right values returning an `Either<T,
823 /// U>`.
824 ///
825 /// # Examples
826 ///
827 /// ```
828 /// use either_or_both::Either;
829 ///
830 /// let map_left = |left: u8| left.to_string();
831 /// let map_right = |right: char| right as i32;
832 ///
833 /// let value: Either<u8, char> = Either::Left(1);
834 /// assert_eq!(
835 /// value.bimap(map_left, map_right),
836 /// Either::Left("1".to_owned())
837 /// );
838 ///
839 /// let value: Either<u8, char> = Either::Right('c');
840 /// assert_eq!(value.bimap(map_left, map_right), Either::Right(99));
841 /// ```
842 #[inline]
843 pub fn bimap<F, G, T, U>(self, f: F, g: G) -> Either<T, U>
844 where
845 F: FnOnce(L) -> T,
846 G: FnOnce(R) -> U,
847 {
848 match self {
849 Self::Left(left) => Left(f(left)),
850 Self::Right(right) => Right(g(right)),
851 }
852 }
853
854 /// Applies a mapping function to the left value returning an `Either<T, R>`.
855 ///
856 /// # Examples
857 ///
858 /// ```
859 /// use either_or_both::Either;
860 ///
861 /// let map_left = |left: u8| left.to_string();
862 ///
863 /// let value: Either<u8, char> = Either::Left(1);
864 /// assert_eq!(value.map_left(map_left), Either::Left("1".to_owned()));
865 ///
866 /// let value: Either<u8, char> = Either::Right('c');
867 /// assert_eq!(value.map_left(map_left), Either::Right('c'));
868 /// ```
869 #[inline]
870 pub fn map_left<F, T>(self, f: F) -> Either<T, R>
871 where
872 F: FnOnce(L) -> T,
873 {
874 match self {
875 Self::Left(left) => Left(f(left)),
876 Self::Right(right) => Right(right),
877 }
878 }
879
880 /// Returns the provided default value if this is a [`Right`] or applies a mapping
881 /// function to the contained left value.
882 ///
883 /// The `map_left_or` combinator eagerly evaluates its arguments, which can result in
884 /// unnecessary computations. When chaining operations that involve function calls,
885 /// use [`map_left_or_else`] instead. It evaluates the function lazily.
886 ///
887 /// # Examples
888 ///
889 /// ```
890 /// use either_or_both::Either;
891 ///
892 /// let map_left = |left: u8| left as u64 + 1;
893 ///
894 /// let value: Either<u8, char> = Either::Right('c');
895 /// assert_eq!(value.map_left_or(42, map_left), 42u64);
896 ///
897 /// let value: Either<u8, char> = Either::Left(1);
898 /// assert_eq!(value.map_left_or(42, map_left), 2u64);
899 /// ```
900 ///
901 /// [`map_left_or_else`]: Either::map_left_or_else
902 #[inline]
903 pub fn map_left_or<F, T>(self, default: T, f: F) -> T
904 where
905 F: FnOnce(L) -> T,
906 {
907 self.map_left_or_else(|| default, f)
908 }
909
910 /// Applies the given function to the left value , mapping `L` to `T` otherwise
911 /// returns the [default value] for type `T`.
912 ///
913 /// # Examples
914 ///
915 /// ```
916 /// use either_or_both::Either;
917 ///
918 /// let map_left = |left: u8| left as u64 + 1;
919 ///
920 /// let value: Either<u8, char> = Either::Right('c');
921 /// assert_eq!(value.map_left_or_default(map_left), 0u64);
922 ///
923 /// let value: Either<u8, char> = Either::Left(1);
924 /// assert_eq!(value.map_left_or_default(map_left), 2u64);
925 /// ```
926 ///
927 /// [default value]: Default::default
928 #[inline]
929 pub fn map_left_or_default<F, T>(self, f: F) -> T
930 where
931 F: FnOnce(L) -> T,
932 T: Default,
933 {
934 self.map_left_or_else(T::default, f)
935 }
936
937 /// Applies the given function to the left value, mapping `L` to `T` otherwise applies
938 /// a different function.
939 ///
940 /// # Examples
941 ///
942 /// ```
943 /// use either_or_both::Either;
944 ///
945 /// let map_left = |left: u8| left.to_string();
946 ///
947 /// let value: Either<u8, char> = Either::Right('c');
948 /// assert_eq!(
949 /// value.map_left_or_else(|| String::from("left"), map_left),
950 /// String::from("left")
951 /// );
952 ///
953 /// let value: Either<u8, char> = Either::Left(1);
954 /// assert_eq!(
955 /// value.map_left_or_else(|| String::from("left"), map_left),
956 /// 1.to_string()
957 /// );
958 /// ```
959 #[inline]
960 pub fn map_left_or_else<D, F, T>(self, default: D, f: F) -> T
961 where
962 F: FnOnce(L) -> T,
963 D: FnOnce() -> T,
964 {
965 match self {
966 Self::Left(left) => f(left),
967 Self::Right(_) => default(),
968 }
969 }
970
971 /// Applies a mapping function to the right value returning an `Either<L, T>`.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// use either_or_both::Either;
977 ///
978 /// let map_right = |right: char| right.to_string();
979 ///
980 /// let value: Either<u8, char> = Either::Right('c');
981 /// assert_eq!(value.map_right(map_right), Either::Right("c".to_owned()));
982 ///
983 /// let value: Either<u8, char> = Either::Left(1);
984 /// assert_eq!(value.map_right(map_right), Either::Left(1));
985 /// ```
986 #[inline]
987 pub fn map_right<F, T>(self, f: F) -> Either<L, T>
988 where
989 F: FnOnce(R) -> T,
990 {
991 match self {
992 Self::Left(left) => Left(left),
993 Self::Right(right) => Right(f(right)),
994 }
995 }
996
997 /// Returns the provided default value if this is a [`Left`] or applies a mapping
998 /// function to the contained right value.
999 ///
1000 /// The `map_right_or` combinator eagerly evaluates its arguments, which can result in
1001 /// unnecessary computations. When chaining operations that involve function calls,
1002 /// use [`map_right_or_else`] instead. It evaluates the function lazily.
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// use either_or_both::Either;
1008 ///
1009 /// let map_right = |right: char| right as i32;
1010 ///
1011 /// let value: Either<u8, char> = Either::Right('c');
1012 /// assert_eq!(value.map_right_or(42, map_right), 99i32);
1013 ///
1014 /// let value: Either<u8, char> = Either::Left(1);
1015 /// assert_eq!(value.map_right_or(42, map_right), 42i32);
1016 /// ```
1017 ///
1018 /// [`map_right_or_else`]: Either::map_right_or_else
1019 #[inline]
1020 pub fn map_right_or<F, T>(self, default: T, f: F) -> T
1021 where
1022 F: FnOnce(R) -> T,
1023 {
1024 self.map_right_or_else(|| default, f)
1025 }
1026
1027 /// Applies the given function to the right value, mapping `R` to `T` otherwise
1028 /// returns the [default value] for type `T`.
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```
1033 /// use either_or_both::Either;
1034 ///
1035 /// let map_right = |right: char| right as u64 + 1;
1036 ///
1037 /// let value: Either<u8, char> = Either::Right('c');
1038 /// assert_eq!(value.map_right_or_default(map_right), 100u64);
1039 ///
1040 /// let value: Either<u8, char> = Either::Left(1);
1041 /// assert_eq!(value.map_right_or_default(map_right), 0u64);
1042 /// ```
1043 ///
1044 /// [default value]: Default::default
1045 #[inline]
1046 pub fn map_right_or_default<F, T>(self, f: F) -> T
1047 where
1048 F: FnOnce(R) -> T,
1049 T: Default,
1050 {
1051 self.map_right_or_else(T::default, f)
1052 }
1053
1054 /// Applies the given function to the right value, mapping `R` to `T` otherwise
1055 /// applies a different function.
1056 ///
1057 /// # Examples
1058 ///
1059 /// ```
1060 /// use either_or_both::Either;
1061 ///
1062 /// let map_right = |right: char| right.to_string();
1063 ///
1064 /// let value: Either<u8, char> = Either::Right('c');
1065 /// assert_eq!(
1066 /// value.map_right_or_else(|| String::from("right"), map_right),
1067 /// "c".to_owned()
1068 /// );
1069 ///
1070 /// let value: Either<u8, char> = Either::Left(1);
1071 /// assert_eq!(
1072 /// value.map_right_or_else(|| String::from("right"), map_right),
1073 /// String::from("right")
1074 /// );
1075 /// ```
1076 #[inline]
1077 pub fn map_right_or_else<D, F, T>(self, default: D, f: F) -> T
1078 where
1079 F: FnOnce(R) -> T,
1080 D: FnOnce() -> T,
1081 {
1082 match self {
1083 Self::Left(_) => default(),
1084 Self::Right(right) => f(right),
1085 }
1086 }
1087
1088 /// Calls functions with a reference to the contained values returning the original
1089 /// `Either`.
1090 ///
1091 /// # Examples
1092 ///
1093 /// ```
1094 /// use either_or_both::Either;
1095 ///
1096 /// // Prints a single line with "Left is: 1"
1097 /// let value: Either<u8, char> = Either::Left(1);
1098 /// let left = value
1099 /// .biinspect(|l| println!("Left is: {l}"), |r| println!("Right is: {r}"))
1100 /// .expect_left("should be a left value");
1101 /// assert_eq!(left, 1);
1102 ///
1103 /// // Prints a single line with "Right is: c"
1104 /// let value: Either<u8, char> = Either::Right('c');
1105 /// let right = value
1106 /// .biinspect(|l| println!("Left is: {l}"), |r| println!("Right is: {r}"))
1107 /// .expect_right("should be a right value");
1108 /// assert_eq!(right, 'c');
1109 /// ```
1110 #[inline]
1111 pub fn biinspect<F, G>(self, f: F, g: G) -> Self
1112 where
1113 for<'a> F: Fn(&'a L),
1114 for<'a> G: Fn(&'a R),
1115 {
1116 match &self {
1117 Self::Left(left) => f(left),
1118 Self::Right(right) => g(right),
1119 }
1120 self
1121 }
1122
1123 /// Calls a function with a reference to the contained left value returning the
1124 /// original `Either`.
1125 ///
1126 /// # Examples
1127 ///
1128 /// ```
1129 /// use either_or_both::Either;
1130 ///
1131 /// // Prints a single line with "Left is: 1"
1132 /// let value: Either<u8, char> = Either::Left(1);
1133 /// let left = value
1134 /// .inspect_left(|l| println!("Left is: {l}"))
1135 /// .expect_left("should be a left value");
1136 /// assert_eq!(left, 1);
1137 ///
1138 /// // Prints nothing
1139 /// let value: Either<u8, char> = Either::Right('c');
1140 /// let right = value
1141 /// .inspect_left(|l| println!("Left is: {l}"))
1142 /// .expect_right("should be a right value");
1143 /// assert_eq!(right, 'c');
1144 /// ```
1145 #[inline]
1146 pub fn inspect_left<F>(self, f: F) -> Self
1147 where
1148 for<'a> F: Fn(&'a L),
1149 {
1150 match &self {
1151 Self::Left(left) => f(left),
1152 Self::Right(_) => {}
1153 }
1154 self
1155 }
1156
1157 /// Calls a function with a reference to the contained right value returning the
1158 /// original `Either`.
1159 ///
1160 /// # Examples
1161 ///
1162 /// ```
1163 /// use either_or_both::Either;
1164 ///
1165 /// // Prints a single line with "Right is: c"
1166 /// let value: Either<u8, char> = Either::Right('c');
1167 /// let right = value
1168 /// .inspect_right(|r| println!("Right is: {r}"))
1169 /// .expect_right("should be a right value");
1170 /// assert_eq!(right, 'c');
1171 ///
1172 /// // Prints nothing
1173 /// let value: Either<u8, char> = Either::Left(1);
1174 /// let left = value
1175 /// .inspect_right(|r| println!("Right is: {r}"))
1176 /// .expect_left("should be a left value");
1177 /// assert_eq!(left, 1);
1178 /// ```
1179 #[inline]
1180 pub fn inspect_right<F>(self, f: F) -> Self
1181 where
1182 for<'a> F: Fn(&'a R),
1183 {
1184 match &self {
1185 Self::Left(_) => {}
1186 Self::Right(right) => f(right),
1187 }
1188 self
1189 }
1190
1191 /// Consumes this `Either` applying functions to the contained values taking mutable
1192 /// references to capture variables.
1193 ///
1194 /// # Examples
1195 ///
1196 /// ```
1197 /// use either_or_both::Either;
1198 ///
1199 /// let mut left = vec![];
1200 /// let mut right = vec![];
1201 ///
1202 /// let value: Either<u8, char> = Either::Left(1);
1203 /// value.biapply(|l| left.push(l), |r| right.push(r)); // moves `value`
1204 ///
1205 /// assert_eq!(left, vec![1]);
1206 /// ```
1207 ///
1208 /// The following example will not compile with the error: "cannot borrow `both` as
1209 /// mutable more than once at a time".
1210 ///
1211 /// If you need to apply a function that requires mutable access to both elements
1212 /// simultaneously, consider using [`biapply_with`] instead.
1213 ///
1214 /// ```compile_fail
1215 /// use either_or_both::Either;
1216 ///
1217 /// let mut both = vec![];
1218 ///
1219 /// let value: Either<u8, char> = Either::Both(1, 'c');
1220 /// value.biapply(|l| both.push(l), |r| both.push(r as u8));
1221 /// ```
1222 ///
1223 /// [`biapply_with`]: Either::biapply_with
1224 #[inline]
1225 pub fn biapply<F, G>(self, mut f: F, mut g: G)
1226 where
1227 F: FnMut(L),
1228 G: FnMut(R),
1229 {
1230 match self {
1231 Self::Left(left) => f(left),
1232 Self::Right(right) => g(right),
1233 }
1234 }
1235
1236 /// Consumes this `Either` applying functions to the contained values and a given
1237 /// accumulator.
1238 ///
1239 /// # Examples
1240 ///
1241 /// ```
1242 /// use either_or_both::Either;
1243 ///
1244 /// let mut both = vec![];
1245 ///
1246 /// let value: Either<u8, char> = Either::Left(1);
1247 /// value.biapply_with(&mut both, |acc, l| acc.push(l), |acc, r| acc.push(r as u8));
1248 ///
1249 /// let value: Either<u8, char> = Either::Right('c');
1250 /// value.biapply_with(&mut both, |acc, l| acc.push(l), |acc, r| acc.push(r as u8));
1251 ///
1252 /// assert_eq!(both, vec![1, 99]);
1253 /// ```
1254 ///
1255 /// [`flip`]: Either::flip
1256 #[inline]
1257 pub fn biapply_with<F, G, Acc>(self, acc: Acc, mut f: F, mut g: G)
1258 where
1259 F: FnMut(Acc, L),
1260 G: FnMut(Acc, R),
1261 {
1262 match self {
1263 Self::Left(left) => f(acc, left),
1264 Self::Right(right) => g(acc, right),
1265 }
1266 }
1267
1268 /// Consumes this `Either` applying a function to the contained left value.
1269 ///
1270 /// # Examples
1271 ///
1272 /// ```
1273 /// use either_or_both::Either;
1274 ///
1275 /// let mut left = vec![];
1276 /// let value: Either<u8, char> = Either::Left(1);
1277 /// value.apply_left(|l| left.push(l));
1278 /// assert_eq!(left, vec![1]);
1279 ///
1280 /// let mut left = vec![];
1281 /// let value: Either<u8, char> = Either::Right('c');
1282 /// value.apply_left(|l| left.push(l));
1283 /// assert_eq!(left.is_empty(), true);
1284 /// ```
1285 #[inline]
1286 pub fn apply_left<F>(self, mut f: F)
1287 where
1288 F: FnMut(L),
1289 {
1290 match self {
1291 Self::Left(left) => f(left),
1292 Self::Right(_) => {}
1293 }
1294 }
1295
1296 /// Consumes this `Either` applying a function to the contained right value.
1297 ///
1298 /// # Examples
1299 ///
1300 /// ```
1301 /// use either_or_both::Either;
1302 ///
1303 /// let mut right = vec![];
1304 /// let value: Either<u8, char> = Either::Right('c');
1305 /// value.apply_right(|r| right.push(r));
1306 /// assert_eq!(right, vec!['c']);
1307 ///
1308 /// let mut right = vec![];
1309 /// let value: Either<u8, char> = Either::Left(1);
1310 /// value.apply_right(|r| right.push(r));
1311 /// assert_eq!(right.is_empty(), true);
1312 /// ```
1313 #[inline]
1314 pub fn apply_right<F>(self, mut f: F)
1315 where
1316 F: FnMut(R),
1317 {
1318 match self {
1319 Self::Right(right) => f(right),
1320 Self::Left(_) => {}
1321 }
1322 }
1323
1324 /// Returns the contained values applying a mapping function which converts the `L`
1325 /// and `R` values to a uniform type.
1326 ///
1327 /// # Examples
1328 ///
1329 /// ```
1330 /// use either_or_both::Either;
1331 ///
1332 /// let value: Either<u8, char> = Either::Left(1);
1333 /// assert_eq!(
1334 /// value.bireduce(|l| l.to_string(), |r| r.to_string()),
1335 /// "1".to_owned()
1336 /// );
1337 ///
1338 /// let value: Either<u8, char> = Either::Right('c');
1339 /// assert_eq!(
1340 /// value.bireduce(|l| l.to_string(), |r| r.to_string()),
1341 /// "c".to_owned()
1342 /// );
1343 /// ```
1344 #[inline]
1345 pub fn bireduce<F, G, T>(self, f: F, g: G) -> T
1346 where
1347 F: FnOnce(L) -> T,
1348 G: FnOnce(R) -> T,
1349 {
1350 match self {
1351 Self::Left(left) => f(left),
1352 Self::Right(right) => g(right),
1353 }
1354 }
1355
1356 /// Returns the left value otherwise applies a function to a [`Right`] variant,
1357 /// converting it into an `L` value.
1358 ///
1359 /// # Example
1360 ///
1361 /// ```
1362 /// use either_or_both::Either;
1363 ///
1364 /// let value: Either<u8, char> = Either::Right('c');
1365 /// assert_eq!(value.reduce_left(|r| r as u8), 99);
1366 ///
1367 /// let value: Either<u8, char> = Either::Left(1);
1368 /// assert_eq!(value.reduce_left(|r| r as u8), 1);
1369 /// ```
1370 #[inline]
1371 pub fn reduce_left<F>(self, f: F) -> L
1372 where
1373 F: FnOnce(R) -> L,
1374 {
1375 match self {
1376 Self::Left(left) => left,
1377 Self::Right(right) => f(right),
1378 }
1379 }
1380
1381 /// Returns the right value otherwise applies a function to a [`Left`] variant,
1382 /// converting it into an `R` value.
1383 ///
1384 /// # Examples
1385 ///
1386 /// ```
1387 /// use either_or_both::Either;
1388 ///
1389 /// let value: Either<u8, char> = Either::Right('c');
1390 /// assert_eq!(value.reduce_right(|l| l as char), 'c');
1391 ///
1392 /// let value: Either<u8, char> = Either::Left(0);
1393 /// assert_eq!(value.reduce_right(|l| l as char), '\0');
1394 /// ```
1395 #[inline]
1396 pub fn reduce_right<F>(self, f: F) -> R
1397 where
1398 F: FnOnce(L) -> R,
1399 {
1400 match self {
1401 Self::Left(left) => f(left),
1402 Self::Right(right) => right,
1403 }
1404 }
1405
1406 /// Transforms the `Either<L, R>` into a `Result<R, L>`.
1407 ///
1408 /// Following the [convention], the left value represents an error and a right value
1409 /// represents a correct value.
1410 ///
1411 /// # Examples
1412 ///
1413 /// ```
1414 /// use either_or_both::Either;
1415 ///
1416 /// let value: Either<&str, u8> = Either::Right(1);
1417 /// assert_eq!(value.ok(), Ok(1));
1418 ///
1419 /// let value: Either<&str, u8> = Either::Left("this is an error");
1420 /// assert_eq!(value.ok(), Err("this is an error"));
1421 /// ```
1422 ///
1423 /// [convention]: ./index.html#conventions-and-edge-cases
1424 #[allow(clippy::missing_errors_doc)]
1425 #[inline]
1426 pub fn ok(self) -> Result<R, L> {
1427 match self {
1428 Self::Left(left) => Err(left),
1429 Self::Right(right) => Ok(right),
1430 }
1431 }
1432
1433 /// Transforms the `Either<L, R>` into a `Result<R, L>` using the provided `error` as
1434 /// error value.
1435 ///
1436 /// Following the [convention], the left value represents an error and a right value
1437 /// represents a correct value.
1438 ///
1439 /// The `ok_or` combinator eagerly evaluates its arguments, which can result in
1440 /// unnecessary computations. When chaining operations that involve function
1441 /// calls, use [`ok_or_else`] instead. It evaluates the function lazily.
1442 ///
1443 /// # Examples
1444 ///
1445 /// ```
1446 /// use either_or_both::Either;
1447 ///
1448 /// let value: Either<u8, char> = Either::Right('c');
1449 /// assert_eq!(value.ok_or("error message"), Ok('c'));
1450 ///
1451 /// let value: Either<u8, char> = Either::Left(1);
1452 /// assert_eq!(value.ok_or("error message"), Err("error message"));
1453 /// ```
1454 ///
1455 /// [`ok_or_else`]: Either::ok_or_else
1456 /// [convention]: ./index.html#conventions-and-edge-cases
1457 #[allow(clippy::missing_errors_doc)]
1458 #[inline]
1459 pub fn ok_or<E>(self, error: E) -> Result<R, E> {
1460 self.ok_or_else(|| error)
1461 }
1462
1463 /// Transforms the `Either<L, R>` into a `Result<R, L>` using the result of an `error`
1464 /// function as error value.
1465 ///
1466 /// Following the [convention], the left value represents an error and a right value
1467 /// represents a correct value.
1468 ///
1469 /// The `ok_or` combinator eagerly evaluates its arguments, which can result in
1470 /// unnecessary computations. When chaining operations that involve function
1471 /// calls, use [`ok_or_else`] instead. It evaluates the function lazily.
1472 ///
1473 /// # Examples
1474 ///
1475 /// ```
1476 /// use either_or_both::Either;
1477 ///
1478 /// let value: Either<u8, char> = Either::Right('c');
1479 /// assert_eq!(value.ok_or_else(|| String::from("error message")), Ok('c'));
1480 ///
1481 /// let value: Either<u8, char> = Either::Left(1);
1482 /// assert_eq!(
1483 /// value.ok_or_else(|| String::from("error message")),
1484 /// Err(String::from("error message"))
1485 /// );
1486 /// ```
1487 ///
1488 /// [`ok_or_else`]: Either::ok_or_else
1489 /// [convention]: ./index.html#conventions-and-edge-cases
1490 #[allow(clippy::missing_errors_doc)]
1491 #[inline]
1492 pub fn ok_or_else<F, E>(self, error: F) -> Result<R, E>
1493 where
1494 F: FnOnce() -> E,
1495 {
1496 match self {
1497 Self::Left(_) => Err(error()),
1498 Self::Right(ok) => Ok(ok),
1499 }
1500 }
1501
1502 /// Returns a tuple (L, R) with the provided values filling in any missing left or
1503 /// right value.
1504 ///
1505 /// # Examples
1506 ///
1507 /// ```
1508 /// use either_or_both::Either;
1509 ///
1510 /// let value: Either<u8, char> = Either::Left(1);
1511 /// assert_eq!(value.or(2, 'm'), (1, 'm'));
1512 ///
1513 /// let value: Either<u8, char> = Either::Right('c');
1514 /// assert_eq!(value.or(2, 'm'), (2, 'c'));
1515 /// ```
1516 #[inline]
1517 pub fn or(self, left: L, right: R) -> (L, R) {
1518 match self {
1519 Self::Left(left) => (left, right),
1520 Self::Right(right) => (left, right),
1521 }
1522 }
1523
1524 /// Returns a tuple (L, R) where any missing left or right value is replaced with its
1525 /// respective default value.
1526 ///
1527 /// # Examples
1528 ///
1529 /// ```
1530 /// use either_or_both::Either;
1531 ///
1532 /// let value: Either<u8, char> = Either::Left(1);
1533 /// assert_eq!(value.or_default(), (1, '\0'));
1534 ///
1535 /// let value: Either<u8, char> = Either::Right('c');
1536 /// assert_eq!(value.or_default(), (0, 'c'));
1537 /// ```
1538 #[inline]
1539 pub fn or_default(self) -> (L, R)
1540 where
1541 L: Default,
1542 R: Default,
1543 {
1544 match self {
1545 Self::Left(left) => (left, R::default()),
1546 Self::Right(right) => (L::default(), right),
1547 }
1548 }
1549
1550 /// Returns a tuple (L, R) where any missing left or right value is computed with the
1551 /// given functions.
1552 ///
1553 /// # Examples
1554 ///
1555 /// ```
1556 /// use either_or_both::Either;
1557 ///
1558 /// let value: Either<u8, char> = Either::Left(1);
1559 /// assert_eq!(value.or_else(|| 1 + 1, || char::from(100)), (1, 'd'));
1560 ///
1561 /// let value: Either<u8, char> = Either::Right('c');
1562 /// assert_eq!(value.or_else(|| 1 + 1, || char::from(100)), (2, 'c'));
1563 /// ```
1564 #[inline]
1565 pub fn or_else<F, G>(self, f: F, g: G) -> (L, R)
1566 where
1567 F: FnOnce() -> L,
1568 G: FnOnce() -> R,
1569 {
1570 match self {
1571 Self::Left(left) => (left, g()),
1572 Self::Right(right) => (f(), right),
1573 }
1574 }
1575
1576 /// Inserts `left` into the `Either` consuming it and returning an `EitherOrBoth`
1577 ///
1578 /// # Examples
1579 ///
1580 /// ```
1581 /// use either_or_both::{Either, EitherOrBoth};
1582 ///
1583 /// let value: Either<u8, char> = Either::Left(1);
1584 /// assert_eq!(value.inject_left(2), EitherOrBoth::Left(2));
1585 ///
1586 /// let value: Either<u8, char> = Either::Right('c');
1587 /// assert_eq!(value.inject_left(1), EitherOrBoth::Both(1, 'c'));
1588 /// ```
1589 #[inline]
1590 pub fn inject_left(self, left: L) -> EitherOrBoth<L, R> {
1591 match self {
1592 Self::Left(_) => EitherOrBoth::Left(left),
1593 Self::Right(right) => EitherOrBoth::Both(left, right),
1594 }
1595 }
1596
1597 /// Inserts `right` into the `Either` consuming it and returning an `EitherOrBoth`
1598 ///
1599 /// # Examples
1600 ///
1601 /// ```
1602 /// use either_or_both::{Either, EitherOrBoth};
1603 ///
1604 /// let value: Either<u8, char> = Either::Right('c');
1605 /// assert_eq!(value.inject_right('m'), EitherOrBoth::Right('m'));
1606 ///
1607 /// let value: Either<u8, char> = Either::Left(1);
1608 /// assert_eq!(value.inject_right('m'), EitherOrBoth::Both(1, 'm'));
1609 /// ```
1610 #[inline]
1611 pub fn inject_right(self, right: R) -> EitherOrBoth<L, R> {
1612 match self {
1613 Self::Left(left) => EitherOrBoth::Both(left, right),
1614 Self::Right(_) => EitherOrBoth::Right(right),
1615 }
1616 }
1617
1618 /// Converts into a [`Left`] variant, using the contained left value or applying a
1619 /// mapping function to the [`Right`] value.
1620 ///
1621 /// # Examples
1622 ///
1623 /// ```
1624 /// use either_or_both::Either;
1625 ///
1626 /// let value: Either<u8, char> = Either::Left(1);
1627 /// assert_eq!(value.into_left(|r| r as u8), Either::Left(1));
1628 ///
1629 /// let value: Either<u8, char> = Either::Right('c');
1630 /// assert_eq!(value.into_left(|r| r as u8), Either::Left(99));
1631 /// ```
1632 #[inline]
1633 pub fn into_left<F>(self, f: F) -> Self
1634 where
1635 F: FnOnce(R) -> L,
1636 {
1637 match self {
1638 Self::Left(_) => self,
1639 Self::Right(right) => Self::Left(f(right)),
1640 }
1641 }
1642
1643 /// Converts into a [`Right`] variant, using the contained right value or applying a
1644 /// mapping function to the [`Left`] value.
1645 ///
1646 /// # Examples
1647 ///
1648 /// ```
1649 /// use either_or_both::Either;
1650 ///
1651 /// let value: Either<u8, char> = Either::Right('c');
1652 /// assert_eq!(value.into_right(|l| l as char), Either::Right('c'));
1653 ///
1654 /// let value: Either<u8, char> = Either::Left(0);
1655 /// assert_eq!(value.into_right(|l| l as char), Either::Right('\0'));
1656 /// ```
1657 #[inline]
1658 pub fn into_right<F>(self, f: F) -> Self
1659 where
1660 F: FnOnce(L) -> R,
1661 {
1662 match self {
1663 Self::Left(left) => Self::Right(f(left)),
1664 Self::Right(_) => self,
1665 }
1666 }
1667
1668 ////////////////////////////////////////////////////////////////////////////////
1669 // Replacing values
1670 ////////////////////////////////////////////////////////////////////////////////
1671
1672 /// Replaces the `left` value returning the old value if present
1673 ///
1674 /// # Examples
1675 ///
1676 /// ```
1677 /// use either_or_both::Either;
1678 ///
1679 /// let mut value: Either<u8, char> = Either::Left(1);
1680 /// let old = value.replace_left(2);
1681 /// assert_eq!(old, Some(1));
1682 /// assert_eq!(value, Either::Left(2));
1683 ///
1684 /// let mut value: Either<u8, char> = Either::Right('c');
1685 /// let old = value.replace_left(2);
1686 /// assert_eq!(old, None);
1687 /// assert_eq!(value, Either::Right('c'));
1688 /// ```
1689 #[inline]
1690 pub fn replace_left(&mut self, value: L) -> Option<L> {
1691 match self {
1692 Self::Left(left) => Some(mem::replace(left, value)),
1693 Self::Right(_) => None,
1694 }
1695 }
1696
1697 /// Replaces the `right` value returning the old value if present
1698 ///
1699 /// # Examples
1700 ///
1701 /// ```
1702 /// use either_or_both::Either;
1703 ///
1704 /// let mut value: Either<u8, char> = Either::Right('c');
1705 /// let old = value.replace_right('m');
1706 /// assert_eq!(old, Some('c'));
1707 /// assert_eq!(value, Either::Right('m'));
1708 ///
1709 /// let mut value: Either<u8, char> = Either::Left(1);
1710 /// let old = value.replace_right('m');
1711 /// assert_eq!(old, None);
1712 /// assert_eq!(value, Either::Left(1));
1713 /// ```
1714 #[inline]
1715 pub fn replace_right(&mut self, value: R) -> Option<R> {
1716 match self {
1717 Self::Right(right) => Some(mem::replace(right, value)),
1718 Self::Left(_) => None,
1719 }
1720 }
1721}
1722
1723impl<T> Either<T, T> {
1724 /// Consumes this `Either` applying a function to the contained value (of a uniform
1725 /// type) taking mutable references to capture variables.
1726 ///
1727 /// # Examples
1728 ///
1729 /// ```
1730 /// use either_or_both::Either;
1731 ///
1732 /// let mut both = vec![];
1733 ///
1734 /// let value: Either<char> = Either::Left('c');
1735 /// value.apply(|c| both.push(c));
1736 ///
1737 /// let value: Either<char> = Either::Right('a');
1738 /// value.apply(|c| both.push(c));
1739 ///
1740 /// assert_eq!(both, vec!['c', 'a']);
1741 /// ```
1742 #[inline]
1743 pub fn apply<F>(self, mut f: F)
1744 where
1745 F: FnMut(T),
1746 {
1747 match self {
1748 Self::Left(left) => f(left),
1749 Self::Right(right) => f(right),
1750 }
1751 }
1752
1753 /// Calls a function with a reference to the contained value (of a uniform type)
1754 /// returning the original `Either`.
1755 ///
1756 /// # Examples
1757 ///
1758 /// ```
1759 /// use either_or_both::Either;
1760 ///
1761 /// // Prints a single line with "The value is: c"
1762 /// let value: Either<char> = Either::Left('c');
1763 /// let left = value
1764 /// .inspect(|c| println!("The value is: {c}"))
1765 /// .expect_left("should be a left value");
1766 /// assert_eq!(left, 'c');
1767 ///
1768 /// // Prints a single line with "The value is: a"
1769 /// let value: Either<char> = Either::Right('a');
1770 /// let right = value
1771 /// .inspect(|c| println!("The value is: {c}"))
1772 /// .expect_right("should be a right value");
1773 ///
1774 /// assert_eq!(right, 'a');
1775 /// ```
1776 #[inline]
1777 pub fn inspect<F>(self, f: F) -> Self
1778 where
1779 for<'a> F: Fn(&'a T),
1780 {
1781 match &self {
1782 Self::Left(left) => f(left),
1783 Self::Right(right) => f(right),
1784 }
1785
1786 self
1787 }
1788
1789 /// Returns an iterator over the contained value of a uniform type
1790 ///
1791 /// # Examples
1792 ///
1793 /// ```
1794 /// use either_or_both::EitherOrBoth;
1795 ///
1796 /// let value: EitherOrBoth<char> = EitherOrBoth::Left('c');
1797 /// let mut iter = value.iter();
1798 /// assert_eq!(iter.next(), Some(&'c'));
1799 /// assert_eq!(iter.next(), None);
1800 ///
1801 /// let value: EitherOrBoth<char> = EitherOrBoth::Right('c');
1802 /// let mut iter = value.iter();
1803 /// assert_eq!(iter.next(), Some(&'c'));
1804 /// assert_eq!(iter.next(), None);
1805 /// ```
1806 #[inline]
1807 pub fn iter(&self) -> IterEither<'_, T> {
1808 IterEither::new(self)
1809 }
1810
1811 /// Returns an iterator over the contained mutable value of a uniform type
1812 ///
1813 /// # Examples
1814 ///
1815 /// ```
1816 /// use either_or_both::EitherOrBoth;
1817 ///
1818 /// let mut value: EitherOrBoth<char> = EitherOrBoth::Left('c');
1819 /// let mut iter = value.iter_mut();
1820 /// assert_eq!(iter.next(), Some(&mut 'c'));
1821 /// assert_eq!(iter.next(), None);
1822 ///
1823 /// let mut value: EitherOrBoth<char> = EitherOrBoth::Right('c');
1824 /// let mut iter = value.iter_mut();
1825 /// assert_eq!(iter.next(), Some(&mut 'c'));
1826 /// assert_eq!(iter.next(), None);
1827 /// ```
1828 #[inline]
1829 pub fn iter_mut(&mut self) -> IterMutEither<'_, T> {
1830 IterMutEither::new(self)
1831 }
1832
1833 /// Consumes the `Either`, returning an iterator over the contained iterator of a
1834 /// uniform type
1835 ///
1836 /// For iteration over contained iterators with non-uniform types, you can use
1837 /// [`into_iter_swap`] instead.
1838 ///
1839 /// # Examples
1840 ///
1841 /// ```
1842 /// use either_or_both::Either;
1843 ///
1844 /// let value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
1845 /// let collected: Vec<char> = value.into_iter_inner().collect();
1846 /// assert_eq!(collected, vec!['c', 'a']);
1847 /// ```
1848 ///
1849 /// [`into_iter_swap`]: Either::into_iter_swap
1850 pub fn into_iter_inner(self) -> InnerIterEither<<T as IntoIterator>::IntoIter>
1851 where
1852 T: IntoIterator,
1853 {
1854 InnerIterEither::new(self.map(IntoIterator::into_iter))
1855 }
1856
1857 /// Returns an iterator over the contained iterator of a uniform type
1858 ///
1859 /// For iteration over contained iterators with non-uniform types, you can use
1860 /// [`iter_swap`] instead.
1861 ///
1862 /// # Examples
1863 ///
1864 /// ```
1865 /// use either_or_both::Either;
1866 ///
1867 /// let value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
1868 /// let collected: Vec<&char> = value.iter_inner().collect();
1869 /// assert_eq!(collected, vec![&'c', &'a']);
1870 /// ```
1871 ///
1872 /// [`iter_swap`]: Either::into_iter_swap
1873 pub fn iter_inner(&self) -> InnerIterEither<<&T as IntoIterator>::IntoIter>
1874 where
1875 for<'a> &'a T: IntoIterator,
1876 {
1877 InnerIterEither::new(self.as_ref().map(IntoIterator::into_iter))
1878 }
1879
1880 /// Returns an iterator over the mutable values of the contained iterator of a uniform
1881 /// type
1882 ///
1883 /// For iteration over contained iterators with non-uniform types, you can use
1884 /// [`iter_swap_mut`] instead.
1885 ///
1886 /// # Examples
1887 ///
1888 /// ```
1889 /// use either_or_both::Either;
1890 ///
1891 /// let mut value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
1892 /// let collected: Vec<&mut char> = value.iter_inner_mut().collect();
1893 /// assert_eq!(collected, vec![&mut 'c', &mut 'a']);
1894 /// ```
1895 ///
1896 /// [`iter_swap_mut`]: Either::iter_swap_mut
1897 pub fn iter_inner_mut(&mut self) -> InnerIterEither<<&mut T as IntoIterator>::IntoIter>
1898 where
1899 for<'a> &'a mut T: IntoIterator,
1900 {
1901 InnerIterEither::new(self.as_mut().map(IntoIterator::into_iter))
1902 }
1903
1904 /// Applies a mapping function to the left and right values (of a uniform type)
1905 /// returning an `Either<U, U>`.
1906 ///
1907 /// # Examples
1908 ///
1909 /// ```
1910 /// use either_or_both::Either;
1911 ///
1912 /// let value: Either<char> = Either::Left('c');
1913 /// assert_eq!(value.map(|c| c.to_string()), Either::Left("c".to_owned()));
1914 ///
1915 /// let value: Either<char> = Either::Right('a');
1916 /// assert_eq!(value.map(|c| c.to_string()), Either::Right("a".to_owned()));
1917 /// ```
1918 #[inline]
1919 pub fn map<F, U>(self, f: F) -> Either<U, U>
1920 where
1921 F: FnOnce(T) -> U,
1922 {
1923 match self {
1924 Self::Left(left) => Left(f(left)),
1925 Self::Right(right) => Right(f(right)),
1926 }
1927 }
1928
1929 /// Returns the contained [`Left`] or [`Right`] value of uniform type.
1930 ///
1931 /// # Example
1932 ///
1933 /// ```
1934 /// use either_or_both::Either;
1935 ///
1936 /// let value: Either<u8> = Either::Left(1);
1937 /// assert_eq!(value.reduce(), 1);
1938 ///
1939 /// let value: Either<u8> = Either::Right(2);
1940 /// assert_eq!(value.reduce(), 2);
1941 /// ```
1942 #[inline]
1943 pub fn reduce(self) -> T {
1944 match self {
1945 Self::Left(left) => left,
1946 Self::Right(right) => right,
1947 }
1948 }
1949
1950 /// Returns the contained [`Left`] or [`Right`] value applying a mapping function to
1951 /// the contained values.
1952 ///
1953 /// # Example
1954 ///
1955 /// ```
1956 /// use either_or_both::Either;
1957 ///
1958 /// let value: Either<u8> = Either::Left(1);
1959 /// assert_eq!(value.reduce_map(|v| v + 1), 2);
1960 ///
1961 /// let value: Either<u8> = Either::Right(2);
1962 /// assert_eq!(value.reduce_map(|v| v + 1), 3);
1963 /// ```
1964 #[inline]
1965 pub fn reduce_map<F, U>(self, f: F) -> U
1966 where
1967 F: FnOnce(T) -> U,
1968 {
1969 match self {
1970 Self::Left(left) => f(left),
1971 Self::Right(right) => f(right),
1972 }
1973 }
1974}
1975
1976impl<L, R> Either<&L, &R> {
1977 /// Converts an `Either<&L, &R>` into an `Either<L, R>` by cloning its contents
1978 ///
1979 /// # Examples
1980 ///
1981 /// ```
1982 /// use either_or_both::Either;
1983 ///
1984 /// let value: Either<u8, char> = Either::Left(1);
1985 /// let refs: Either<&u8, &char> = value.as_ref();
1986 /// assert_eq!(refs.cloned(), Either::Left(1));
1987 /// ```
1988 #[must_use = "`self` will be dropped if the result is not used"]
1989 pub fn cloned(self) -> Either<L, R>
1990 where
1991 L: Clone,
1992 R: Clone,
1993 {
1994 match self {
1995 Self::Left(left) => Left(left.clone()),
1996 Self::Right(right) => Right(right.clone()),
1997 }
1998 }
1999
2000 /// Converts an `Either<&L, &R>` into an `Either<L, R>` by copying its contents.
2001 ///
2002 /// # Examples
2003 ///
2004 /// ```
2005 /// use either_or_both::Either;
2006 ///
2007 /// let value: Either<u8, char> = Either::Left(1);
2008 /// let refs: Either<&u8, &char> = value.as_ref();
2009 /// assert_eq!(refs.copied(), Either::Left(1));
2010 /// ```
2011 #[must_use = "`self` will be dropped if the result is not used"]
2012 pub const fn copied(self) -> Either<L, R>
2013 where
2014 L: Copy,
2015 R: Copy,
2016 {
2017 match self {
2018 Self::Left(left) => Left(*left),
2019 Self::Right(right) => Right(*right),
2020 }
2021 }
2022}
2023
2024impl<L, R> Either<&mut L, &mut R> {
2025 /// Converts an `Either<&mut L, &mut R>` into an `Either<L, R>` by cloning its
2026 /// contents.
2027 ///
2028 /// # Examples
2029 ///
2030 /// ```
2031 /// use either_or_both::Either;
2032 ///
2033 /// let mut value: Either<u8, char> = Either::Left(1);
2034 /// let refs: Either<&mut u8, &mut char> = value.as_mut();
2035 /// assert_eq!(refs.cloned(), Either::Left(1));
2036 /// ```
2037 #[must_use = "`self` will be dropped if the result is not used"]
2038 pub fn cloned(self) -> Either<L, R>
2039 where
2040 L: Clone,
2041 R: Clone,
2042 {
2043 match self {
2044 Self::Left(left) => Left(left.clone()),
2045 Self::Right(right) => Right(right.clone()),
2046 }
2047 }
2048
2049 /// Converts an `Either<&mut L, &mut R>` into an `Either<L, R>` by copying its
2050 /// contents
2051 ///
2052 /// # Examples
2053 ///
2054 /// ```
2055 /// use either_or_both::Either;
2056 ///
2057 /// let mut value: Either<u8, char> = Either::Left(1);
2058 /// let refs: Either<&mut u8, &mut char> = value.as_mut();
2059 /// assert_eq!(refs.copied(), Either::Left(1));
2060 /// ```
2061 #[must_use = "`self` will be dropped if the result is not used"]
2062 pub fn copied(self) -> Either<L, R>
2063 where
2064 L: Copy,
2065 R: Copy,
2066 {
2067 match self {
2068 Self::Left(left) => Left(*left),
2069 Self::Right(right) => Right(*right),
2070 }
2071 }
2072}
2073
2074impl<L1, L2, R1, R2> Either<(L1, R1), (L2, R2)> {
2075 /// Transposes a `Either` of tuples to a tuple of `Eithers`
2076 ///
2077 /// # Examples
2078 ///
2079 /// ```
2080 /// use either_or_both::Either;
2081 ///
2082 /// let value: Either<(u8, char), (i32, u64)> = Either::Left((1, 'c'));
2083 /// assert_eq!(value.transpose(), (Either::Left(1), Either::Left('c')));
2084 ///
2085 /// let value: Either<(u8, char), (i32, u64)> = Either::Right((-2, 10));
2086 /// assert_eq!(value.transpose(), (Either::Right(-2), Either::Right(10)));
2087 /// ```
2088 pub fn transpose(self) -> (Either<L1, L2>, Either<R1, R2>) {
2089 match self {
2090 Self::Left((l1, r1)) => (Left(l1), Left(r1)),
2091 Self::Right((l2, r2)) => (Right(l2), Right(r2)),
2092 }
2093 }
2094}
2095
2096impl<L, R, T> Either<(T, L), (T, R)> {
2097 /// Transposes an `Either` of tuples to a tuple of a single value and an `Either` with
2098 /// the left value having a uniform type
2099 ///
2100 /// # Examples
2101 ///
2102 /// ```
2103 /// use either_or_both::Either;
2104 ///
2105 /// let value: Either<(u8, char), (u8, i32)> = Either::Left((1, 'c'));
2106 /// assert_eq!(value.transpose_left(), (1, Either::Left('c')));
2107 ///
2108 /// let value: Either<(u8, char), (u8, i32)> = Either::Right((2, -10));
2109 /// assert_eq!(value.transpose_left(), (2, Either::Right(-10)));
2110 /// ```
2111 pub fn transpose_left(self) -> (T, Either<L, R>) {
2112 match self {
2113 Self::Left((target, left)) => (target, Left(left)),
2114 Self::Right((target, right)) => (target, Right(right)),
2115 }
2116 }
2117}
2118
2119impl<L, R, T> Either<(L, T), (R, T)> {
2120 /// Transposes an `Either` of tuples to a tuple of a single value and an `Either` with
2121 /// the right value having a uniform type
2122 ///
2123 /// # Examples
2124 ///
2125 /// ```
2126 /// use either_or_both::Either;
2127 ///
2128 /// let value: Either<(u8, char), (i32, char)> = Either::Left((1, 'c'));
2129 /// assert_eq!(value.transpose_right(), (Either::Left(1), 'c'));
2130 ///
2131 /// let value: Either<(u8, char), (i32, char)> = Either::Right((-2, 'a'));
2132 /// assert_eq!(value.transpose_right(), (Either::Right(-2), 'a'));
2133 /// ```
2134 pub fn transpose_right(self) -> (Either<L, R>, T) {
2135 match self {
2136 Self::Left((left, target)) => (Left(left), target),
2137 Self::Right((right, target)) => (Right(right), target),
2138 }
2139 }
2140}
2141
2142impl<L, R> Either<Option<L>, Option<R>> {
2143 /// Transposes an `Either` of [`Options`] to an option of an `Either`
2144 ///
2145 /// # Examples
2146 ///
2147 /// ```
2148 /// use either_or_both::Either;
2149 ///
2150 /// let value: Either<Option<u8>, Option<char>> = Either::Left(Some(1));
2151 /// assert_eq!(value.transpose(), Some(Either::Left(1)));
2152 ///
2153 /// let value: Either<Option<u8>, Option<char>> = Either::Left(None);
2154 /// assert_eq!(value.transpose(), None);
2155 ///
2156 /// let value: Either<Option<u8>, Option<char>> = Either::Right(Some('c'));
2157 /// assert_eq!(value.transpose(), Some(Either::Right('c')));
2158 /// ```
2159 ///
2160 /// [`Options`]: Option
2161 #[inline]
2162 pub fn transpose(self) -> Option<Either<L, R>> {
2163 match self {
2164 Self::Left(left) => left.map(Left),
2165 Self::Right(right) => right.map(Right),
2166 }
2167 }
2168}
2169
2170impl<L, R, E1, E2> Either<Result<L, E1>, Result<R, E2>> {
2171 /// Transposes an `Either` of [`Results`] to a [`Result`] of an `Either`
2172 ///
2173 /// # Examples
2174 ///
2175 /// ```
2176 /// use either_or_both::Either;
2177 ///
2178 /// let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Left(Ok(1));
2179 /// assert_eq!(value.transpose(), Ok(Either::Left(1)));
2180 ///
2181 /// let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Left(Err('c'));
2182 /// assert_eq!(value.transpose(), Err(Either::Left('c')));
2183 ///
2184 /// let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Right(Ok(-2));
2185 /// assert_eq!(value.transpose(), Ok(Either::Right(-2)));
2186 /// ```
2187 ///
2188 /// [`Results`]: Result
2189 #[allow(clippy::missing_errors_doc)]
2190 #[inline]
2191 pub fn transpose(self) -> Result<Either<L, R>, Either<E1, E2>> {
2192 match self {
2193 Self::Left(left) => match left {
2194 Ok(ok) => Ok(Left(ok)),
2195 Err(err) => Err(Left(err)),
2196 },
2197 Self::Right(right) => match right {
2198 Ok(ok) => Ok(Right(ok)),
2199 Err(err) => Err(Right(err)),
2200 },
2201 }
2202 }
2203}
2204
2205impl<L, R, E> Either<Result<L, E>, Result<R, E>> {
2206 /// Transposes an `Either` of [`Results`] to a [`Result`] with an uniform error type
2207 ///
2208 /// # Examples
2209 ///
2210 /// ```
2211 /// use either_or_both::Either;
2212 ///
2213 /// let x: Either<Result<u8, char>, Result<i32, char>> = Either::Left(Ok(1));
2214 /// assert_eq!(x.transpose_err(), Ok(Either::Left(1)));
2215 ///
2216 /// let x: Either<Result<u8, char>, Result<i32, char>> = Either::Left(Err('c'));
2217 /// assert_eq!(x.transpose_err(), Err('c'));
2218 ///
2219 /// let x: Either<Result<u8, char>, Result<i32, char>> = Either::Right(Ok(-2));
2220 /// assert_eq!(x.transpose_err(), Ok(Either::Right(-2)));
2221 /// ```
2222 ///
2223 /// [`Results`]: Result
2224 #[allow(clippy::missing_errors_doc)]
2225 #[inline]
2226 pub fn transpose_err(self) -> Result<Either<L, R>, E> {
2227 match self {
2228 Self::Left(left) => left.map(Left),
2229 Self::Right(right) => right.map(Right),
2230 }
2231 }
2232}
2233
2234impl<T, E1, E2> Either<Result<T, E1>, Result<T, E2>> {
2235 /// Transposes an `Either` of [`Results`] to a [`Result`] with an uniform correct type
2236 ///
2237 /// # Examples
2238 ///
2239 /// ```
2240 /// use either_or_both::Either;
2241 ///
2242 /// let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Left(Ok(2));
2243 /// assert_eq!(x.transpose_ok(), Ok(2));
2244 ///
2245 /// let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Left(Err('c'));
2246 /// assert_eq!(x.transpose_ok(), Err(Either::Left('c')));
2247 ///
2248 /// let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Right(Ok(2));
2249 /// assert_eq!(x.transpose_ok(), Ok(2));
2250 /// ```
2251 ///
2252 /// [`Results`]: Result
2253 #[allow(clippy::missing_errors_doc)]
2254 #[inline]
2255 pub fn transpose_ok(self) -> Result<T, Either<E1, E2>> {
2256 match self {
2257 Self::Left(left) => left.map_err(Left),
2258 Self::Right(right) => right.map_err(Right),
2259 }
2260 }
2261}