From 771e71996329123922712ed7a551a6aaf5f7b4aa Mon Sep 17 00:00:00 2001 From: David Perez Date: Mon, 11 Nov 2024 14:46:55 -0600 Subject: [PATCH] PM-14805: Ensure results cannot be double wrapped from 'asSuccess' (#4283) --- .../bitwarden/data/platform/util/ResultExtensions.kt | 9 ++++++++- .../com/x8bit/bitwarden/data/platform/util/ResultTest.kt | 8 ++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/x8bit/bitwarden/data/platform/util/ResultExtensions.kt b/app/src/main/java/com/x8bit/bitwarden/data/platform/util/ResultExtensions.kt index 7784700e8..6b1a51775 100644 --- a/app/src/main/java/com/x8bit/bitwarden/data/platform/util/ResultExtensions.kt +++ b/app/src/main/java/com/x8bit/bitwarden/data/platform/util/ResultExtensions.kt @@ -14,9 +14,16 @@ inline fun Result.flatMap(transform: (T) -> Result): Result = /** * Returns the given receiver of type [T] as a "success" [Result]. + * + * Note that this will never double wrap the `Result` and we return the original value if [T] is + * already an instance of `Result` */ -fun T.asSuccess(): Result = +fun T.asSuccess(): Result = if (this is Result<*>) { + @Suppress("UNCHECKED_CAST") + this as Result +} else { Result.success(this) +} /** * Returns the given [Throwable] as a "failure" [Result]. diff --git a/app/src/test/java/com/x8bit/bitwarden/data/platform/util/ResultTest.kt b/app/src/test/java/com/x8bit/bitwarden/data/platform/util/ResultTest.kt index a8d3462bb..1d6f4c75d 100644 --- a/app/src/test/java/com/x8bit/bitwarden/data/platform/util/ResultTest.kt +++ b/app/src/test/java/com/x8bit/bitwarden/data/platform/util/ResultTest.kt @@ -59,6 +59,14 @@ class ResultTest { ) } + @Test + fun `asSuccess returns a success Result with the correct content that is not double-wrapped`() { + assertEquals( + Result.success("Test"), + "Test".asSuccess().asSuccess(), + ) + } + @Test fun `asFailure returns a failure Result with the correct content`() { val throwable = IllegalStateException("Test")