Skip to content

Commit

Permalink
feat: async methods for readers and writers
Browse files Browse the repository at this point in the history
  • Loading branch information
jenspots committed Apr 30, 2024
1 parent 2394112 commit 416b4db
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/main/kotlin/bridge/MemoryBridge.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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() }
Expand All @@ -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
}
Expand Down
1 change: 1 addition & 0 deletions src/main/kotlin/bridge/Reader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ interface Reader {
}
}

suspend fun read(): Result
fun readSync(): Result
fun isClosed(): Boolean
}
Expand Down
1 change: 1 addition & 0 deletions src/main/kotlin/bridge/Writer.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bridge

interface Writer {
suspend fun push(value: ByteArray)
fun pushSync(value: ByteArray)
fun close()
}

0 comments on commit 416b4db

Please sign in to comment.