diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/io/Io.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/io/Io.kt index ce8469b..f829973 100644 --- a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/io/Io.kt +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/io/Io.kt @@ -2,10 +2,12 @@ // Copyright (C) 2026 Neo-Desktop package com.neodesktop.dmodem.io +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.coroutines.selects.onTimeout +import kotlinx.coroutines.selects.select import kotlin.time.TimeSource /** @@ -84,11 +86,21 @@ class ByteQueue { ch.trySend(b) } - /** the next chunk, waiting up to [ms]; null if none came (the reader's thread) */ + /** + * the next chunk, waiting up to [ms]; null if none came (the reader's + * thread). (A select, not receive() in withTimeoutOrNull: a chunk sent + * just as that timed out was taken by the cancelled receive and lost.) + */ + @OptIn(ExperimentalCoroutinesApi::class) fun poll(ms: Long): ByteArray? { poll()?.let { return it } if (ms <= 0) return null - return runBlocking { withTimeoutOrNull(ms) { ch.receive() } } + return runBlocking { + select { + ch.onReceive { it } + onTimeout(ms) { null } + } + } } /** the next chunk if one waits, else null */ diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/io/ByteQueueTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/io/ByteQueueTest.kt new file mode 100644 index 0000000..f3e6fe2 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/io/ByteQueueTest.kt @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.io + +import kotlin.concurrent.Volatile +import kotlin.test.Test +import kotlin.test.assertEquals + +/** A ByteQueue between two threads loses nothing, whatever its reads' timeouts. */ +class ByteQueueTest { + private class Flag { @Volatile var on = false } + + /** chunks put while the reader's short waits keep timing out all come, in order */ + @Test + fun nothingLostToATimeout() { + val q = ByteQueue() + val n = 3000 + val done = Flag() + background("writer") { + for (i in 0 until n) { + q.put(byteArrayOf((i shr 8).toByte(), i.toByte())) + // (now and then just as the reader's wait runs out) + if (i % 3 == 0) sleepMs(1) + } + done.on = true + } + var next = 0 + val end = monotonicMs() + 30_000 + while (next < n && monotonicMs() < end) { + val b = q.poll(1) ?: continue + val i = ((b[0].toInt() and 0xff) shl 8) or (b[1].toInt() and 0xff) + assertEquals(next, i, "chunk $next") + next++ + } + assertEquals(n, next) + } +}