Skip to content

Commit

Permalink
Add Either::cloned and Either::copied
Browse files Browse the repository at this point in the history
Similar to Option::cloned and Option::copied, these methods will clone or copy
the contents of an Either containing references on both sides.
  • Loading branch information
ColonelThirtyTwo committed Jun 18, 2024
1 parent 7a60ae8 commit 8e62690
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,62 @@ impl<T> Either<T, T> {
}
}

impl<L, R> Either<&L, &R> {
/// Maps an `Either<&L, &R>` to an `Either<L, R>` by cloning the contents of
/// either branch.
pub fn cloned(self) -> Either<L, R>
where
L: Clone,
R: Clone,
{
match self {
Self::Left(l) => Either::Left(l.clone()),
Self::Right(r) => Either::Right(r.clone()),
}
}

/// Maps an `Either<&L, &R>` to an `Either<L, R>` by copying the contents of
/// either branch.
pub fn copied(self) -> Either<L, R>
where
L: Copy,
R: Copy,
{
match self {
Self::Left(l) => Either::Left(*l),
Self::Right(r) => Either::Right(*r),
}
}
}

impl<L, R> Either<&mut L, &mut R> {
/// Maps an `Either<&mut L, &mut R>` to an `Either<L, R>` by cloning the contents of
/// either branch.
pub fn cloned(self) -> Either<L, R>
where
L: Clone,
R: Clone,
{
match self {
Self::Left(l) => Either::Left(l.clone()),
Self::Right(r) => Either::Right(r.clone()),
}
}

/// Maps an `Either<&L, &R>` to an `Either<L, R>` by copying the contents of
/// either branch.
pub fn copied(self) -> Either<L, R>
where
L: Copy,
R: Copy,
{
match self {
Self::Left(l) => Either::Left(*l),
Self::Right(r) => Either::Right(*r),
}
}
}

/// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`.
impl<L, R> From<Result<R, L>> for Either<L, R> {
fn from(r: Result<R, L>) -> Self {
Expand Down

0 comments on commit 8e62690

Please sign in to comment.