From 8e626907acb2073d570b02599370fe5f5dd5208a Mon Sep 17 00:00:00 2001 From: Alex Parrill Date: Tue, 18 Jun 2024 10:11:55 -0400 Subject: [PATCH 1/2] Add Either::cloned and Either::copied Similar to Option::cloned and Option::copied, these methods will clone or copy the contents of an Either containing references on both sides. --- src/lib.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index d7fbf2c..d6e0b18 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -955,6 +955,62 @@ impl Either { } } +impl Either<&L, &R> { + /// Maps an `Either<&L, &R>` to an `Either` by cloning the contents of + /// either branch. + pub fn cloned(self) -> Either + 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` by copying the contents of + /// either branch. + pub fn copied(self) -> Either + where + L: Copy, + R: Copy, + { + match self { + Self::Left(l) => Either::Left(*l), + Self::Right(r) => Either::Right(*r), + } + } +} + +impl Either<&mut L, &mut R> { + /// Maps an `Either<&mut L, &mut R>` to an `Either` by cloning the contents of + /// either branch. + pub fn cloned(self) -> Either + 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` by copying the contents of + /// either branch. + pub fn copied(self) -> Either + 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 From> for Either { fn from(r: Result) -> Self { From e31810d584a3b80b275ae3640781db25b18a5c6d Mon Sep 17 00:00:00 2001 From: Alex Parrill Date: Tue, 25 Jun 2024 09:21:23 -0400 Subject: [PATCH 2/2] Fix docs on Either<&mut L, &mut R>::copied Co-authored-by: Josh Stone --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index d6e0b18..accdc34 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -997,7 +997,7 @@ impl Either<&mut L, &mut R> { } } - /// Maps an `Either<&L, &R>` to an `Either` by copying the contents of + /// Maps an `Either<&mut L, &mut R>` to an `Either` by copying the contents of /// either branch. pub fn copied(self) -> Either where