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