From 416b4dbc12e84ac478aa9471a74a604cb278049d Mon Sep 17 00:00:00 2001 From: Jens Pots Date: Tue, 30 Apr 2024 09:54:27 +0200 Subject: [PATCH] feat: async methods for readers and writers --- src/main/kotlin/bridge/MemoryBridge.kt | 20 ++++++++++++++++++++ src/main/kotlin/bridge/Reader.kt | 1 + src/main/kotlin/bridge/Writer.kt | 1 + 3 files changed, 22 insertions(+) diff --git a/src/main/kotlin/bridge/MemoryBridge.kt b/src/main/kotlin/bridge/MemoryBridge.kt index 71b6231..e0cb055 100644 --- a/src/main/kotlin/bridge/MemoryBridge.kt +++ b/src/main/kotlin/bridge/MemoryBridge.kt @@ -2,6 +2,7 @@ import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import bridge.Bridge import bridge.Reader +import kotlinx.coroutines.channels.ClosedReceiveChannelException import technology.idlab.logging.Log class MemoryBridge : Bridge { @@ -13,6 +14,14 @@ class MemoryBridge : Bridge { Log.shared.debug("Done") } + override suspend fun push(value: ByteArray) { + try { + channel.trySend(value) + } catch (e: Exception) { + Log.shared.fatal(e) + } + } + override fun readSync(): Reader.Result { Log.shared.debug("Reading bytes") val result = runBlocking { channel.receiveCatching() } @@ -31,6 +40,17 @@ class MemoryBridge : Bridge { return Reader.Result.success(bytes) } + override suspend fun read(): Reader.Result { + try { + val result = channel.receive() + return Reader.Result.success(result) + } catch (e: ClosedReceiveChannelException) { + return Reader.Result.closed() + } catch (e: Exception) { + Log.shared.fatal(e) + } + } + override fun isClosed(): Boolean { return channel.isClosedForSend } diff --git a/src/main/kotlin/bridge/Reader.kt b/src/main/kotlin/bridge/Reader.kt index f249ad1..1f422ab 100644 --- a/src/main/kotlin/bridge/Reader.kt +++ b/src/main/kotlin/bridge/Reader.kt @@ -37,6 +37,7 @@ interface Reader { } } + suspend fun read(): Result fun readSync(): Result fun isClosed(): Boolean } diff --git a/src/main/kotlin/bridge/Writer.kt b/src/main/kotlin/bridge/Writer.kt index a5b923f..481c150 100644 --- a/src/main/kotlin/bridge/Writer.kt +++ b/src/main/kotlin/bridge/Writer.kt @@ -1,6 +1,7 @@ package bridge interface Writer { + suspend fun push(value: ByteArray) fun pushSync(value: ByteArray) fun close() }