kotlinx-io
kotlinx-io copied to clipboard
[io-2] Reusable Input
Another feature I would like to see (and contribute) after io-2 release is the reusable Input (and maybe output) abstraction. It could look like this. The idea is that we have an Input provider that could be instantiated and reused in a safe way. Tho simple examples are file and a network stream. In case of file, we do not have to get file input, just a file reference, and the open, use and close the input automatically (my code have also an interface of RandomAccessBinary which could be used to access file not from the beginning). Another case is a network connection. Here, we won't close the input after read, but we will provide thread safe access for several readers to the same stream without them knowing about one another.
I am not sure about the size field. It is quite helpful in case one needs to copy the whole input to another binary, or in case of random access, but could be bothersome for infinite streams.
The same could be probably done for output, but I did not encounter use case so far.
An example. Here how test looked before:
val input = bytes.input()
val ba = ByteArray(2)
input.readArray(ba)
assertEquals(0x11, ba[0])
assertEquals(0x22, ba[1])
assertEquals(0x12, input.readByte())
assertEquals(0x82u, input.readUByte())
assertEquals(0x3456, input.readShort())
assertEquals(0x789abcde, input.readInt())
assertEquals(1.25, input.readDouble())
assertEquals(1.25f, input.readFloat())
val ll = (1..8).map { input.readByte().toInt() and 0xff }.joinToString()
assertEquals("18, 52, 86, 120, 154, 188, 222, 240", ll)
assertEquals(0x123456789abcdef0, input.readLong())
assertEquals("OK", input.readUTF8Line())
After:
bytes.read {
val ba = ByteArray(2)
readArray(ba)
assertEquals(0x11, ba[0])
assertEquals(0x22, ba[1])
assertEquals(0x12, readByte())
assertEquals(0x82u, readUByte())
assertEquals(0x3456, readShort())
assertEquals(0x789abcde, readInt())
assertEquals(1.25, readDouble())
assertEquals(1.25f, readFloat())
val ll = (1..8).map { readByte().toInt() and 0xff }.joinToString()
assertEquals("18, 52, 86, 120, 154, 188, 222, 240", ll)
assertEquals(0x123456789abcdef0, readLong())
assertEquals("OK", readUTF8Line())
}
Implemented with tests in https://github.com/altavir/kotlinx-io/commit/9ab810d76f7ce23890d901cb5787f6c01d52d360 and https://github.com/altavir/kotlinx-io/commit/6602436c89426b4a6323dd6f6e75da70d8404f03
the .read{} call plays well in my mind as a coroutinecontext with keys supporting the needs of readers, writers, and parser frameworks given their specific generic context keys that reduce the explicit accumulators and signalling parameters of being semi-stateful expression evaluations
We're rebooting the kotlinx-io development (see https://github.com/Kotlin/kotlinx-io/issues/131), all issues related to the previous versions will be closed. Consider reopening it if the issue remains (or the feature is still missing) in a new version.