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