Skip to content

Commit

Permalink
Merge pull request #107 from ColonelThirtyTwo/cloned-copied
Browse files Browse the repository at this point in the history
Add Either::cloned and Either::copied
  • Loading branch information
cuviper authored Jun 25, 2024
2 parents 1cea51a + e31810d commit cd0aab9
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 @@ -1093,6 +1093,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<&mut L, &mut 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 cd0aab9

Please sign in to comment.