Either

Enum Either 

Source
pub enum Either<L, R = L> {
    Left(L),
    Right(R),
}
Available on crate feature either only.
Expand description

Represent values with two possibilities. Either can be either Left or Right

Variants§

§

Left(L)

Represent a left value

§

Right(R)

Represent a right value

Implementations§

Source§

impl<L, R> Either<L, R>

Source

pub const fn is_left(&self) -> bool

Returns true if Either is a Left value.

§Examples
use either_or_both::Either;

let either = Either::<u8>::Left(1);
assert_eq!(either.is_left(), true);

let either = Either::<u8>::Right(1);
assert_eq!(either.is_left(), false);
Source

pub fn is_left_and<F>(self, f: F) -> bool
where F: FnOnce(L) -> bool,

Returns true if Either is Left and the contained value matches a predicate

§Examples
use either_or_both::Either;

let either: Either<u8> = Either::Left(1);
assert_eq!(either.is_left_and(|l| l == 1), true);

let either: Either<u8> = Either::Left(1);
assert_eq!(either.is_left_and(|l| l == 2), false);

let either: Either<u8> = Either::Right(1);
assert_eq!(either.is_left_and(|l| l == 1), false);
Source

pub fn is_left_or<F>(self, f: F) -> bool
where F: FnOnce(R) -> bool,

Returns true if Either is Left or the Right value matches a predicate

§Examples
use either_or_both::Either;

let either: Either<u8, char> = Either::Left(1);
assert_eq!(either.is_left_or(|r| r == 'c'), true);

let either: Either<u8, char> = Either::Right('c');
assert_eq!(either.is_left_or(|r| r == 'c'), true);

let either: Either<u8, char> = Either::Right('c');
assert_eq!(either.is_left_or(|r| r == 'm'), false);
Source

pub const fn is_right(&self) -> bool

Returns true if Either is a Right value.

§Examples
use either_or_both::Either;

let either = Either::<u8, char>::Right('c');
assert_eq!(either.is_right(), true);

let either = Either::<u8, char>::Left(1);
assert_eq!(either.is_right(), false);
Source

pub fn is_right_and<F>(self, f: F) -> bool
where F: FnOnce(R) -> bool,

Returns true if Either is Right and the contained value matches a predicate

§Examples
use either_or_both::Either;

let either: Either<u8, char> = Either::Right('c');
assert_eq!(either.is_right_and(|r| r == 'c'), true);

let either: Either<u8, char> = Either::Right('c');
assert_eq!(either.is_right_and(|r| r == 'm'), false);

let either: Either<u8, char> = Either::Left(1);
assert_eq!(either.is_right_and(|r| r == 'c'), false);
Source

pub fn is_right_or<F>(self, f: F) -> bool
where F: FnOnce(L) -> bool,

Returns true if Either is Right or the Left value matches a predicate

§Examples
use either_or_both::Either;

let either: Either<u8, char> = Either::Right('c');
assert_eq!(either.is_right_or(|l| l == 1), true);

let either: Either<u8, char> = Either::Left(1);
assert_eq!(either.is_right_or(|l| l == 1), true);

let either: Either<u8, char> = Either::Left(2);
assert_eq!(either.is_right_or(|l| l == 1), false);
Source

pub const fn as_ref(&self) -> Either<&L, &R>

Converts from &Either<L, R> to Either<&L, &R>.

§Examples

Calculate the length of the strings without moving the Strings.

use either_or_both::Either;

let text: Either<String> = Either::Left("left value".to_owned());

// Cast `Either<String>` to `Either<&String>` and then apply a map consuming the
// result of `as_ref` instead of `text` itself
let length: Either<usize> = text.as_ref().map(String::len);
assert_eq!(length, Either::Left(10));

println!("`text` has not been moved: {:?}", &text);
Source

pub fn as_mut(&mut self) -> Either<&mut L, &mut R>

Converts from &mut Either<L, R> to Either<&mut L, &mut R>.

§Examples
use either_or_both::Either;

let mut either: Either<u8, char> = Either::Left(1);

match either.as_mut() {
    Either::Left(left) => *left = 3,
    Either::Right(right) => *right = 'x',
}

assert_eq!(either, Either::Left(3))
Source

pub fn as_deref(&self) -> Either<&<L as Deref>::Target, &<R as Deref>::Target>
where L: Deref, R: Deref,

Converts from Either<L, R> to Either<&L::Target, &R::Target>.

This method keeps the original Either unchanged, while creating a new instance that holds a reference to the original. It also coerces the inner values through the Deref trait.

use either_or_both::Either;

let values: Either<String> = Either::Left("left".to_owned());
let deref: Either<&str> = values.as_deref();
assert_eq!(deref.left(), Some("left"));
Source

pub fn as_deref_mut( &mut self, ) -> Either<&mut <L as Deref>::Target, &mut <R as Deref>::Target>
where L: DerefMut, R: DerefMut,

Converts from Either<L, R> to Either<&mut L::Target, &mut R::Target>.

This method keeps the original Either unchanged, while creating a new instance that holds a mutable reference to the inner type’s Deref::Target type.

use either_or_both::Either;

let mut value: Either<String> = Either::Left("left".to_owned());
let upper_case: Either<&mut str> = value.as_deref_mut().map(|v| {
    v.make_ascii_uppercase();
    v
});

assert_eq!(upper_case.left(), Some("LEFT".to_owned().as_mut_str()));
Source

pub fn as_pin_ref(self: Pin<&Self>) -> Either<Pin<&L>, Pin<&R>>

Converts from Pin<&Either<L, R>> to Either<Pin<&L>, Pin<&R>>.

Source

pub fn as_pin_mut(self: Pin<&mut Self>) -> Either<Pin<&mut L>, Pin<&mut R>>

Converts from Pin<&mut Either<L, R>> to Either<Pin<&mut L>, Pin<&mut R>>.

Source

pub fn expect_left(self, msg: &str) -> L

Returns the contained left value consuming self.

§Panics

Panics with a custom panic message provided by msg if there is no left value present

§Examples
use either_or_both::Either;

let value: Either<&str> = Either::Left("left");
assert_eq!(value.expect_left("should be left"), "left");

This example panics with the message should be left

use either_or_both::Either;

let value: Either<&str> = Either::Right("right");
value.expect_left("should be left");
Source

pub fn expect_right(self, msg: &str) -> R

Returns the contained right value consuming self.

§Panics

Panics with a custom panic message provided by msg if there is no right value present

§Examples
use either_or_both::Either;

let value: Either<&str> = Either::Right("right");
assert_eq!(value.expect_right("should be right"), "right");

The following example panics with the message should be right

use either_or_both::Either;

let value: Either<&str> = Either::Left("left");
value.expect_right("should be right");
Source

pub fn unwrap_left(self) -> L

Returns the contained left value consuming self.

§Panics

Panics if Either is a Right variant

§Examples
use either_or_both::Either;

let value: Either<&str> = Either::Left("left");
assert_eq!(value.unwrap_left(), "left");
use either_or_both::Either;

let value: Either<&str> = Either::Right("right");
value.unwrap_left(); // panics
Source

pub unsafe fn unwrap_left_unchecked(self) -> L

Returns the contained left value consuming self, without checking that the value is not Left.

§SAFETY

Calling this method on a Right variant is undefined behavior.

§Examples
use either_or_both::Either;

let value: Either<&str> = Either::Left("left");
assert_eq!(unsafe { value.unwrap_left_unchecked() }, "left");

The following example introduces undefined behavior

use either_or_both::Either;

let value: Either<&str> = Either::Right("right");
assert_eq!(unsafe { value.unwrap_left_unchecked() }, "left");
Source

pub fn unwrap_right(self) -> R

Returns the contained right value consuming self.

§Panics

Panics if Either is a Left variant

§Examples
use either_or_both::Either;

let value: Either<&str> = Either::Right("right");
assert_eq!(value.unwrap_right(), "right");
use either_or_both::Either;

let value: Either<&str> = Either::Left("left");
value.unwrap_right(); // panics
Source

pub unsafe fn unwrap_right_unchecked(self) -> R

Returns the contained right value consuming self, without checking that the value is not Right.

§SAFETY

Calling this method on a Left variant is undefined behavior.

§Examples
use either_or_both::Either;

let value: Either<&str> = Either::Right("right");
assert_eq!(unsafe { value.unwrap_right_unchecked() }, "right");

The following example introduces undefined behavior

use either_or_both::Either;

let value: Either<&str> = Either::Left("left");
assert_eq!(unsafe { value.unwrap_right_unchecked() }, "right");
Source

pub fn left(self) -> Option<L>

If a left value is present, return Some containing the value otherwise return None.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.left(), Some(1));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.left(), None);
Source

pub fn left_and<T>(self, other: Either<T, R>) -> Either<T, R>

Returns Right if the Either is Right otherwise returns other.

The left_and combinator eagerly evaluates its arguments, which can result in unnecessary computations. When chaining operations that involve function calls, use left_and_then instead. It evaluates the function lazily.

§Examples
use either_or_both::Either;

let x: Either<u8, char> = Either::Left(1);
let y: Either<&str, char> = Either::Left("left");
assert_eq!(x.left_and(y), Either::Left("left"));

let x: Either<u8, char> = Either::Right('c');
let y: Either<&str, char> = Either::Left("left");
assert_eq!(x.left_and(y), Either::Right('c'));
Source

pub fn left_and_then<F, T>(self, f: F) -> Either<T, R>
where F: FnOnce(L) -> Either<T, R>,

Returns Right otherwise calls f with the left value and returns the result.

§Examples
use either_or_both::Either;

fn left_to_string(x: u8) -> Either<String, char> {
    Either::Left(x.to_string())
}

let x: Either<u8, char> = Either::Left(1);
assert_eq!(x.left_and_then(left_to_string), Either::Left(1.to_string()));

let x: Either<u8, char> = Either::Right('c');
assert_eq!(x.left_and_then(left_to_string), Either::Right('c'));
Source

pub fn right(self) -> Option<R>

If a left value is present, return Some containing the value otherwise return None.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.right(), Some('c'));

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.right(), None);
Source

pub fn right_and<T>(self, other: Either<L, T>) -> Either<L, T>

Returns Left if the Either is Left otherwise returns other.

The right_and combinator eagerly evaluates its arguments, which can result in unnecessary computations. When chaining operations that involve function calls, use right_and_then instead. It evaluates the function lazily.

§Examples
use either_or_both::Either;

let x: Either<u8, char> = Either::Right('c');
let y: Either<u8, &str> = Either::Right("right");
assert_eq!(x.right_and(y), Either::Right("right"));

let x: Either<u8, char> = Either::Left(1);
let y: Either<u8, &str> = Either::Right("right");
assert_eq!(x.right_and(y), Either::Left(1));
Source

pub fn right_and_then<F, T>(self, f: F) -> Either<L, T>
where F: FnOnce(R) -> Either<L, T>,

Returns Left otherwise calls f with the right value and returns the result.

§Examples
use either_or_both::Either;

fn right_to_string(x: char) -> Either<u8, String> {
    Either::Right(x.to_string())
}

let x: Either<u8, char> = Either::Right('c');
assert_eq!(
    x.right_and_then(right_to_string),
    Either::Right('c'.to_string())
);

let x: Either<u8, char> = Either::Left(1);
assert_eq!(x.right_and_then(right_to_string), Either::Left(1));
Source

pub fn into_iter_swap( self, ) -> SwapIterEither<<L as IntoIterator>::IntoIter, <R as IntoIterator>::IntoIter>

Consumes the inner iterators and returns an iterator that yields items of type Either<L, R>.

This iterator allows traversing inner iterators with different types

§Examples
use either_or_both::Either;

let x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
let mut iter = x.into_iter_swap(); // moves `x` and the iterators

assert_eq!(iter.next(), Some(Either::Left(1)));
assert_eq!(iter.next(), Some(Either::Left(2)));
assert_eq!(iter.next(), None);
Source

pub fn iter_swap( &self, ) -> SwapIterEither<<&L as IntoIterator>::IntoIter, <&R as IntoIterator>::IntoIter>
where for<'a> &'a L: IntoIterator, for<'a> &'a R: IntoIterator,

Borrow the inner iterators and returns an iterator that yields items of type Either<&L, &R>.

This iterator allows traversing inner iterators with different types

§Examples
use either_or_both::Either;

let x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
let mut iter = x.iter_swap();

assert_eq!(iter.next(), Some(Either::Left(&1)));
assert_eq!(iter.next(), Some(Either::Left(&2)));
assert_eq!(iter.next(), None);

println!("{x:?}"); // still can access `x`
Source

pub fn iter_swap_mut( &mut self, ) -> SwapIterEither<<&mut L as IntoIterator>::IntoIter, <&mut R as IntoIterator>::IntoIter>
where for<'a> &'a mut L: IntoIterator, for<'a> &'a mut R: IntoIterator,

Mutably borrows the inner iterators returning an iterator that yields items of type Either<&mut L, &mut R>.

This iterator allows traversing inner iterators with different types

§Examples
use either_or_both::Either;

let mut x: Either<_, Vec<char>> = Either::Left(vec![1, 2]);
let mut iter = x.iter_swap_mut();

assert_eq!(iter.next(), Some(Either::Left(&mut 1)));
assert_eq!(iter.next(), Some(Either::Left(&mut 2)));
assert_eq!(iter.next(), None);

println!("{x:?}"); // still can access `x`
Source

pub fn flip(self) -> Either<R, L>

Converts Either<L, R> to Either<R, L>.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.flip(), Either::Right(1));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.flip(), Either::Left('c'));
Source

pub fn bimap<F, G, T, U>(self, f: F, g: G) -> Either<T, U>
where F: FnOnce(L) -> T, G: FnOnce(R) -> U,

Applies mapping functions to the left and right values returning an Either<T, U>.

§Examples
use either_or_both::Either;

let map_left = |left: u8| left.to_string();
let map_right = |right: char| right as i32;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(
    value.bimap(map_left, map_right),
    Either::Left("1".to_owned())
);

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.bimap(map_left, map_right), Either::Right(99));
Source

pub fn map_left<F, T>(self, f: F) -> Either<T, R>
where F: FnOnce(L) -> T,

Applies a mapping function to the left value returning an Either<T, R>.

§Examples
use either_or_both::Either;

let map_left = |left: u8| left.to_string();

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.map_left(map_left), Either::Left("1".to_owned()));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.map_left(map_left), Either::Right('c'));
Source

pub fn map_left_or<F, T>(self, default: T, f: F) -> T
where F: FnOnce(L) -> T,

Returns the provided default value if this is a Right or applies a mapping function to the contained left value.

The map_left_or combinator eagerly evaluates its arguments, which can result in unnecessary computations. When chaining operations that involve function calls, use map_left_or_else instead. It evaluates the function lazily.

§Examples
use either_or_both::Either;

let map_left = |left: u8| left as u64 + 1;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.map_left_or(42, map_left), 42u64);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.map_left_or(42, map_left), 2u64);
Source

pub fn map_left_or_default<F, T>(self, f: F) -> T
where F: FnOnce(L) -> T, T: Default,

Applies the given function to the left value , mapping L to T otherwise returns the default value for type T.

§Examples
use either_or_both::Either;

let map_left = |left: u8| left as u64 + 1;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.map_left_or_default(map_left), 0u64);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.map_left_or_default(map_left), 2u64);
Source

pub fn map_left_or_else<D, F, T>(self, default: D, f: F) -> T
where F: FnOnce(L) -> T, D: FnOnce() -> T,

Applies the given function to the left value, mapping L to T otherwise applies a different function.

§Examples
use either_or_both::Either;

let map_left = |left: u8| left.to_string();

let value: Either<u8, char> = Either::Right('c');
assert_eq!(
    value.map_left_or_else(|| String::from("left"), map_left),
    String::from("left")
);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(
    value.map_left_or_else(|| String::from("left"), map_left),
    1.to_string()
);
Source

pub fn map_right<F, T>(self, f: F) -> Either<L, T>
where F: FnOnce(R) -> T,

Applies a mapping function to the right value returning an Either<L, T>.

§Examples
use either_or_both::Either;

let map_right = |right: char| right.to_string();

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.map_right(map_right), Either::Right("c".to_owned()));

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.map_right(map_right), Either::Left(1));
Source

pub fn map_right_or<F, T>(self, default: T, f: F) -> T
where F: FnOnce(R) -> T,

Returns the provided default value if this is a Left or applies a mapping function to the contained right value.

The map_right_or combinator eagerly evaluates its arguments, which can result in unnecessary computations. When chaining operations that involve function calls, use map_right_or_else instead. It evaluates the function lazily.

§Examples
use either_or_both::Either;

let map_right = |right: char| right as i32;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.map_right_or(42, map_right), 99i32);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.map_right_or(42, map_right), 42i32);
Source

pub fn map_right_or_default<F, T>(self, f: F) -> T
where F: FnOnce(R) -> T, T: Default,

Applies the given function to the right value, mapping R to T otherwise returns the default value for type T.

§Examples
use either_or_both::Either;

let map_right = |right: char| right as u64 + 1;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.map_right_or_default(map_right), 100u64);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.map_right_or_default(map_right), 0u64);
Source

pub fn map_right_or_else<D, F, T>(self, default: D, f: F) -> T
where F: FnOnce(R) -> T, D: FnOnce() -> T,

Applies the given function to the right value, mapping R to T otherwise applies a different function.

§Examples
use either_or_both::Either;

let map_right = |right: char| right.to_string();

let value: Either<u8, char> = Either::Right('c');
assert_eq!(
    value.map_right_or_else(|| String::from("right"), map_right),
    "c".to_owned()
);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(
    value.map_right_or_else(|| String::from("right"), map_right),
    String::from("right")
);
Source

pub fn biinspect<F, G>(self, f: F, g: G) -> Self
where for<'a> F: Fn(&'a L), for<'a> G: Fn(&'a R),

Calls functions with a reference to the contained values returning the original Either.

§Examples
use either_or_both::Either;

// Prints a single line with "Left is: 1"
let value: Either<u8, char> = Either::Left(1);
let left = value
    .biinspect(|l| println!("Left is: {l}"), |r| println!("Right is: {r}"))
    .expect_left("should be a left value");
assert_eq!(left, 1);

// Prints a single line with "Right is: c"
let value: Either<u8, char> = Either::Right('c');
let right = value
    .biinspect(|l| println!("Left is: {l}"), |r| println!("Right is: {r}"))
    .expect_right("should be a right value");
assert_eq!(right, 'c');
Source

pub fn inspect_left<F>(self, f: F) -> Self
where for<'a> F: Fn(&'a L),

Calls a function with a reference to the contained left value returning the original Either.

§Examples
use either_or_both::Either;

// Prints a single line with "Left is: 1"
let value: Either<u8, char> = Either::Left(1);
let left = value
    .inspect_left(|l| println!("Left is: {l}"))
    .expect_left("should be a left value");
assert_eq!(left, 1);

// Prints nothing
let value: Either<u8, char> = Either::Right('c');
let right = value
    .inspect_left(|l| println!("Left is: {l}"))
    .expect_right("should be a right value");
assert_eq!(right, 'c');
Source

pub fn inspect_right<F>(self, f: F) -> Self
where for<'a> F: Fn(&'a R),

Calls a function with a reference to the contained right value returning the original Either.

§Examples
use either_or_both::Either;

// Prints a single line with "Right is: c"
let value: Either<u8, char> = Either::Right('c');
let right = value
    .inspect_right(|r| println!("Right is: {r}"))
    .expect_right("should be a right value");
assert_eq!(right, 'c');

// Prints nothing
let value: Either<u8, char> = Either::Left(1);
let left = value
    .inspect_right(|r| println!("Right is: {r}"))
    .expect_left("should be a left value");
assert_eq!(left, 1);
Source

pub fn biapply<F, G>(self, f: F, g: G)
where F: FnMut(L), G: FnMut(R),

Consumes this Either applying functions to the contained values taking mutable references to capture variables.

§Examples
use either_or_both::Either;

let mut left = vec![];
let mut right = vec![];

let value: Either<u8, char> = Either::Left(1);
value.biapply(|l| left.push(l), |r| right.push(r)); // moves `value`

assert_eq!(left, vec![1]);

The following example will not compile with the error: “cannot borrow both as mutable more than once at a time”.

If you need to apply a function that requires mutable access to both elements simultaneously, consider using biapply_with instead.

use either_or_both::Either;

let mut both = vec![];

let value: Either<u8, char> = Either::Both(1, 'c');
value.biapply(|l| both.push(l), |r| both.push(r as u8));
Source

pub fn biapply_with<F, G, Acc>(self, acc: Acc, f: F, g: G)
where F: FnMut(Acc, L), G: FnMut(Acc, R),

Consumes this Either applying functions to the contained values and a given accumulator.

§Examples
use either_or_both::Either;

let mut both = vec![];

let value: Either<u8, char> = Either::Left(1);
value.biapply_with(&mut both, |acc, l| acc.push(l), |acc, r| acc.push(r as u8));

let value: Either<u8, char> = Either::Right('c');
value.biapply_with(&mut both, |acc, l| acc.push(l), |acc, r| acc.push(r as u8));

assert_eq!(both, vec![1, 99]);
Source

pub fn apply_left<F>(self, f: F)
where F: FnMut(L),

Consumes this Either applying a function to the contained left value.

§Examples
use either_or_both::Either;

let mut left = vec![];
let value: Either<u8, char> = Either::Left(1);
value.apply_left(|l| left.push(l));
assert_eq!(left, vec![1]);

let mut left = vec![];
let value: Either<u8, char> = Either::Right('c');
value.apply_left(|l| left.push(l));
assert_eq!(left.is_empty(), true);
Source

pub fn apply_right<F>(self, f: F)
where F: FnMut(R),

Consumes this Either applying a function to the contained right value.

§Examples
use either_or_both::Either;

let mut right = vec![];
let value: Either<u8, char> = Either::Right('c');
value.apply_right(|r| right.push(r));
assert_eq!(right, vec!['c']);

let mut right = vec![];
let value: Either<u8, char> = Either::Left(1);
value.apply_right(|r| right.push(r));
assert_eq!(right.is_empty(), true);
Source

pub fn bireduce<F, G, T>(self, f: F, g: G) -> T
where F: FnOnce(L) -> T, G: FnOnce(R) -> T,

Returns the contained values applying a mapping function which converts the L and R values to a uniform type.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(
    value.bireduce(|l| l.to_string(), |r| r.to_string()),
    "1".to_owned()
);

let value: Either<u8, char> = Either::Right('c');
assert_eq!(
    value.bireduce(|l| l.to_string(), |r| r.to_string()),
    "c".to_owned()
);
Source

pub fn reduce_left<F>(self, f: F) -> L
where F: FnOnce(R) -> L,

Returns the left value otherwise applies a function to a Right variant, converting it into an L value.

§Example
use either_or_both::Either;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.reduce_left(|r| r as u8), 99);

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.reduce_left(|r| r as u8), 1);
Source

pub fn reduce_right<F>(self, f: F) -> R
where F: FnOnce(L) -> R,

Returns the right value otherwise applies a function to a Left variant, converting it into an R value.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.reduce_right(|l| l as char), 'c');

let value: Either<u8, char> = Either::Left(0);
assert_eq!(value.reduce_right(|l| l as char), '\0');
Source

pub fn ok(self) -> Result<R, L>

Transforms the Either<L, R> into a Result<R, L>.

Following the convention, the left value represents an error and a right value represents a correct value.

§Examples
use either_or_both::Either;

let value: Either<&str, u8> = Either::Right(1);
assert_eq!(value.ok(), Ok(1));

let value: Either<&str, u8> = Either::Left("this is an error");
assert_eq!(value.ok(), Err("this is an error"));
Source

pub fn ok_or<E>(self, error: E) -> Result<R, E>

Transforms the Either<L, R> into a Result<R, L> using the provided error as error value.

Following the convention, the left value represents an error and a right value represents a correct value.

The ok_or combinator eagerly evaluates its arguments, which can result in unnecessary computations. When chaining operations that involve function calls, use ok_or_else instead. It evaluates the function lazily.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.ok_or("error message"), Ok('c'));

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.ok_or("error message"), Err("error message"));
Source

pub fn ok_or_else<F, E>(self, error: F) -> Result<R, E>
where F: FnOnce() -> E,

Transforms the Either<L, R> into a Result<R, L> using the result of an error function as error value.

Following the convention, the left value represents an error and a right value represents a correct value.

The ok_or combinator eagerly evaluates its arguments, which can result in unnecessary computations. When chaining operations that involve function calls, use ok_or_else instead. It evaluates the function lazily.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.ok_or_else(|| String::from("error message")), Ok('c'));

let value: Either<u8, char> = Either::Left(1);
assert_eq!(
    value.ok_or_else(|| String::from("error message")),
    Err(String::from("error message"))
);
Source

pub fn or(self, left: L, right: R) -> (L, R)

Returns a tuple (L, R) with the provided values filling in any missing left or right value.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.or(2, 'm'), (1, 'm'));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.or(2, 'm'), (2, 'c'));
Source

pub fn or_default(self) -> (L, R)
where L: Default, R: Default,

Returns a tuple (L, R) where any missing left or right value is replaced with its respective default value.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.or_default(), (1, '\0'));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.or_default(), (0, 'c'));
Source

pub fn or_else<F, G>(self, f: F, g: G) -> (L, R)
where F: FnOnce() -> L, G: FnOnce() -> R,

Returns a tuple (L, R) where any missing left or right value is computed with the given functions.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.or_else(|| 1 + 1, || char::from(100)), (1, 'd'));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.or_else(|| 1 + 1, || char::from(100)), (2, 'c'));
Source

pub fn inject_left(self, left: L) -> EitherOrBoth<L, R>

Inserts left into the Either consuming it and returning an EitherOrBoth

§Examples
use either_or_both::{Either, EitherOrBoth};

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.inject_left(2), EitherOrBoth::Left(2));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.inject_left(1), EitherOrBoth::Both(1, 'c'));
Source

pub fn inject_right(self, right: R) -> EitherOrBoth<L, R>

Inserts right into the Either consuming it and returning an EitherOrBoth

§Examples
use either_or_both::{Either, EitherOrBoth};

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.inject_right('m'), EitherOrBoth::Right('m'));

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.inject_right('m'), EitherOrBoth::Both(1, 'm'));
Source

pub fn into_left<F>(self, f: F) -> Self
where F: FnOnce(R) -> L,

Converts into a Left variant, using the contained left value or applying a mapping function to the Right value.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
assert_eq!(value.into_left(|r| r as u8), Either::Left(1));

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.into_left(|r| r as u8), Either::Left(99));
Source

pub fn into_right<F>(self, f: F) -> Self
where F: FnOnce(L) -> R,

Converts into a Right variant, using the contained right value or applying a mapping function to the Left value.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Right('c');
assert_eq!(value.into_right(|l| l as char), Either::Right('c'));

let value: Either<u8, char> = Either::Left(0);
assert_eq!(value.into_right(|l| l as char), Either::Right('\0'));
Source

pub fn replace_left(&mut self, value: L) -> Option<L>

Replaces the left value returning the old value if present

§Examples
use either_or_both::Either;

let mut value: Either<u8, char> = Either::Left(1);
let old = value.replace_left(2);
assert_eq!(old, Some(1));
assert_eq!(value, Either::Left(2));

let mut value: Either<u8, char> = Either::Right('c');
let old = value.replace_left(2);
assert_eq!(old, None);
assert_eq!(value, Either::Right('c'));
Source

pub fn replace_right(&mut self, value: R) -> Option<R>

Replaces the right value returning the old value if present

§Examples
use either_or_both::Either;

let mut value: Either<u8, char> = Either::Right('c');
let old = value.replace_right('m');
assert_eq!(old, Some('c'));
assert_eq!(value, Either::Right('m'));

let mut value: Either<u8, char> = Either::Left(1);
let old = value.replace_right('m');
assert_eq!(old, None);
assert_eq!(value, Either::Left(1));
Source§

impl<T> Either<T, T>

Source

pub fn apply<F>(self, f: F)
where F: FnMut(T),

Consumes this Either applying a function to the contained value (of a uniform type) taking mutable references to capture variables.

§Examples
use either_or_both::Either;

let mut both = vec![];

let value: Either<char> = Either::Left('c');
value.apply(|c| both.push(c));

let value: Either<char> = Either::Right('a');
value.apply(|c| both.push(c));

assert_eq!(both, vec!['c', 'a']);
Source

pub fn inspect<F>(self, f: F) -> Self
where for<'a> F: Fn(&'a T),

Calls a function with a reference to the contained value (of a uniform type) returning the original Either.

§Examples
use either_or_both::Either;

// Prints a single line with "The value is: c"
let value: Either<char> = Either::Left('c');
let left = value
    .inspect(|c| println!("The value is: {c}"))
    .expect_left("should be a left value");
assert_eq!(left, 'c');

// Prints a single line with "The value is: a"
let value: Either<char> = Either::Right('a');
let right = value
    .inspect(|c| println!("The value is: {c}"))
    .expect_right("should be a right value");

assert_eq!(right, 'a');
Source

pub fn iter(&self) -> IterEither<'_, T>

Returns an iterator over the contained value of a uniform type

§Examples
use either_or_both::EitherOrBoth;

let value: EitherOrBoth<char> = EitherOrBoth::Left('c');
let mut iter = value.iter();
assert_eq!(iter.next(), Some(&'c'));
assert_eq!(iter.next(), None);

let value: EitherOrBoth<char> = EitherOrBoth::Right('c');
let mut iter = value.iter();
assert_eq!(iter.next(), Some(&'c'));
assert_eq!(iter.next(), None);
Source

pub fn iter_mut(&mut self) -> IterMutEither<'_, T>

Returns an iterator over the contained mutable value of a uniform type

§Examples
use either_or_both::EitherOrBoth;

let mut value: EitherOrBoth<char> = EitherOrBoth::Left('c');
let mut iter = value.iter_mut();
assert_eq!(iter.next(), Some(&mut 'c'));
assert_eq!(iter.next(), None);

let mut value: EitherOrBoth<char> = EitherOrBoth::Right('c');
let mut iter = value.iter_mut();
assert_eq!(iter.next(), Some(&mut 'c'));
assert_eq!(iter.next(), None);
Source

pub fn into_iter_inner(self) -> InnerIterEither<<T as IntoIterator>::IntoIter>
where T: IntoIterator,

Consumes the Either, returning an iterator over the contained iterator of a uniform type

For iteration over contained iterators with non-uniform types, you can use into_iter_swap instead.

§Examples
use either_or_both::Either;

let value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
let collected: Vec<char> = value.into_iter_inner().collect();
assert_eq!(collected, vec!['c', 'a']);
Source

pub fn iter_inner(&self) -> InnerIterEither<<&T as IntoIterator>::IntoIter>
where for<'a> &'a T: IntoIterator,

Returns an iterator over the contained iterator of a uniform type

For iteration over contained iterators with non-uniform types, you can use iter_swap instead.

§Examples
use either_or_both::Either;

let value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
let collected: Vec<&char> = value.iter_inner().collect();
assert_eq!(collected, vec![&'c', &'a']);
Source

pub fn iter_inner_mut( &mut self, ) -> InnerIterEither<<&mut T as IntoIterator>::IntoIter>
where for<'a> &'a mut T: IntoIterator,

Returns an iterator over the mutable values of the contained iterator of a uniform type

For iteration over contained iterators with non-uniform types, you can use iter_swap_mut instead.

§Examples
use either_or_both::Either;

let mut value: Either<Vec<char>> = Either::Left(vec!['c', 'a']);
let collected: Vec<&mut char> = value.iter_inner_mut().collect();
assert_eq!(collected, vec![&mut 'c', &mut 'a']);
Source

pub fn map<F, U>(self, f: F) -> Either<U, U>
where F: FnOnce(T) -> U,

Applies a mapping function to the left and right values (of a uniform type) returning an Either<U, U>.

§Examples
use either_or_both::Either;

let value: Either<char> = Either::Left('c');
assert_eq!(value.map(|c| c.to_string()), Either::Left("c".to_owned()));

let value: Either<char> = Either::Right('a');
assert_eq!(value.map(|c| c.to_string()), Either::Right("a".to_owned()));
Source

pub fn reduce(self) -> T

Returns the contained Left or Right value of uniform type.

§Example
use either_or_both::Either;

let value: Either<u8> = Either::Left(1);
assert_eq!(value.reduce(), 1);

let value: Either<u8> = Either::Right(2);
assert_eq!(value.reduce(), 2);
Source

pub fn reduce_map<F, U>(self, f: F) -> U
where F: FnOnce(T) -> U,

Returns the contained Left or Right value applying a mapping function to the contained values.

§Example
use either_or_both::Either;

let value: Either<u8> = Either::Left(1);
assert_eq!(value.reduce_map(|v| v + 1), 2);

let value: Either<u8> = Either::Right(2);
assert_eq!(value.reduce_map(|v| v + 1), 3);
Source§

impl<L, R> Either<&L, &R>

Source

pub fn cloned(self) -> Either<L, R>
where L: Clone, R: Clone,

Converts an Either<&L, &R> into an Either<L, R> by cloning its contents

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
let refs: Either<&u8, &char> = value.as_ref();
assert_eq!(refs.cloned(), Either::Left(1));
Source

pub const fn copied(self) -> Either<L, R>
where L: Copy, R: Copy,

Converts an Either<&L, &R> into an Either<L, R> by copying its contents.

§Examples
use either_or_both::Either;

let value: Either<u8, char> = Either::Left(1);
let refs: Either<&u8, &char> = value.as_ref();
assert_eq!(refs.copied(), Either::Left(1));
Source§

impl<L, R> Either<&mut L, &mut R>

Source

pub fn cloned(self) -> Either<L, R>
where L: Clone, R: Clone,

Converts an Either<&mut L, &mut R> into an Either<L, R> by cloning its contents.

§Examples
use either_or_both::Either;

let mut value: Either<u8, char> = Either::Left(1);
let refs: Either<&mut u8, &mut char> = value.as_mut();
assert_eq!(refs.cloned(), Either::Left(1));
Source

pub fn copied(self) -> Either<L, R>
where L: Copy, R: Copy,

Converts an Either<&mut L, &mut R> into an Either<L, R> by copying its contents

§Examples
use either_or_both::Either;

let mut value: Either<u8, char> = Either::Left(1);
let refs: Either<&mut u8, &mut char> = value.as_mut();
assert_eq!(refs.copied(), Either::Left(1));
Source§

impl<L1, L2, R1, R2> Either<(L1, R1), (L2, R2)>

Source

pub fn transpose(self) -> (Either<L1, L2>, Either<R1, R2>)

Transposes a Either of tuples to a tuple of Eithers

§Examples
use either_or_both::Either;

let value: Either<(u8, char), (i32, u64)> = Either::Left((1, 'c'));
assert_eq!(value.transpose(), (Either::Left(1), Either::Left('c')));

let value: Either<(u8, char), (i32, u64)> = Either::Right((-2, 10));
assert_eq!(value.transpose(), (Either::Right(-2), Either::Right(10)));
Source§

impl<L, R, T> Either<(T, L), (T, R)>

Source

pub fn transpose_left(self) -> (T, Either<L, R>)

Transposes an Either of tuples to a tuple of a single value and an Either with the left value having a uniform type

§Examples
use either_or_both::Either;

let value: Either<(u8, char), (u8, i32)> = Either::Left((1, 'c'));
assert_eq!(value.transpose_left(), (1, Either::Left('c')));

let value: Either<(u8, char), (u8, i32)> = Either::Right((2, -10));
assert_eq!(value.transpose_left(), (2, Either::Right(-10)));
Source§

impl<L, R, T> Either<(L, T), (R, T)>

Source

pub fn transpose_right(self) -> (Either<L, R>, T)

Transposes an Either of tuples to a tuple of a single value and an Either with the right value having a uniform type

§Examples
use either_or_both::Either;

let value: Either<(u8, char), (i32, char)> = Either::Left((1, 'c'));
assert_eq!(value.transpose_right(), (Either::Left(1), 'c'));

let value: Either<(u8, char), (i32, char)> = Either::Right((-2, 'a'));
assert_eq!(value.transpose_right(), (Either::Right(-2), 'a'));
Source§

impl<L, R> Either<Option<L>, Option<R>>

Source

pub fn transpose(self) -> Option<Either<L, R>>

Transposes an Either of Options to an option of an Either

§Examples
use either_or_both::Either;

let value: Either<Option<u8>, Option<char>> = Either::Left(Some(1));
assert_eq!(value.transpose(), Some(Either::Left(1)));

let value: Either<Option<u8>, Option<char>> = Either::Left(None);
assert_eq!(value.transpose(), None);

let value: Either<Option<u8>, Option<char>> = Either::Right(Some('c'));
assert_eq!(value.transpose(), Some(Either::Right('c')));
Source§

impl<L, R, E1, E2> Either<Result<L, E1>, Result<R, E2>>

Source

pub fn transpose(self) -> Result<Either<L, R>, Either<E1, E2>>

Transposes an Either of Results to a Result of an Either

§Examples
use either_or_both::Either;

let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Left(Ok(1));
assert_eq!(value.transpose(), Ok(Either::Left(1)));

let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Left(Err('c'));
assert_eq!(value.transpose(), Err(Either::Left('c')));

let value: Either<Result<u8, char>, Result<i32, u64>> = Either::Right(Ok(-2));
assert_eq!(value.transpose(), Ok(Either::Right(-2)));
Source§

impl<L, R, E> Either<Result<L, E>, Result<R, E>>

Source

pub fn transpose_err(self) -> Result<Either<L, R>, E>

Transposes an Either of Results to a Result with an uniform error type

§Examples
use either_or_both::Either;

let x: Either<Result<u8, char>, Result<i32, char>> = Either::Left(Ok(1));
assert_eq!(x.transpose_err(), Ok(Either::Left(1)));

let x: Either<Result<u8, char>, Result<i32, char>> = Either::Left(Err('c'));
assert_eq!(x.transpose_err(), Err('c'));

let x: Either<Result<u8, char>, Result<i32, char>> = Either::Right(Ok(-2));
assert_eq!(x.transpose_err(), Ok(Either::Right(-2)));
Source§

impl<T, E1, E2> Either<Result<T, E1>, Result<T, E2>>

Source

pub fn transpose_ok(self) -> Result<T, Either<E1, E2>>

Transposes an Either of Results to a Result with an uniform correct type

§Examples
use either_or_both::Either;

let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Left(Ok(2));
assert_eq!(x.transpose_ok(), Ok(2));

let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Left(Err('c'));
assert_eq!(x.transpose_ok(), Err(Either::Left('c')));

let x: Either<Result<u8, char>, Result<u8, i32>> = Either::Right(Ok(2));
assert_eq!(x.transpose_ok(), Ok(2));

Trait Implementations§

Source§

impl<L, R, T> AsMut<T> for Either<L, R>
where T: ?Sized, L: AsMut<T>, R: AsMut<T>,

Source§

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<L, R, T> AsRef<T> for Either<L, R>
where T: ?Sized, L: AsRef<T>, R: AsRef<T>,

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<L, R> BufRead for Either<L, R>
where L: BufRead, R: BufRead,

Available on crate feature std only.
Source§

fn fill_buf(&mut self) -> Result<&[u8]>

Returns the contents of the internal buffer, filling it with more data, via Read methods, if empty. Read more
Source§

fn consume(&mut self, amount: usize)

Marks the given amount of additional bytes from the internal buffer as having been read. Subsequent calls to read only return bytes that have not been marked as read. Read more
Source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Checks if there is any data left to be read. Read more
1.0.0 · Source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
1.83.0 · Source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · Source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer. Read more
1.0.0 · Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns an iterator over the contents of this reader split on the byte byte. Read more
1.0.0 · Source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns an iterator over the lines of this reader. Read more
Source§

impl<L: Clone, R: Clone> Clone for Either<L, R>

Source§

fn clone(&self) -> Either<L, R>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<L: Debug, R: Debug> Debug for Either<L, R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<L, R> Deref for Either<L, R>
where L: Deref<Target = R::Target>, R: Deref,

Source§

type Target = <R as Deref>::Target

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<L, R> DerefMut for Either<L, R>
where L: DerefMut<Target = R::Target>, R: DerefMut,

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<'de, L, R> Deserialize<'de> for Either<L, R>
where L: Deserialize<'de>, R: Deserialize<'de>,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<L, R> Display for Either<L, R>
where L: Display, R: Display,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<L, R> Error for Either<L, R>
where L: Error, R: Error,

Available on crate feature std only.
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl<A, T> Extend<A> for Either<T>
where T: Extend<A>,

Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = A>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<'a, L, R> From<&'a Either<L, R>> for Either<&'a L, &'a R>

Source§

fn from(value: &'a Either<L, R>) -> Self

Converts to this type from the input type.
Source§

impl<'a, L, R> From<&'a mut Either<L, R>> for Either<&'a mut L, &'a mut R>

Source§

fn from(value: &'a mut Either<L, R>) -> Self

Converts to this type from the input type.
Source§

impl<L, R> From<Either<L, R>> for EitherOrBoth<L, R>

Source§

fn from(value: Either<L, R>) -> Self

Converts to this type from the input type.
Source§

impl<L, R> From<Result<R, L>> for Either<L, R>

Source§

fn from(value: Result<R, L>) -> Self

Converts to this type from the input type.
Source§

impl<K1, K2, V1, V2, S1, S2> FromIterator<Either<(K1, V1), (K2, V2)>> for EitherOrBoth<HashMap<K1, V1, S1>, HashMap<K2, V2, S2>>
where K1: Hash + Eq, K2: Hash + Eq, S1: BuildHasher + Default, S2: BuildHasher + Default,

Available on crate feature std only.
Source§

fn from_iter<T>(iter: T) -> Self
where T: IntoIterator<Item = Either<(K1, V1), (K2, V2)>>,

Consumes an Iterator of Either items, collecting all left and right values into separate HashMaps.

  • If only left values are present, returns Left with the left HashMap.
  • If only right values are present, returns Right with the right HashMap.
  • If none or both left and right values are present, returns Both with both HashMaps.
§Examples

This example collects into a Both variant:

use std::collections::HashMap;

use either_or_both::{Either, EitherOrBoth};

let items: Vec<Either<(&str, u8), (&str, char)>> =
    vec![Either::Right(("right", 'c')), Either::Left(("left", 2))];

let collected: EitherOrBoth<HashMap<&str, u8>, HashMap<&str, char>> =
    items.into_iter().collect();

assert_eq!(
    collected,
    EitherOrBoth::Both(
        HashMap::from([("left", 2)]),
        HashMap::from([("right", 'c')])
    )
);

This example collects into a Left variant:

use std::collections::HashMap;

use either_or_both::{Either, EitherOrBoth};

let items: Vec<Either<(&str, u8), (&str, char)>> =
    vec![Either::Left(("left", 2))];
let collected: EitherOrBoth<HashMap<&str, u8>, HashMap<&str, char>> =
    items.into_iter().collect();

assert_eq!(collected, EitherOrBoth::Left(HashMap::from([("left", 2)]),));
Source§

impl<K1, K2, V1, V2, S1, S2> FromIterator<Either<(K1, V1), (K2, V2)>> for EitherOrBoth<IndexMap<K1, V1, S1>, IndexMap<K2, V2, S2>>
where K1: Hash + Eq, K2: Hash + Eq, S1: BuildHasher + Default, S2: BuildHasher + Default,

Available on crate feature indexmap only.
Source§

fn from_iter<T>(iter: T) -> Self
where T: IntoIterator<Item = Either<(K1, V1), (K2, V2)>>,

Consumes an Iterator of Either items, collecting all left and right values into separate IndexMaps.

  • If only left values are present, returns Left with the left IndexMap.
  • If only right values are present, returns Right with the right IndexMap.
  • If none or both left and right values are present, returns Both with both IndexMaps.
§Examples

This example collects into a Both variant:

use either_or_both::{Either, EitherOrBoth};
use indexmap::IndexMap;

let items: Vec<Either<(&str, u8), (&str, char)>> =
    vec![Either::Right(("right", 'c')), Either::Left(("left", 2))];

let collected: EitherOrBoth<IndexMap<&str, u8>, IndexMap<&str, char>> =
    items.into_iter().collect();

assert_eq!(
    collected,
    EitherOrBoth::Both(
        IndexMap::from([("left", 2)]),
        IndexMap::from([("right", 'c')])
    )
);

This example collects into a Left variant:

use either_or_both::{Either, EitherOrBoth};
use indexmap::IndexMap;

let items: Vec<Either<(&str, u8), (&str, char)>> =
    vec![Either::Left(("left", 2))];
let collected: EitherOrBoth<IndexMap<&str, u8>, IndexMap<&str, char>> =
    items.into_iter().collect();

assert_eq!(
    collected,
    EitherOrBoth::Left(IndexMap::from([("left", 2)]),)
);
Source§

impl<K1, K2, S1, S2> FromIterator<Either<K1, K2>> for EitherOrBoth<HashSet<K1, S1>, HashSet<K2, S2>>
where K1: Hash + Eq, K2: Hash + Eq, S1: BuildHasher + Default, S2: BuildHasher + Default,

Available on crate feature std only.
Source§

fn from_iter<T>(iter: T) -> Self
where T: IntoIterator<Item = Either<K1, K2>>,

Consumes an Iterator of Either items, collecting all left and right values into separate HashSets.

  • If only left values are present, returns Left with the left HashSet.
  • If only right values are present, returns Right with the right HashSet.
  • If none or both left and right values are present, returns Both with both HashSets.
§Examples

This example collects into a Both variant:

use std::collections::HashSet;

use either_or_both::{Either, EitherOrBoth};

let items: Vec<Either<u8, char>> = vec![Either::Right('c'), Either::Left(2)];

let collected: EitherOrBoth<HashSet<u8>, HashSet<char>> =
   items.into_iter().collect();

assert_eq!(
    collected,
    EitherOrBoth::Both(HashSet::from([2]), HashSet::from(['c']))
);

This example collects into a Left variant:

use std::collections::HashSet;

use either_or_both::{Either, EitherOrBoth};

let items: Vec<Either<u8, char>> = vec![Either::Left(2)];
let collected: EitherOrBoth<HashSet<u8>, HashSet<char>> =
    items.into_iter().collect();

assert_eq!(collected, EitherOrBoth::Left(HashSet::from([2])));
Source§

impl<K1, K2, S1, S2> FromIterator<Either<K1, K2>> for EitherOrBoth<IndexSet<K1, S1>, IndexSet<K2, S2>>
where K1: Hash + Eq, K2: Hash + Eq, S1: BuildHasher + Default, S2: BuildHasher + Default,

Available on crate feature indexmap only.
Source§

fn from_iter<T>(iter: T) -> Self
where T: IntoIterator<Item = Either<K1, K2>>,

Consumes an Iterator of Either items, collecting all left and right values into separate IndexSets.

  • If only left values are present, returns Left with the left IndexSet.
  • If only right values are present, returns Right with the right IndexSet.
  • If none or both left and right values are present, returns Both with both IndexSets.
§Examples

This example collects into a Both variant:

use either_or_both::{Either, EitherOrBoth};
use indexmap::IndexSet;

let items: Vec<Either<u8, char>> = vec![Either::Right('c'), Either::Left(2)];
let collected: EitherOrBoth<IndexSet<u8>, IndexSet<char>> =
   items.into_iter().collect();

assert_eq!(
    collected,
    EitherOrBoth::Both(IndexSet::from([2]), IndexSet::from(['c']))
);

This example collects into a Left variant:

use either_or_both::{Either, EitherOrBoth};
use indexmap::IndexSet;

let items: Vec<Either<u8, char>> = vec![Either::Left(2)];
let collected: EitherOrBoth<IndexSet<u8>, IndexSet<char>> =
   items.into_iter().collect();

assert_eq!(collected, EitherOrBoth::Left(IndexSet::from([2])));
Source§

impl<L, R> FromIterator<Either<L, R>> for EitherOrBoth<Vec<L>, Vec<R>>

Available on crate feature std only.
Source§

fn from_iter<T: IntoIterator<Item = Either<L, R>>>(iter: T) -> Self

Consumes an Iterator of Either items, collecting all left and right values into separate vectors.

  • If only left values are present, returns Left with the left Vec.
  • If only right values are present, returns Right with the right Vec.
  • If none or both left and right values are present, returns Both with both Vecs.
§Examples

This example collects into a Both variant:

use either_or_both::{Either, EitherOrBoth};

let items: Vec<Either<u8, char>> = vec![Either::Left(1), Either::Right('c')];
let collected: EitherOrBoth<Vec<u8>, Vec<char>> = items.into_iter().collect();

assert_eq!(collected, EitherOrBoth::Both(vec![1], vec!['c']));

This example collects into a Left variant:

use either_or_both::{Either, EitherOrBoth};

let items: Vec<Either<u8, char>> = vec![Either::Left(1), Either::Right('c')];
let collected: EitherOrBoth<Vec<u8>, Vec<char>> = items.into_iter().collect();

assert_eq!(collected, EitherOrBoth::Both(vec![1], vec!['c']));
Source§

impl<L, R> Future for Either<L, R>
where L: Future<Output = R::Output>, R: Future,

Source§

type Output = <R as Future>::Output

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more
Source§

impl<L: Hash, R: Hash> Hash for Either<L, R>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a, T> IntoIterator for &'a Either<T>

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = IterEither<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T> IntoIterator for &'a mut Either<T>

Source§

type Item = &'a mut T

The type of the elements being iterated over.
Source§

type IntoIter = IterMutEither<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T> IntoIterator for Either<T>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIterEither<T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<L, R> JsonSchema for Either<L, R>
where L: JsonSchema, R: JsonSchema,

Source§

fn schema_name() -> Cow<'static, str>

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn inline_schema() -> bool

Whether JSON Schemas generated for this type should be included directly in parent schemas, rather than being re-used where possible using the $ref keyword. Read more
Source§

impl<L: PartialEq, R: PartialEq> PartialEq for Either<L, R>

Source§

fn eq(&self, other: &Either<L, R>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<L, R> Read for Either<L, R>
where L: Read, R: Read,

Available on crate feature std only.
Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

impl<L, R> Seek for Either<L, R>
where L: Seek, R: Seek,

Available on crate feature std only.
Source§

fn seek(&mut self, pos: SeekFrom) -> Result<u64>

Seek to an offset, in bytes, in a stream. Read more
1.55.0 · Source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
Source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.51.0 · Source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.80.0 · Source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
Source§

impl<L, R> Serialize for Either<L, R>
where L: Serialize, R: Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<L, R> Write for Either<L, R>
where L: Write, R: Write,

Source§

fn write_str(&mut self, s: &str) -> Result

Writes a string slice into this writer, returning whether the write succeeded. Read more
1.1.0 · Source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a char into this writer, returning whether the write succeeded. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the write! macro with implementors of this trait. Read more
Source§

impl<L, R> Write for Either<L, R>
where L: Write, R: Write,

Available on crate feature std only.
Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
Source§

impl<L: Copy, R: Copy> Copy for Either<L, R>

Source§

impl<L: Eq, R: Eq> Eq for Either<L, R>

Source§

impl<L, R> StructuralPartialEq for Either<L, R>

Auto Trait Implementations§

§

impl<L, R> Freeze for Either<L, R>
where L: Freeze, R: Freeze,

§

impl<L, R> RefUnwindSafe for Either<L, R>

§

impl<L, R> Send for Either<L, R>
where L: Send, R: Send,

§

impl<L, R> Sync for Either<L, R>
where L: Sync, R: Sync,

§

impl<L, R> Unpin for Either<L, R>
where L: Unpin, R: Unpin,

§

impl<L, R> UnwindSafe for Either<L, R>
where L: UnwindSafe, R: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<F> IntoFuture for F
where F: Future,

Source§

type Output = <F as Future>::Output

The output that the future will produce on completion.
Source§

type IntoFuture = F

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,