From 11cd947d05f441c2eb7c6db463985f9e2e944751 Mon Sep 17 00:00:00 2001 From: Ian Campbell Date: Tue, 2 May 2023 16:32:45 +0100 Subject: [PATCH] Support returning an `Option` from an async function The newly added test case previously failed with: ``` target/tmp/uniffi-fixture-futures-a3d73500fcde9679/uniffi/fixture/futures/uniffi_futures.kt:1638:63: error: type mismatch: inferred type is RustFutureWakerEnvironment but RustFutureWakerEnvironment was expected _UniFFILib.FUTURE_WAKER_ENVIRONMENTS.put(envHash, env) ^ test uniffi_foreign_language_testcase_test_futures_kts ... FAILED ``` --- fixtures/futures/src/lib.rs | 10 ++++++++++ fixtures/futures/tests/bindings/test_futures.kts | 9 +++++++++ .../kotlin/templates/NamespaceLibraryTemplate.kt | 2 +- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/fixtures/futures/src/lib.rs b/fixtures/futures/src/lib.rs index 92ca4bffcc..c1529b4cab 100644 --- a/fixtures/futures/src/lib.rs +++ b/fixtures/futures/src/lib.rs @@ -130,6 +130,16 @@ pub async fn async_new_megaphone() -> Arc { new_megaphone() } +/// Async function that possibly generates a new `Megaphone`. +#[uniffi::export] +pub async fn async_maybe_new_megaphone(y: bool) -> Option> { + if y { + Some(new_megaphone()) + } else { + None + } +} + /// A megaphone. Be careful with the neighbours. #[derive(uniffi::Object)] pub struct Megaphone; diff --git a/fixtures/futures/tests/bindings/test_futures.kts b/fixtures/futures/tests/bindings/test_futures.kts index 86a550692a..29f466e89a 100644 --- a/fixtures/futures/tests/bindings/test_futures.kts +++ b/fixtures/futures/tests/bindings/test_futures.kts @@ -92,6 +92,15 @@ runBlocking { println(" ... ok") } +// Test async method returning optional object +runBlocking { + val megaphone = asyncMaybeNewMegaphone(true) + assert(megaphone != null) + + val not_megaphone = asyncMaybeNewMegaphone(false) + assert(not_megaphone == null) +} + // Test with the Tokio runtime. runBlocking { val time = measureTimeMillis { diff --git a/uniffi_bindgen/src/bindings/kotlin/templates/NamespaceLibraryTemplate.kt b/uniffi_bindgen/src/bindings/kotlin/templates/NamespaceLibraryTemplate.kt index 7b1ccc678b..2bd2078ad3 100644 --- a/uniffi_bindgen/src/bindings/kotlin/templates/NamespaceLibraryTemplate.kt +++ b/uniffi_bindgen/src/bindings/kotlin/templates/NamespaceLibraryTemplate.kt @@ -30,7 +30,7 @@ internal interface _UniFFILib : Library { } {%- if ci.has_async_fns() %} - internal val FUTURE_WAKER_ENVIRONMENTS: ConcurrentHashMap> by lazy { + internal val FUTURE_WAKER_ENVIRONMENTS: ConcurrentHashMap> by lazy { ConcurrentHashMap(8) } {%- endif %}