Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Either::cloned and Either::copied #107

Merged
merged 2 commits into from
Jun 25, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
ColonelThirtyTwo marked this conversation as resolved.
Show resolved Hide resolved
/// 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