either_both/lib.rs
1//! This crate is intended to be similar to [`either`][either-crate],
2//! but also cover the "both" variant.
3//!
4//! This crate was inspired by wanting to implement a method similar to
5//! [`Iterator::zip`] that continues until *both* zipped iterators are exhausted.
6//!
7//! # Usage
8//!
9//! It's recommended to use the prelude, which brings into scope `Either<L, R>`, and
10//! also its variants:
11//!
12//! * `Left`
13//! * `Right`
14//! * `Both`
15//!
16//! ```rust
17//! use either_both::prelude::*;
18//!
19//! // Just like how Option's and Result's variants are often used without the prefix,
20//! // you can now use Left, Right, and Both without prefixing with "Either::"
21//! const CHOICES: [Either<bool, u8>;3] = [Left(true), Right(1), Both(false, 0)];
22//! ```
23//!
24//! # Example
25//!
26//! ```rust
27//! use either_both::prelude::*;
28//!
29//! pub struct ZipToEnd<A: Iterator, B: Iterator>(A, B);
30//!
31//! impl<A: Iterator, B: Iterator> Iterator for ZipToEnd<A, B> {
32//! type Item = Either<<A as Iterator>::Item, <B as Iterator>::Item>;
33//!
34//! fn next(&mut self) -> Option<Self::Item> {
35//! Either::from_options(self.0.next(), self.1.next())
36//! }
37//! }
38//! ```
39//!
40//! [either-crate]: https://crates.io/crates/either
41#![cfg_attr(not(feature = "std"), no_std)]
42use core::{convert::identity, iter::FusedIterator, ops::Add};
43
44pub use Either::{Both, Left, Right};
45
46pub mod prelude;
47/// The main enum, with variants `Left`, `Right`, and `Both`.
48///
49/// Because `Both` represents *both* left and right variants being present, most
50/// methods that act on either `Left` or `Right` will also act on `Both`. For
51/// example, [`Either::left`] should only return `None` on the variant `Right`, and
52/// `Some` on `Left` and `Both`. Methods that act *exclusively* on the `Left` or
53/// `Right` variants will usually have "only" in the name, like [`Either::only_left`].
54///
55/// While most methods will have an "only" version, some will not if:
56///
57/// * other wording would be more descriptive. For example, rather than define `is_left`
58/// and `is_only_left`, there is [`Either::is_left`] and [`Either::has_left`].
59/// * it doesn't make sense to have an "only" version. For example, while there is
60/// [`Either::map_left`], there isn't `map_only_left`, because it would be unknown
61/// what the `Both` variant's left value should become when the left type changes.
62///
63#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
64pub enum Either<L, R> {
65 Left(L),
66 Right(R),
67 /// Both `Left` and `Right` variants, together.
68 Both(L, R),
69}
70
71/// Always returns `None`, to represent when neither the left nor right value are
72/// present.
73///
74/// Using `None` (or `Option::<Either::<L, R>>::None` for the long form) is fine.
75///
76/// # Example
77///
78/// ```rust
79/// # use either_both::prelude::*;
80/// let maybe_either: MaybeEither<u32, i32> = Either::from_options(None, None);
81/// assert_eq!(maybe_either, neither());
82/// ```
83#[inline]
84pub const fn neither<L, R>() -> MaybeEither<L, R> {
85 None
86}
87
88/// A shortcut to represent the possibility of neither left nor right values existing
89/// by wrapping the `Either<L, R>` in an `Option`.
90pub type MaybeEither<L, R> = Option<Either<L, R>>;
91
92impl<L, R> Either<L, R> {
93 /// Converts two options to `Option<Either<L, R>>`.
94 ///
95 /// # Example
96 ///
97 /// ```rust
98 /// # use either_both::prelude::*;
99 /// assert!(Either::<(), ()>::from_options(None, None).is_none());
100 /// let left = Either::<_, ()>::from_options(Some(1), None).unwrap();
101 /// assert_eq!(left, Left(1));
102 /// let right = Either::<(), _>::from_options(None, Some(1)).unwrap();
103 /// assert_eq!(right, Right(1));
104 /// let both = Either::from_options(Some('l'), Some('r')).unwrap();
105 /// assert_eq!(both, Both('l', 'r'));
106 /// ```
107 pub fn from_options(left: Option<L>, right: Option<R>) -> MaybeEither<L, R> {
108 let either = match (left, right) {
109 (None, None) => return None,
110 (Some(l), None) => Left(l),
111 (None, Some(r)) => Right(r),
112 (Some(l), Some(r)) => Both(l, r),
113 };
114 Some(either)
115 }
116
117 /// Converts `&Either<L, R>` to `Either<&L, &R>`
118 ///
119 /// # Example
120 ///
121 /// ```rust
122 /// # use either_both::prelude::*;
123 /// let value_and_label = Both(1usize, "one");
124 /// let threes: Either<usize, usize> = value_and_label
125 /// .map_left(|value| value + 2)
126 /// .map_right(|label| label.len());
127 /// println!("still can print value_and_label: {value_and_label:?}");
128 /// ```
129 ///
130 pub const fn as_ref(&self) -> Either<&L, &R> {
131 match *self {
132 Left(ref l) => Left(l),
133 Right(ref r) => Right(r),
134 Both(ref l, ref r) => Both(l, r),
135 }
136 }
137
138 /// Gets the left value from either `Left` or `Both`. To exclude `Both`, use
139 /// [`Either::only_left`].
140 pub fn left(self) -> Option<L> {
141 match self {
142 Left(l) | Both(l, _) => Some(l),
143 Right(_) => None,
144 }
145 }
146
147 /// Gets the left value from only `Left`. To include `Both`, use [`Either::left`].
148 pub fn only_left(self) -> Option<L> {
149 match self {
150 Left(l) => Some(l),
151 _ => None,
152 }
153 }
154
155 /// Gets the right value from either `Right` or `Both`. To exclude `Both`, use
156 /// [`Either::only_right`].
157 pub fn right(self) -> Option<R> {
158 match self {
159 Right(r) | Both(_, r) => Some(r),
160 Left(_) => None,
161 }
162 }
163
164 /// Gets the right value from only `Right`. To include `Both`, use [`Either::right`].
165 pub fn only_right(self) -> Option<R> {
166 match self {
167 Right(r) => Some(r),
168 _ => None,
169 }
170 }
171
172 /// Gets both values if they exist.
173 ///
174 /// # Example
175 ///
176 /// ```rust
177 /// # use either_both::prelude::*;
178 /// let vehicles = Both(2u8, 1u8);
179 /// let (cars, motorcycles) = vehicles
180 /// .both()
181 /// .expect("inventory for both cars and motorcycles to be tracked");
182 /// assert_eq!(cars, 2);
183 /// assert_eq!(motorcycles, 1);
184 /// ```
185 pub fn both(self) -> Option<(L, R)> {
186 match self {
187 Both(l, r) => Some((l, r)),
188 _ => None,
189 }
190 }
191
192 /// Tries to get a left value from either `Left` or `Both`. To exclude `Both`,
193 /// use [`Either::expect_only_left`].
194 ///
195 /// # Examples
196 ///
197 /// ```rust
198 /// # use either_both::prelude::*;
199 /// let left: Either<_, ()> = Left(1);
200 /// let one = left.expect_left("left to exist");
201 /// ```
202 ///
203 /// ```rust,should_panic
204 /// # use either_both::prelude::*;
205 /// let right: Either<i32, _> = Right(());
206 /// let two = right.expect_left("left to exist");
207 /// ```
208 ///
209 /// ```rust
210 /// # use either_both::prelude::*;
211 /// let both = Both(3, ());
212 /// let three = both.expect_left("left to exist");
213 /// ```
214 pub fn expect_left(self, message: &str) -> L {
215 match self {
216 Left(l) | Both(l, _) => l,
217 Right(_) => panic!("{message}"),
218 }
219 }
220
221 /// Tries to get a left value from `Left`. To include `Both`,
222 /// use [`Either::expect_left`].
223 ///
224 /// # Examples
225 ///
226 /// ```rust
227 /// # use either_both::prelude::*;
228 /// let left: Either<_, ()> = Left(1);
229 /// let one = left.expect_only_left("left to exist");
230 /// ```
231 ///
232 /// ```rust,should_panic
233 /// # use either_both::prelude::*;
234 /// let right: Either<i32, _> = Right(());
235 /// let two = right.expect_only_left("left to exist");
236 /// ```
237 ///
238 /// ```rust,should_panic
239 /// # use either_both::prelude::*;
240 /// let both = Both(3, ());
241 /// let three = both.expect_only_left("left to exist");
242 /// ```
243 pub fn expect_only_left(self, message: &str) -> L {
244 if let Left(l) = self {
245 l
246 } else {
247 panic!("{message}")
248 }
249 }
250
251 /// Tries to get a right value from either `Right` or `Both`. To exclude `Both`,
252 /// use [`Either::expect_only_right`].
253 ///
254 /// # Examples
255 ///
256 /// ```rust,should_panic
257 /// # use either_both::prelude::*;
258 /// let left: Either<_, i32> = Left(());
259 /// let one = left.expect_right("left to exist");
260 /// ```
261 ///
262 /// ```rust
263 /// # use either_both::prelude::*;
264 /// let right: Either<(), _> = Right(2);
265 /// let two = right.expect_right("left to exist");
266 /// ```
267 ///
268 /// ```rust
269 /// # use either_both::prelude::*;
270 /// let both = Both((), 3);
271 /// let three = both.expect_right("left to exist");
272 /// ```
273 pub fn expect_right(self, message: &str) -> R {
274 match self {
275 Right(r) | Both(_, r) => r,
276 Left(_) => panic!("{message}"),
277 }
278 }
279
280 /// Tries to get a right value from `Right`. To include `Both`,
281 /// use [`Either::expect_right`].
282 ///
283 /// # Examples
284 ///
285 /// ```rust,should_panic
286 /// # use either_both::prelude::*;
287 /// let left: Either<_, i32> = Left(());
288 /// let one = left.expect_only_right("left to exist");
289 /// ```
290 ///
291 /// ```rust
292 /// # use either_both::prelude::*;
293 /// let right: Either<(), _> = Right(2);
294 /// let two = right.expect_only_right("left to exist");
295 /// ```
296 ///
297 /// ```rust,should_panic
298 /// # use either_both::prelude::*;
299 /// let both = Both((), 3);
300 /// let three = both.expect_only_right("left to exist");
301 /// ```
302 pub fn expect_only_right(self, message: &str) -> R {
303 if let Right(r) = self {
304 r
305 } else {
306 panic!("{message}")
307 }
308 }
309
310 /// Tries to get both left and right values together.
311 ///
312 /// # Examples
313 ///
314 /// ```rust,should_panic
315 /// # use either_both::prelude::*;
316 /// let left: Either<_, i32> = Left(1);
317 /// let (one, two) = left.expect_both("both to exist");
318 /// ```
319 ///
320 /// ```rust,should_panic
321 /// # use either_both::prelude::*;
322 /// let right: Either<i32, _> = Right(4);
323 /// let (three, four) = right.expect_both("both to exist");
324 /// ```
325 ///
326 /// ```rust
327 /// # use either_both::prelude::*;
328 /// let both = Both(5, 6);
329 /// let (five, six) = both.expect_both("both to exist");
330 /// ```
331 pub fn expect_both(self, message: &str) -> (L, R) {
332 if let Both(l, r) = self {
333 (l, r)
334 } else {
335 panic!("{message}")
336 }
337 }
338
339 /// Tries to get a left value from either `Left` or `Both`. To exclude `Both`,
340 /// use [`Either::unwrap_only_left`].
341 ///
342 /// # Examples
343 ///
344 /// ```rust
345 /// # use either_both::prelude::*;
346 /// let left: Either<_, ()> = Left(1);
347 /// let one = left.unwrap_left();
348 /// ```
349 ///
350 /// ```rust,should_panic
351 /// # use either_both::prelude::*;
352 /// let right: Either<i32, _> = Right(());
353 /// let two = right.unwrap_left();
354 /// ```
355 ///
356 /// ```rust
357 /// # use either_both::prelude::*;
358 /// let both = Both(3, ());
359 /// let three = both.unwrap_left();
360 /// ```
361 #[inline]
362 pub fn unwrap_left(self) -> L {
363 self.expect_left("unwrap_left called on Right")
364 }
365
366 /// Tries to get a left value from `Left`. To include `Both`,
367 /// use [`Either::unwrap_left`].
368 ///
369 /// # Examples
370 ///
371 /// ```rust
372 /// # use either_both::prelude::*;
373 /// let left: Either<_, ()> = Left(1);
374 /// let one = left.unwrap_only_left();
375 /// ```
376 ///
377 /// ```rust,should_panic
378 /// # use either_both::prelude::*;
379 /// let right: Either<i32, _> = Right(());
380 /// let two = right.unwrap_only_left();
381 /// ```
382 ///
383 /// ```rust,should_panic
384 /// # use either_both::prelude::*;
385 /// let both = Both(3, ());
386 /// let three = both.unwrap_only_left();
387 /// ```
388 #[inline]
389 pub fn unwrap_only_left(self) -> L {
390 self.expect_only_left("unwrap_only_left called on Right or Both")
391 }
392
393 /// Tries to get a right value from either `Right` or `Both`. To exclude `Both`,
394 /// use [`Either::unwrap_only_right`].
395 ///
396 /// # Examples
397 ///
398 /// ```rust,should_panic
399 /// # use either_both::prelude::*;
400 /// let left: Either<_, i32> = Left(());
401 /// let one = left.unwrap_right();
402 /// ```
403 ///
404 /// ```rust
405 /// # use either_both::prelude::*;
406 /// let right: Either<(), _> = Right(2);
407 /// let two = right.unwrap_right();
408 /// ```
409 ///
410 /// ```rust
411 /// # use either_both::prelude::*;
412 /// let both = Both((), 3);
413 /// let three = both.unwrap_right();
414 /// ```
415 #[inline]
416 pub fn unwrap_right(self) -> R {
417 self.expect_right("unwrap_right called on Left")
418 }
419
420 /// Tries to get a right value from `Right`. To include `Both`,
421 /// use [`Either::unwrap_right`].
422 ///
423 /// # Examples
424 ///
425 /// ```rust,should_panic
426 /// # use either_both::prelude::*;
427 /// let left: Either<_, i32> = Left(());
428 /// let one = left.unwrap_only_right();
429 /// ```
430 ///
431 /// ```rust
432 /// # use either_both::prelude::*;
433 /// let right: Either<(), _> = Right(2);
434 /// let two = right.unwrap_only_right();
435 /// ```
436 ///
437 /// ```rust,should_panic
438 /// # use either_both::prelude::*;
439 /// let both = Both((), 3);
440 /// let three = both.unwrap_only_right();
441 /// ```
442 #[inline]
443 pub fn unwrap_only_right(self) -> R {
444 self.expect_only_right("unwrap_only_right called on Left or Both")
445 }
446
447 /// Tries to get both left and right values together.
448 ///
449 /// # Examples
450 ///
451 /// ```rust,should_panic
452 /// # use either_both::prelude::*;
453 /// let left: Either<_, i32> = Left(1);
454 /// let (one, two) = left.unwrap_both();
455 /// ```
456 ///
457 /// ```rust,should_panic
458 /// # use either_both::prelude::*;
459 /// let right: Either<i32, _> = Right(4);
460 /// let (three, four) = right.unwrap_both();
461 /// ```
462 ///
463 /// ```rust
464 /// # use either_both::prelude::*;
465 /// let both = Both(5, 6);
466 /// let (five, six) = both.unwrap_both();
467 /// ```
468 #[inline]
469 pub fn unwrap_both(self) -> (L, R) {
470 self.expect_both("unwrap_both called on Left or Right")
471 }
472
473 /// Tries to get the left value, or uses a default value. To unwrap *only* the
474 /// `Left` variant, and exclude `Both`, use
475 /// [`Either::unwrap_only_left_or_default`].
476 pub fn unwrap_left_or_default(self) -> L
477 where
478 L: Default,
479 {
480 match self {
481 Left(l) | Both(l, _) => l,
482 Right(_) => L::default(),
483 }
484 }
485
486 /// Tries to get the left from `Left`, or uses a default value. To also use the left
487 /// value from `Both`, use [`Either::unwrap_left_or_default`].
488 pub fn unwrap_only_left_or_default(self) -> L
489 where
490 L: Default,
491 {
492 match self {
493 Left(l) => l,
494 _ => L::default(),
495 }
496 }
497
498 /// Tries to get the right value, or uses a default value. To unwrap *only* the
499 /// `Right` variant, and exclude `Both`, use
500 /// [`Either::unwrap_only_right_or_default`].
501 pub fn unwrap_right_or_default(self) -> R
502 where
503 R: Default,
504 {
505 match self {
506 Right(r) | Both(_, r) => r,
507 Left(_) => R::default(),
508 }
509 }
510
511 /// Tries to get the right from `Right`, or uses a default value. To also use the
512 /// right value from `Both`, use [`Either::unwrap_right_or_default`].
513 pub fn unwrap_only_right_or_default(self) -> R
514 where
515 R: Default,
516 {
517 match self {
518 Right(r) => r,
519 _ => R::default(),
520 }
521 }
522
523 /// Tries to get both the left and right values, and uses a default value for any
524 /// missing value. To unwrap only `Both`, use [`Either::unwrap_only_both_or_default`].
525 ///
526 /// # Example
527 ///
528 /// ```rust
529 /// # use either_both::prelude::*;
530 /// let left: Either<_, &str> = Left("left");
531 /// assert_eq!(left.unwrap_both_or_default(), ("left", ""));
532 /// let right: Either<&str, _> = Right("right");
533 /// assert_eq!(right.unwrap_both_or_default(), ("", "right"));
534 /// let both = Both("left", "right");
535 /// assert_eq!(both.unwrap_both_or_default(), ("left", "right"));
536 /// ```
537 pub fn unwrap_both_or_default(self) -> (L, R)
538 where
539 L: Default,
540 R: Default,
541 {
542 match self {
543 Left(l) => (l, R::default()),
544 Right(r) => (L::default(), r),
545 Both(l, r) => (l, r),
546 }
547 }
548
549 /// Tries to get both the left and right values. If the variant is not `Both`,
550 /// the default value will be used for both `L` and `R`. To keep the existing
551 /// value in a `Left` or `Right` variant, use [`Either::unwrap_both_or_default`].
552 ///
553 /// # Example
554 ///
555 /// ```rust
556 /// # use either_both::prelude::*;
557 /// let left: Either<_, &str> = Left("left");
558 /// assert_eq!(left.unwrap_only_both_or_default(), ("", ""));
559 /// let right: Either<&str, _> = Right("right");
560 /// assert_eq!(right.unwrap_only_both_or_default(), ("", ""));
561 /// let both = Both("left", "right");
562 /// assert_eq!(both.unwrap_only_both_or_default(), ("left", "right"));
563 /// ```
564 pub fn unwrap_only_both_or_default(self) -> (L, R)
565 where
566 L: Default,
567 R: Default,
568 {
569 match self {
570 Both(l, r) => (l, r),
571 _ => Default::default(),
572 }
573 }
574
575 /// Maps `Either<L, R>` to `Either<L2, R2>` by applying a function to the left
576 /// and right values.
577 ///
578 /// # Example
579 ///
580 /// ```rust
581 /// # use either_both::prelude::*;
582 /// let label: Either<_, i32> = Left("one");
583 /// let value: Either<&str, _> = Right(1);
584 /// let item = Both("one", 1);
585 ///
586 /// assert_eq!(label.map(str::len, |n| n + 2), Left(3));
587 /// assert_eq!(value.map(str::len, |n| n + 2), Right(3));
588 /// assert_eq!(item.map(str::len, |n| n + 2), Both(3, 3));
589 /// ```
590 #[inline]
591 pub fn map<L2, R2, LF, RF>(self, left: LF, right: RF) -> Either<L2, R2>
592 where
593 LF: FnOnce(L) -> L2,
594 RF: FnOnce(R) -> R2,
595 {
596 match self {
597 Left(l) => Left(left(l)),
598 Right(r) => Right(right(r)),
599 Both(l, r) => Both(left(l), right(r)),
600 }
601 }
602
603 /// Maps `Either<L, R>` to `Either<L2, R>` by applying a function to `Left` or
604 /// `Both`.
605 ///
606 /// # Examples
607 ///
608 /// ```rust
609 /// # use either_both::prelude::*;
610 /// let num_or_str: Either<_, &str> = Left(1usize);
611 /// let b: Either<bool, &str> = num_or_str.map_left(|num| num == 1);
612 /// assert_eq!(b, Left(true));
613 /// ```
614 ///
615 /// ```rust
616 /// # use either_both::prelude::*;
617 /// let num_or_str = Both(1usize, "false");
618 /// let b: Either<bool, &str> = num_or_str.map_left(|num| num == 1);
619 /// assert_eq!(b, Both(true, "false"));
620 /// ```
621 #[inline]
622 pub fn map_left<L2, F>(self, f: F) -> Either<L2, R>
623 where
624 F: FnOnce(L) -> L2,
625 {
626 self.map(f, identity)
627 }
628
629 /// Maps `Either<L, R>` to `Either<L2, R>` by applying a function to `Right` or
630 /// `Both`.
631 ///
632 /// # Example
633 ///
634 /// ```rust
635 /// # use either_both::prelude::*;
636 /// let num_or_str: Either<usize, _> = Right("false");
637 /// let b: Either<usize, bool> = num_or_str.map_right(|s| s == "true");
638 /// assert_eq!(b, Right(false));
639 /// ```
640 ///
641 /// ```rust
642 /// # use either_both::prelude::*;
643 /// let num_or_str = Both(1usize, "false");
644 /// let b: Either<usize, bool> = num_or_str.map_right(|s| s == "true");
645 /// assert_eq!(b, Both(1, false));
646 /// ```
647 #[inline]
648 pub fn map_right<R2, F>(self, f: F) -> Either<L, R2>
649 where
650 F: FnOnce(R) -> R2,
651 {
652 self.map(identity, f)
653 }
654
655 /// Calls the left function on the left value and the right function on the right value.
656 /// Returns the original `Either`.
657 ///
658 /// # Example
659 ///
660 /// ```rust
661 /// # use either_both::prelude::*;
662 /// let list = vec![1, 2, 3];
663 /// // NOTE from_options returns an Option<Either<L, R>>
664 /// let sum = Either::from_options(list.get(0), list.get(2))
665 /// .and_then(|either| {
666 /// either
667 /// .inspect(|l| println!("left = {l}"), |r| println!("right = {r}"))
668 /// .both()
669 /// })
670 /// .map(|(l, r)| l + r)
671 /// .expect("list should have indices 0 and 2");
672 /// ```
673 ///
674 pub fn inspect<LF, RF>(self, left: LF, right: RF) -> Self
675 where
676 LF: FnOnce(&L),
677 RF: FnOnce(&R),
678 {
679 match self {
680 Left(ref l) => left(l),
681 Right(ref r) => right(r),
682 Both(ref l, ref r) => {
683 left(l);
684 right(r);
685 }
686 }
687 self
688 }
689
690 /// Calls a function with a reference to the left value. Returns the original
691 /// `Either`.
692 ///
693 /// To call the function on only the `Left` variant, use
694 /// [`Either::inspect_only_left`].
695 ///
696 /// # Example
697 ///
698 /// ```rust
699 /// # use either_both::prelude::*;
700 /// let list = vec![1, 2, 3];
701 /// // NOTE from_options returns an Option<Either<L, R>>
702 /// let first = Either::from_options(list.get(0), list.get(100))
703 /// .and_then(|either| {
704 /// either
705 /// .inspect_left(|l| println!("left = {l}"))
706 /// .left()
707 /// })
708 /// .expect("list should have index 0");
709 /// ```
710 #[inline]
711 pub fn inspect_left<F>(self, f: F) -> Self
712 where
713 F: FnOnce(&L),
714 {
715 self.inspect(f, noop1)
716 }
717
718 /// Calls a function with a reference to the value contained in only the `Left`
719 /// variant. Returns the original `Either`.
720 ///
721 /// To call the function on the `Left` *or* `Both` variant, use
722 /// [`Either::inspect_left`].
723 ///
724 /// # Example
725 ///
726 /// ```rust
727 /// # use either_both::prelude::*;
728 /// let list = vec![1, 2, 3];
729 /// // NOTE from_options returns an Option<Either<L, R>>
730 /// let first = Either::from_options(list.get(0), list.get(100))
731 /// .and_then(|either| {
732 /// either
733 /// .inspect_only_left(|l| println!("left = {l}"))
734 /// .only_left()
735 /// })
736 /// .expect("list should have index 0 and not index 100");
737 /// ```
738 pub fn inspect_only_left<F>(self, f: F) -> Self
739 where
740 F: FnOnce(&L),
741 {
742 if let Left(ref l) = self {
743 f(l);
744 }
745 self
746 }
747
748 /// Calls a function with a reference to the right value. Returns the original
749 /// `Either`.
750 ///
751 /// To call the function on only the `Right` variant, use
752 /// [`Either::inspect_only_right`].
753 ///
754 /// # Example
755 ///
756 /// ```rust
757 /// # use either_both::prelude::*;
758 /// let list = vec![1, 2, 3];
759 /// // NOTE from_options returns an Option<Either<L, R>>
760 /// let last = Either::from_options(list.get(0), list.get(2))
761 /// .and_then(|either| {
762 /// either
763 /// .inspect_right(|r| println!("right = {r}"))
764 /// .right()
765 /// })
766 /// .expect("list should have index 2");
767 /// ```
768 #[inline]
769 pub fn inspect_right<F>(self, f: F) -> Self
770 where
771 F: FnOnce(&R),
772 {
773 self.inspect(noop1, f)
774 }
775
776 /// Calls a function with a reference to the value contained in only the `Right`
777 /// variant. Returns the original `Either`.
778 ///
779 /// To call the function on the `Right` *or* `Both` variant, use
780 /// [`Either::inspect_right`].
781 ///
782 /// # Example
783 ///
784 /// ```rust
785 /// # use either_both::prelude::*;
786 /// let list = vec![1, 2, 3];
787 /// // NOTE from_options returns an Option<Either<L, R>>
788 /// let last = Either::from_options(list.get(100), list.get(2))
789 /// .and_then(|either| {
790 /// either
791 /// .inspect_only_right(|r| println!("right = {r}"))
792 /// .only_right()
793 /// })
794 /// .expect("list shouldn't have index 100 but should have index 2");
795 /// ```
796 pub fn inspect_only_right<F>(self, f: F) -> Self
797 where
798 F: FnOnce(&R),
799 {
800 if let Right(ref r) = self {
801 f(r);
802 }
803 self
804 }
805
806 /// Calls a function with a reference to the left value and a reference to the
807 /// right value contained in (and only in) `Both`.
808 ///
809 /// If you would like to inspect all possible variants, you can chain
810 /// [`Either::inspect_left`] and [`Either::inspect_right`] instead.
811 ///
812 /// # Example
813 ///
814 /// ```rust
815 /// # use either_both::prelude::*;
816 /// let list = vec![1, 2, 3];
817 /// // NOTE from_options returns an Option<Either<L, R>>
818 /// let (first, last) = Either::from_options(list.get(0), list.get(2))
819 /// .and_then(|either| {
820 /// either
821 /// .inspect_both(|l, r| println!("left = {l}, right = {r}"))
822 /// .both()
823 /// })
824 /// .expect("list should have indices 0 and 2");
825 /// ```
826 pub fn inspect_both<F>(self, f: F) -> Self
827 where
828 F: FnOnce(&L, &R),
829 {
830 if let Both(ref l, ref r) = self {
831 f(l, r);
832 }
833 self
834 }
835
836 /// If the left value doesn't exist, it is populated.
837 ///
838 /// # Example
839 ///
840 /// ```rust
841 /// # use either_both::prelude::*;
842 /// let left: Either<u32, u64> = Left(1);
843 /// assert_eq!(left.fill_left(100), Left(1));
844 /// let right: Either<u32, u64> = Right(2);
845 /// assert_eq!(right.fill_left(100), Both(100, 2));
846 /// let both: Either<u32, u64> = Both(3, 4);
847 /// assert_eq!(both.fill_left(100), Both(3, 4));
848 /// ```
849 pub fn fill_left(self, left: L) -> Either<L, R> {
850 match self {
851 Left(l) => Left(l),
852 Right(r) => Both(left, r),
853 Both(l, r) => Both(l, r),
854 }
855 }
856
857 /// If the left value doesn't exist, it is populated.
858 ///
859 /// # Example
860 ///
861 /// ```rust
862 /// # use either_both::prelude::*;
863 /// let left: Either<u32, u64> = Left(1);
864 /// assert_eq!(left.fill_left_lazy(|| 100), Left(1));
865 /// let right: Either<u32, u64> = Right(2);
866 /// assert_eq!(right.fill_left_lazy(|| 100), Both(100, 2));
867 /// let both: Either<u32, u64> = Both(3, 4);
868 /// assert_eq!(both.fill_left_lazy(|| 100), Both(3, 4));
869 /// ```
870 pub fn fill_left_lazy<F>(self, f: F) -> Either<L, R>
871 where
872 F: FnOnce() -> L,
873 {
874 match self {
875 Left(l) => Left(l),
876 Right(r) => Both(f(), r),
877 Both(l, r) => Both(l, r),
878 }
879 }
880
881 /// If the right value doesn't exist, it is populated.
882 ///
883 /// # Example
884 ///
885 /// ```rust
886 /// # use either_both::prelude::*;
887 /// let left: Either<u32, u64> = Left(1);
888 /// assert_eq!(left.fill_right(100), Both(1, 100));
889 /// let right: Either<u32, u64> = Right(2);
890 /// assert_eq!(right.fill_right(100), Right(2));
891 /// let both: Either<u32, u64> = Both(3, 4);
892 /// assert_eq!(both.fill_right(100), Both(3, 4));
893 /// ```
894 pub fn fill_right(self, right: R) -> Either<L, R> {
895 match self {
896 Left(l) => Both(l, right),
897 Right(r) => Right(r),
898 Both(l, r) => Both(l, r),
899 }
900 }
901
902 /// If the right value doesn't exist, it is populated.
903 ///
904 /// # Example
905 ///
906 /// ```rust
907 /// # use either_both::prelude::*;
908 /// let left: Either<u32, u64> = Left(1);
909 /// assert_eq!(left.fill_right_lazy(|| 100), Both(1, 100));
910 /// let right: Either<u32, u64> = Right(2);
911 /// assert_eq!(right.fill_right_lazy(|| 100), Right(2));
912 /// let both: Either<u32, u64> = Both(3, 4);
913 /// assert_eq!(both.fill_right_lazy(|| 100), Both(3, 4));
914 /// ```
915 pub fn fill_right_lazy<F>(self, f: F) -> Either<L, R>
916 where
917 F: FnOnce() -> R,
918 {
919 match self {
920 Left(l) => Both(l, f()),
921 Right(r) => Right(r),
922 Both(l, r) => Both(l, r),
923 }
924 }
925
926 /// Returns `true` if the variant is `Left`. To check if a left value exists (which
927 /// includes `Both`) [`Either::has_left`].
928 ///
929 /// # Example
930 ///
931 /// ```rust
932 /// # use either_both::prelude::*;
933 /// let left: Either<_, ()> = Left(());
934 /// assert!(left.is_left());
935 /// let both = Both((), ());
936 /// assert!(!both.is_left());
937 /// ```
938 #[inline]
939 pub const fn is_left(&self) -> bool {
940 matches!(self, Left(_))
941 }
942
943 /// Returns `true` if the variant is `Right`. To check if a right value exists (which
944 /// includes `Both`) [`Either::has_right`].
945 ///
946 /// ```rust
947 /// # use either_both::prelude::*;
948 /// let right: Either<(), _> = Right(());
949 /// assert!(right.is_right());
950 /// let both = Both((), ());
951 /// assert!(!both.is_right());
952 /// ```
953 #[inline]
954 pub const fn is_right(&self) -> bool {
955 matches!(self, Right(_))
956 }
957
958 /// Returns `true` if the variant is `Both`.
959 #[inline]
960 pub const fn is_both(&self) -> bool {
961 matches!(self, Both(_, _))
962 }
963
964 /// Returns `true` if the variant is `Left` or `Both`. To check for only `Left`,
965 /// use [`Either::is_left`].
966 ///
967 /// ```rust
968 /// # use either_both::prelude::*;
969 /// let left: Either<_, ()> = Left(());
970 /// assert!(left.has_left());
971 /// let both = Both((), ());
972 /// assert!(both.has_left());
973 /// ```
974 #[inline]
975 pub const fn has_left(&self) -> bool {
976 matches!(self, Left(_) | Both(_, _))
977 }
978
979 /// Returns `true` if the variant is `Right` or `Both`. To check for only `Right`,
980 /// use [`Either::is_right`].
981 ///
982 /// ```rust
983 /// # use either_both::prelude::*;
984 /// let right: Either<(), _> = Right(());
985 /// assert!(right.has_right());
986 /// let both = Both((), ());
987 /// assert!(both.has_right());
988 /// ```
989 #[inline]
990 pub const fn has_right(&self) -> bool {
991 matches!(self, Right(_) | Both(_, _))
992 }
993
994 /// Returns `true` if a left value exists and `f` returns `true`. If you want
995 /// to return *`false`* on `Both`, use [`Either::is_left_and`].
996 ///
997 /// # Example
998 ///
999 /// ```rust
1000 /// # use either_both::prelude::*;
1001 /// let left: Either<_, ()> = Left(1);
1002 /// assert!(left.has_left_and(|n| *n == 1));
1003 /// let both = Both(1, ());
1004 /// assert!(both.has_left_and(|n| *n == 1));
1005 /// ```
1006 pub fn has_left_and<F>(&self, f: F) -> bool
1007 where
1008 F: FnOnce(&L) -> bool,
1009 {
1010 match self {
1011 Self::Left(l) | Self::Both(l, _) => f(l),
1012 Self::Right(_) => false,
1013 }
1014 }
1015
1016 /// Returns `true` the variant is `Left` and `f` returns `true`. If you want
1017 /// to allow `Both` to return `true`, use [`Either::has_left_and`].
1018 ///
1019 /// # Example
1020 ///
1021 /// ```rust
1022 /// # use either_both::prelude::*;
1023 /// let left: Either<_, ()> = Left(1);
1024 /// assert!(left.is_left_and(|n| *n == 1));
1025 /// let both = Both(1, ());
1026 /// assert!(!both.is_left_and(|n| *n == 1));
1027 /// ```
1028 pub fn is_left_and<F>(&self, f: F) -> bool
1029 where
1030 F: FnOnce(&L) -> bool,
1031 {
1032 if let Left(l) = self { f(l) } else { false }
1033 }
1034
1035 /// Returns `true` if a right value exists and `f` returns `true`. If you want
1036 /// to return *`false`* on `Both`, use [`Either::is_right_and`].
1037 ///
1038 /// # Example
1039 ///
1040 /// ```rust
1041 /// # use either_both::prelude::*;
1042 /// let right: Either<(), _> = Right(1);
1043 /// assert!(right.has_right_and(|n| *n == 1));
1044 /// let both = Both((), 1);
1045 /// assert!(both.has_right_and(|n| *n == 1));
1046 /// ```
1047 pub fn has_right_and<F>(&self, f: F) -> bool
1048 where
1049 F: FnOnce(&R) -> bool,
1050 {
1051 match self {
1052 Self::Right(r) | Self::Both(_, r) => f(r),
1053 Self::Left(_) => false,
1054 }
1055 }
1056
1057 /// Returns `true` the variant is `Right` and `f` returns `true`. If you want
1058 /// to allow `Both` to return `true`, use [`Either::has_right_and`].
1059 ///
1060 /// # Example
1061 ///
1062 /// ```rust
1063 /// # use either_both::prelude::*;
1064 /// let right: Either<(), _> = Right(1);
1065 /// assert!(right.is_right_and(|n| *n == 1));
1066 /// let both = Both((), 1);
1067 /// assert!(!both.is_right_and(|n| *n == 1));
1068 /// ```
1069 pub fn is_right_and<F>(&self, f: F) -> bool
1070 where
1071 F: FnOnce(&R) -> bool,
1072 {
1073 if let Right(r) = self { f(r) } else { false }
1074 }
1075
1076 /// Returns `true` if both left and right values exist and `f` returns `true`.
1077 ///
1078 /// # Example
1079 ///
1080 /// ```rust
1081 /// # use either_both::prelude::*;
1082 /// let both = Both(1, 2);
1083 /// assert!(both.is_both_and(|a, b| a + b == 3));
1084 /// ```
1085 pub fn is_both_and<F>(&self, f: F) -> bool
1086 where
1087 F: FnOnce(&L, &R) -> bool,
1088 {
1089 if let Both(l, r) = self {
1090 f(l, r)
1091 } else {
1092 false
1093 }
1094 }
1095
1096 /// Returns true if a left value exists, or if the right value passes the predicate
1097 /// `f`.
1098 pub fn has_left_or<F>(&self, f: F) -> bool
1099 where
1100 F: FnOnce(&R) -> bool,
1101 {
1102 match self {
1103 Left(_) | Both(_, _) => true,
1104 Right(r) => f(r),
1105 }
1106 }
1107
1108 /// Returns true if the variant is `Left`, or if the right value passes the predicate
1109 /// `f`.
1110 pub fn is_left_or<F>(&self, f: F) -> bool
1111 where
1112 F: FnOnce(&R) -> bool,
1113 {
1114 match self {
1115 Left(_) => true,
1116 Right(r) | Both(_, r) => f(r),
1117 }
1118 }
1119
1120 /// Returns true if a right value exists, or if the left value passes the predicate
1121 /// `f`.
1122 pub fn has_right_or<F>(&self, f: F) -> bool
1123 where
1124 F: FnOnce(&L) -> bool,
1125 {
1126 match self {
1127 Right(_) | Both(_, _) => true,
1128 Left(l) => f(l),
1129 }
1130 }
1131
1132 /// Returns true if the variant is `Right`, or if the left value passes the predicate
1133 /// `f`.
1134 pub fn is_right_or<F>(&self, f: F) -> bool
1135 where
1136 F: FnOnce(&L) -> bool,
1137 {
1138 match self {
1139 Left(l) | Both(l, _) => f(l),
1140 Right(_) => true,
1141 }
1142 }
1143
1144 /// Swaps the left and right values.
1145 ///
1146 /// ```rust
1147 /// # use either_both::prelude::*;
1148 /// let left: Either<_, ()> = Left('l');
1149 /// assert_eq!(left.swap(), Right('l'));
1150 /// let right: Either<(), _> = Right('r');
1151 /// assert_eq!(right.swap(), Left('r'));
1152 /// let both = Both('l', 'r');
1153 /// assert_eq!(both.swap(), Both('r', 'l'));
1154 /// ```
1155 pub fn swap(self) -> Either<R, L> {
1156 match self {
1157 Left(l) => Right(l),
1158 Right(r) => Left(r),
1159 Both(l, r) => Both(r, l),
1160 }
1161 }
1162
1163 /// Uses a function to fold the left and right values into each other.
1164 /// `default_left` and `default_right` are used where the left value or right
1165 /// value isn't available.
1166 ///
1167 /// If generating `default_left` or `default_right` is an expensive operation,
1168 /// consider using [`Either::fold_with`].
1169 ///
1170 /// # Example
1171 ///
1172 /// ```rust
1173 /// # use either_both::prelude::*;
1174 /// let list = vec![1];
1175 ///
1176 /// let left = Either::from_options(list.first().copied(), list.get(1).copied())
1177 /// .expect("list should have at least one element");
1178 /// let sum = left.fold(100, 2, |l, r| l + r);
1179 /// assert_eq!(sum, 1 + 2);
1180 /// ```
1181 #[inline]
1182 pub fn fold<T, F>(self, default_left: L, default_right: R, f: F) -> T
1183 where
1184 F: FnOnce(L, R) -> T,
1185 {
1186 self.fold_with(|| default_left, || default_right, f)
1187 }
1188
1189 /// Uses a function to fold the left and right values into each other.
1190 /// `default_left` and `default_right` are used where the left value or right
1191 /// value isn't available.
1192 ///
1193 /// # Example
1194 ///
1195 /// ```rust
1196 /// # use either_both::prelude::*;
1197 /// fn expensive_function() -> i32 {
1198 /// 100
1199 /// }
1200 /// let list = vec![1];
1201 ///
1202 /// let left = Either::from_options(list.first().copied(), list.get(1).copied())
1203 /// .expect("list should have at least one element");
1204 /// let sum = left.fold_with(
1205 /// expensive_function,
1206 /// expensive_function,
1207 /// |l, r| l + r,
1208 /// );
1209 /// assert_eq!(sum, 1 + 100);
1210 /// ```
1211 pub fn fold_with<T, F, DLF, DRF>(self, default_left: DLF, default_right: DRF, f: F) -> T
1212 where
1213 F: FnOnce(L, R) -> T,
1214 DLF: FnOnce() -> L,
1215 DRF: FnOnce() -> R,
1216 {
1217 let (left, right) = match self {
1218 Left(l) => (l, default_right()),
1219 Right(r) => (default_left(), r),
1220 Both(l, r) => (l, r),
1221 };
1222 f(left, right)
1223 }
1224
1225 #[inline]
1226 const fn count_usize(&self) -> usize {
1227 if self.is_both() { 2 } else { 1 }
1228 }
1229}
1230
1231impl<L, R> Either<&L, R> {
1232 pub fn left_copied(self) -> Either<L, R>
1233 where
1234 L: Copy,
1235 {
1236 match self {
1237 Left(&l) => Left(l),
1238 Right(r) => Right(r),
1239 Both(&l, r) => Both(l, r),
1240 }
1241 }
1242
1243 #[inline]
1244 pub fn left_cloned(self) -> Either<L, R>
1245 where
1246 L: Clone,
1247 {
1248 self.map_left(|l| l.clone())
1249 }
1250}
1251
1252impl<L, R> Either<L, &R> {
1253 pub fn right_copied(self) -> Either<L, R>
1254 where
1255 R: Copy,
1256 {
1257 match self {
1258 Left(l) => Left(l),
1259 Right(&r) => Right(r),
1260 Both(l, &r) => Both(l, r),
1261 }
1262 }
1263
1264 #[inline]
1265 pub fn right_cloned(self) -> Either<L, R>
1266 where
1267 R: Clone,
1268 {
1269 self.map_right(|r| r.clone())
1270 }
1271}
1272
1273impl<L, R> Either<&L, &R> {
1274 pub const fn copied(self) -> Either<L, R>
1275 where
1276 L: Copy,
1277 R: Copy,
1278 {
1279 match self {
1280 Left(&l) => Left(l),
1281 Right(&r) => Right(r),
1282 Both(&l, &r) => Both(l, r),
1283 }
1284 }
1285
1286 #[inline]
1287 pub fn cloned(self) -> Either<L, R>
1288 where
1289 L: Clone,
1290 R: Clone,
1291 {
1292 self.map(Clone::clone, Clone::clone)
1293 }
1294}
1295
1296impl<L, R> Either<&mut L, R> {
1297 pub fn left_copied(self) -> Either<L, R>
1298 where
1299 L: Copy,
1300 {
1301 match self {
1302 Left(&mut l) => Left(l),
1303 Right(r) => Right(r),
1304 Both(&mut l, r) => Both(l, r),
1305 }
1306 }
1307
1308 #[inline]
1309 pub fn left_cloned(self) -> Either<L, R>
1310 where
1311 L: Clone,
1312 {
1313 self.map_left(|l| l.clone())
1314 }
1315}
1316
1317impl<L, R> Either<L, &mut R> {
1318 pub fn right_copied(self) -> Either<L, R>
1319 where
1320 R: Copy,
1321 {
1322 match self {
1323 Left(l) => Left(l),
1324 Right(&mut r) => Right(r),
1325 Both(l, &mut r) => Both(l, r),
1326 }
1327 }
1328
1329 #[inline]
1330 pub fn right_cloned(self) -> Either<L, R>
1331 where
1332 R: Clone,
1333 {
1334 self.map_right(|r| r.clone())
1335 }
1336}
1337
1338impl<L, R> Either<&mut L, &mut R> {
1339 pub const fn copied(self) -> Either<L, R>
1340 where
1341 L: Copy,
1342 R: Copy,
1343 {
1344 match self {
1345 Left(&mut l) => Left(l),
1346 Right(&mut r) => Right(r),
1347 Both(&mut l, &mut r) => Both(l, r),
1348 }
1349 }
1350
1351 #[inline]
1352 pub fn cloned(self) -> Either<L, R>
1353 where
1354 L: Clone,
1355 R: Clone,
1356 {
1357 self.map(|l| l.clone(), |r| r.clone())
1358 }
1359}
1360
1361impl<L, R> Either<Option<L>, Option<R>> {
1362 /// Converts an `Either<Option<L>, Option<R>>` to an `Option<Either<L, R>>`.
1363 ///
1364 /// # Example
1365 ///
1366 /// ```rust
1367 /// # use either_both::prelude::*;
1368 /// let nothing: Either<Option<()>, Option<()>> = Both(None, None);
1369 /// assert_eq!(nothing.transpose(), None);
1370 /// let left: Either<_, Option<char>> = Left(Some('l'));
1371 /// assert_eq!(left.transpose(), Some(Left('l')));
1372 /// let left: Either<_, Option<char>> = Both(Some('l'), None);
1373 /// assert_eq!(left.transpose(), Some(Left('l')));
1374 /// let both = Both(Some('l'), Some('r'));
1375 /// assert_eq!(both.transpose(), Some(Both('l', 'r')));
1376 /// ```
1377 pub fn transpose(self) -> MaybeEither<L, R> {
1378 match self {
1379 Left(None) | Right(None) | Both(None, None) => None,
1380 Left(Some(l)) | Both(Some(l), None) => Some(Left(l)),
1381 Right(Some(r)) | Both(None, Some(r)) => Some(Right(r)),
1382 Both(Some(l), Some(r)) => Some(Both(l, r)),
1383 }
1384 }
1385}
1386
1387impl<L, EL, R, ER> Either<Result<L, EL>, Result<R, ER>> {
1388 /// Converts an `Either<Result<L, EL>, Result<R, ER>>` to an
1389 /// `Result<Either<L, R>, Either<EL, ER>>`.
1390 ///
1391 /// In the case of mixed results (`Both(ok, err)` or `Both(err, ok)`), `Ok` will
1392 /// be returned if `prefer_ok` is `true`, and `Err` will be returned if `prefer_ok`
1393 /// is `false`.
1394 ///
1395 /// # Example
1396 ///
1397 /// ```rust
1398 /// # use either_both::prelude::*;
1399 /// let ok_left: Either<Result<_, ()>, Result<(), ()>> = Left(Ok(1));
1400 /// assert_eq!(ok_left.transpose(true), Ok(Left(1)));
1401 /// let ok_both: Either<Result<_, ()>, Result<_, ()>> = Both(Ok(3), Ok(4));
1402 /// assert_eq!(ok_both.transpose(true), Ok(Both(3, 4)));
1403 /// let err_left: Either<Result<(), _>, Result<(), ()>> = Left(Err('a'));
1404 /// assert_eq!(err_left.transpose(true), Err(Left('a')));
1405 /// let err_both: Either<Result<(), _>, Result<(), _>> = Both(Err('b'), Err('c'));
1406 /// assert_eq!(err_both.transpose(true), Err(Both('b', 'c')));
1407 ///
1408 /// // The prefer_ok argument is used to decide what to do with mixed results.
1409 /// let mixed_results: Either<Result<bool, _>, Result<_, ()>>
1410 /// = Both(Err("error"), Ok("success"));
1411 /// assert_eq!(mixed_results.transpose(true), Ok(Right("success")));
1412 /// let mixed_results: Either<Result<bool, _>, Result<_, ()>>
1413 /// = Both(Err("error"), Ok("success"));
1414 /// assert_eq!(mixed_results.transpose(false), Err(Left("error")));
1415 /// ```
1416 pub fn transpose(self, prefer_ok: bool) -> Result<Either<L, R>, Either<EL, ER>> {
1417 match self {
1418 Left(Ok(l)) => Ok(Left(l)),
1419 Left(Err(el)) => Err(Left(el)),
1420 Right(Ok(r)) => Ok(Right(r)),
1421 Right(Err(er)) => Err(Right(er)),
1422 Both(Ok(l), Ok(r)) => Ok(Both(l, r)),
1423 Both(Err(el), Err(er)) => Err(Both(el, er)),
1424 Both(Ok(l), Err(er)) => {
1425 if prefer_ok {
1426 Ok(Left(l))
1427 } else {
1428 Err(Right(er))
1429 }
1430 }
1431 Both(Err(el), Ok(r)) => {
1432 if prefer_ok {
1433 Ok(Right(r))
1434 } else {
1435 Err(Left(el))
1436 }
1437 }
1438 }
1439 }
1440}
1441
1442impl<T> Either<T, T> {
1443 /// Gets the total value of the left and/or right values. If only one value exists,
1444 /// it is returned. If both left and right values exist, they are added together.
1445 ///
1446 /// # Example
1447 ///
1448 /// ```rust
1449 /// # use either_both::prelude::*;
1450 /// use std::collections::HashMap;
1451 /// let mut vehicles = HashMap::from([("car", 3usize)]);
1452 /// let total = Either::from_options(vehicles.get("car").copied(), vehicles.get("truck").copied())
1453 /// .map(|either| either.total())
1454 /// .expect("vehicles should have at least one entry");
1455 /// assert_eq!(total, 3);
1456 ///
1457 /// vehicles.insert("truck", 2);
1458 /// let total = Either::from_options(vehicles.get("car").copied(), vehicles.get("truck").copied())
1459 /// .map(|either| either.total())
1460 /// .expect("vehicles should have at least one entry");
1461 /// assert_eq!(total, 3 + 2);
1462 /// ```
1463 pub fn total(self) -> T
1464 where
1465 T: Add<T, Output = T>,
1466 {
1467 match self {
1468 Left(l) => l,
1469 Right(r) => r,
1470 Both(l, r) => l + r,
1471 }
1472 }
1473
1474 /// Creates an iterator that iterates over one or two items. In the case of `Both`,
1475 /// the left value will always be the first item, and the right value will be the
1476 /// second.
1477 ///
1478 /// # Examples
1479 ///
1480 /// ```rust
1481 /// # use either_both::prelude::*;
1482 /// let either: Either<_, char> = Left('l');
1483 /// let mut iter = either.iter();
1484 /// assert_eq!(iter.next(), Some(&'l'));
1485 /// assert_eq!(iter.next(), None);
1486 /// ```
1487 ///
1488 /// ```rust
1489 /// # use either_both::prelude::*;
1490 /// let either: Either<char, _> = Right('r');
1491 /// let mut iter = either.iter();
1492 /// assert_eq!(iter.next(), Some(&'r'));
1493 /// assert_eq!(iter.next(), None);
1494 /// ```
1495 ///
1496 /// ```rust
1497 /// # use either_both::prelude::*;
1498 /// let either = Both('l', 'r');
1499 /// let mut iter = either.iter();
1500 /// assert_eq!(iter.next(), Some(&'l'));
1501 /// assert_eq!(iter.next(), Some(&'r'));
1502 /// assert_eq!(iter.next(), None);
1503 /// ```
1504 pub fn iter(&self) -> Iter<'_, T> {
1505 Iter {
1506 inner: Some(self.as_ref()),
1507 }
1508 }
1509}
1510
1511/// The iterator for [`Either`].
1512pub struct Iter<'a, T> {
1513 inner: MaybeEither<&'a T, &'a T>,
1514}
1515
1516impl<'a, T> Iterator for Iter<'a, T> {
1517 type Item = &'a T;
1518
1519 fn next(&mut self) -> Option<Self::Item> {
1520 match self.inner {
1521 None => None,
1522 Some(Left(v)) | Some(Right(v)) => {
1523 self.inner = None;
1524 Some(v)
1525 }
1526 Some(Both(l, r)) => {
1527 self.inner = Some(Right(r));
1528 Some(l)
1529 }
1530 }
1531 }
1532
1533 fn size_hint(&self) -> (usize, Option<usize>) {
1534 let size = self.inner.as_ref().map(|e| e.count_usize()).unwrap_or(0);
1535 (size, Some(size))
1536 }
1537}
1538
1539impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1540 fn next_back(&mut self) -> Option<Self::Item> {
1541 match self.inner {
1542 None => None,
1543 Some(Left(v)) | Some(Right(v)) => {
1544 self.inner = None;
1545 Some(v)
1546 }
1547 Some(Both(l, r)) => {
1548 self.inner = Some(Left(l));
1549 Some(r)
1550 }
1551 }
1552 }
1553}
1554
1555impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1556
1557impl<'a, T> FusedIterator for Iter<'a, T> {}
1558
1559impl<L, R> From<(L, R)> for Either<L, R> {
1560 /// Converts a tuple of two values to `Both`.
1561 ///
1562 /// # Example
1563 ///
1564 /// ```rust
1565 /// # use either_both::prelude::*;
1566 /// let item = ("Dark mode", true);
1567 /// let label_and_value = Either::from(item);
1568 /// assert_eq!(label_and_value, Both("Dark mode", true));
1569 /// ```
1570 #[inline]
1571 fn from((left, right): (L, R)) -> Self {
1572 Self::Both(left, right)
1573 }
1574}
1575
1576/// Takes one argument and does nothing.
1577#[inline]
1578const fn noop1<T>(_: &T) {}
1579
1580#[cfg(feature = "either")]
1581mod either_interop;
1582
1583#[cfg(test)]
1584mod tests {
1585 use super::*;
1586 use rstest::rstest;
1587
1588 #[rstest]
1589 #[case(Left(()), Some(()))]
1590 #[case(Right(()), None)]
1591 #[case(Both((), ()), Some(()))]
1592 fn test_left(#[case] variant: Either<(), ()>, #[case] expected: Option<()>) {
1593 assert_eq!(variant.left(), expected);
1594 }
1595
1596 #[rstest]
1597 #[case(Left(()), Some(()))]
1598 #[case(Right(()), None)]
1599 #[case(Both((), ()), None)]
1600 fn test_only_left(#[case] variant: Either<(), ()>, #[case] expected: Option<()>) {
1601 assert_eq!(variant.only_left(), expected);
1602 }
1603
1604 #[rstest]
1605 #[case(Left(()), None)]
1606 #[case(Right(()), Some(()))]
1607 #[case(Both((), ()), Some(()))]
1608 fn test_right(#[case] variant: Either<(), ()>, #[case] expected: Option<()>) {
1609 assert_eq!(variant.right(), expected);
1610 }
1611
1612 #[rstest]
1613 #[case(Left(()), None)]
1614 #[case(Right(()), Some(()))]
1615 #[case(Both((), ()), None)]
1616 fn test_only_right(#[case] variant: Either<(), ()>, #[case] expected: Option<()>) {
1617 assert_eq!(variant.only_right(), expected);
1618 }
1619
1620 #[rstest]
1621 #[case(Left(()))]
1622 #[case(Both((), ()))]
1623 fn ok_test_unwrap_left(#[case] either: Either<(), ()>) {
1624 either.unwrap_left()
1625 }
1626
1627 #[test]
1628 fn ok_test_unwrap_only_left() {
1629 let left: Either<_, ()> = Left(());
1630 left.unwrap_only_left()
1631 }
1632
1633 #[rstest]
1634 #[case(Right(()))]
1635 #[case(Both((), ()))]
1636 fn ok_test_unwrap_right(#[case] either: Either<(), ()>) {
1637 either.unwrap_right()
1638 }
1639
1640 #[test]
1641 fn ok_test_unwrap_only_right() {
1642 let right: Either<(), _> = Right(());
1643 right.unwrap_only_right()
1644 }
1645
1646 #[rstest]
1647 #[case(Left(()))]
1648 #[case(Both((), ()))]
1649 fn ok_test_expect_left(#[case] either: Either<(), ()>) {
1650 either.expect_left("left value to exist")
1651 }
1652
1653 #[test]
1654 fn ok_test_expect_only_left() {
1655 let left: Either<_, ()> = Left(());
1656 left.expect_only_left("only left value to exist")
1657 }
1658
1659 #[rstest]
1660 #[case(Right(()))]
1661 #[case(Both((), ()))]
1662 fn ok_test_expect_right(#[case] either: Either<(), ()>) {
1663 either.expect_right("right value to exist")
1664 }
1665
1666 #[test]
1667 fn ok_test_expect_only_right() {
1668 let right: Either<(), _> = Right(());
1669 right.expect_only_right("only right value to exist")
1670 }
1671
1672 #[test]
1673 #[should_panic(expected = "unwrap_left called on Right")]
1674 fn panic_test_unwrap_left() {
1675 let right: Either<(), _> = Right(());
1676 right.unwrap_left()
1677 }
1678
1679 #[rstest]
1680 #[case(Right(()))]
1681 #[case(Both((), ()))]
1682 #[should_panic(expected = "unwrap_only_left called on Right or Both")]
1683 fn panic_test_unwrap_only_left(#[case] either: Either<(), ()>) {
1684 either.unwrap_only_left()
1685 }
1686
1687 #[test]
1688 #[should_panic(expected = "unwrap_right called on Left")]
1689 fn panic_test_unwrap_right() {
1690 let left: Either<_, ()> = Left(());
1691 left.unwrap_right()
1692 }
1693
1694 #[rstest]
1695 #[case(Left(()))]
1696 #[case(Both((), ()))]
1697 #[should_panic(expected = "unwrap_only_right called on Left or Both")]
1698 fn panic_test_unwrap_only_right(#[case] either: Either<(), ()>) {
1699 either.unwrap_only_right()
1700 }
1701
1702 #[test]
1703 #[should_panic(expected = "left value to exist")]
1704 fn panic_test_expect_left() {
1705 let right: Either<(), _> = Right(());
1706 right.expect_left("left value to exist")
1707 }
1708
1709 #[rstest]
1710 #[case(Right(()))]
1711 #[case(Both((), ()))]
1712 #[should_panic(expected = "only left value to exist")]
1713 fn panic_test_expect_only_left(#[case] either: Either<(), ()>) {
1714 either.expect_only_left("only left value to exist")
1715 }
1716
1717 #[test]
1718 #[should_panic(expected = "right value to exist")]
1719 fn panic_test_expect_right() {
1720 let left: Either<_, ()> = Left(());
1721 left.expect_right("right value to exist")
1722 }
1723
1724 #[rstest]
1725 #[case(Left(()))]
1726 #[case(Both((), ()))]
1727 #[should_panic(expected = "only right value to exist")]
1728 fn panic_test_expect_only_right(#[case] either: Either<(), ()>) {
1729 either.expect_only_right("only right value to exist")
1730 }
1731
1732 #[rstest]
1733 #[case(Left(1), Left(1))]
1734 #[case(Right(2), Both(100, 2))]
1735 #[case(Both(1, 2), Both(1, 2))]
1736 fn test_fill_left(#[case] either: Either<u8, u8>, #[case] expected: Either<u8, u8>) {
1737 assert_eq!(either.fill_left(100), expected);
1738 }
1739
1740 #[rstest]
1741 #[case(Left(1), Left(1))]
1742 #[case(Right(2), Both(100, 2))]
1743 #[case(Both(1, 2), Both(1, 2))]
1744 fn test_fill_left_lazy(#[case] either: Either<u8, u8>, #[case] expected: Either<u8, u8>) {
1745 assert_eq!(either.fill_left_lazy(|| 100), expected);
1746 }
1747
1748 #[rstest]
1749 #[case(Left(1), Both(1, 100))]
1750 #[case(Right(2), Right(2))]
1751 #[case(Both(1, 2), Both(1, 2))]
1752 fn test_fill_right(#[case] either: Either<u8, u8>, #[case] expected: Either<u8, u8>) {
1753 assert_eq!(either.fill_right(100), expected);
1754 }
1755
1756 #[rstest]
1757 #[case(Left(1), Both(1, 100))]
1758 #[case(Right(2), Right(2))]
1759 #[case(Both(1, 2), Both(1, 2))]
1760 fn test_fill_right_lazy(#[case] either: Either<u8, u8>, #[case] expected: Either<u8, u8>) {
1761 assert_eq!(either.fill_right_lazy(|| 100), expected);
1762 }
1763
1764 #[rstest]
1765 #[case(Left(()), true)]
1766 #[case(Right(()), false)]
1767 #[case(Both((), ()), false)]
1768 fn test_is_left(#[case] either: Either<(), ()>, #[case] expected: bool) {
1769 assert_eq!(either.is_left(), expected);
1770 }
1771
1772 #[rstest]
1773 #[case(Left(()), false)]
1774 #[case(Right(()), true)]
1775 #[case(Both((), ()), false)]
1776 fn test_is_right(#[case] either: Either<(), ()>, #[case] expected: bool) {
1777 assert_eq!(either.is_right(), expected);
1778 }
1779
1780 #[rstest]
1781 #[case(Left(()), false)]
1782 #[case(Right(()), false)]
1783 #[case(Both((), ()), true)]
1784 fn test_is_both(#[case] either: Either<(), ()>, #[case] expected: bool) {
1785 assert_eq!(either.is_both(), expected);
1786 }
1787
1788 #[rstest]
1789 #[case(Left(()), true)]
1790 #[case(Right(()), false)]
1791 #[case(Both((), ()), true)]
1792 fn test_has_left(#[case] either: Either<(), ()>, #[case] expected: bool) {
1793 assert_eq!(either.has_left(), expected);
1794 }
1795
1796 #[rstest]
1797 #[case(Left(()), false)]
1798 #[case(Right(()), true)]
1799 #[case(Both((), ()), true)]
1800 fn test_has_right(#[case] either: Either<(), ()>, #[case] expected: bool) {
1801 assert_eq!(either.has_right(), expected);
1802 }
1803
1804 #[rstest]
1805 #[case(Left(()), true, false)]
1806 #[case(Right(()), false, true)]
1807 #[case(Both((), ()), true, true)]
1808 fn test_inspect(
1809 #[case] either: Either<(), ()>,
1810 #[case] should_call_left: bool,
1811 #[case] should_call_right: bool,
1812 ) {
1813 let mut left_called = false;
1814 let mut right_called = false;
1815 either.inspect(
1816 |_| {
1817 left_called = true;
1818 },
1819 |_| {
1820 right_called = true;
1821 },
1822 );
1823 assert_eq!(left_called, should_call_left);
1824 assert_eq!(right_called, should_call_right);
1825 }
1826
1827 #[rstest]
1828 #[case(Left(()), true)]
1829 #[case(Right(()), false)]
1830 #[case(Both((), ()), true)]
1831 fn test_inspect_left(#[case] either: Either<(), ()>, #[case] should_call: bool) {
1832 let mut called = false;
1833 either.inspect_left(|_| {
1834 called = true;
1835 });
1836 assert_eq!(called, should_call);
1837 }
1838
1839 #[rstest]
1840 #[case(Left(()), true)]
1841 #[case(Right(()), false)]
1842 #[case(Both((), ()), false)]
1843 fn test_inspect_only_left(#[case] either: Either<(), ()>, #[case] should_call: bool) {
1844 let mut called = false;
1845 either.inspect_only_left(|_| {
1846 called = true;
1847 });
1848 assert_eq!(called, should_call);
1849 }
1850
1851 #[rstest]
1852 #[case(Left(()), false)]
1853 #[case(Right(()), true)]
1854 #[case(Both((), ()), true)]
1855 fn test_inspect_right(#[case] either: Either<(), ()>, #[case] should_call: bool) {
1856 let mut called = false;
1857 either.inspect_right(|_| {
1858 called = true;
1859 });
1860 assert_eq!(called, should_call);
1861 }
1862
1863 #[rstest]
1864 #[case(Left(()), false)]
1865 #[case(Right(()), true)]
1866 #[case(Both((), ()), false)]
1867 fn test_inspect_only_right(#[case] either: Either<(), ()>, #[case] should_call: bool) {
1868 let mut called = false;
1869 either.inspect_only_right(|_| {
1870 called = true;
1871 });
1872 assert_eq!(called, should_call);
1873 }
1874
1875 #[rstest]
1876 #[case(Left(()), false)]
1877 #[case(Right(()), false)]
1878 #[case(Both((), ()), true)]
1879 fn test_inspect_both(#[case] either: Either<(), ()>, #[case] should_call: bool) {
1880 let mut called = false;
1881 either.inspect_both(|_, _| {
1882 called = true;
1883 });
1884 assert_eq!(called, should_call);
1885 }
1886}