dev.mzarnowski.infra.Reader.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of buffer Show documentation
Show all versions of buffer Show documentation
Buffer supporting single writer and multiple readers
The newest version!
package dev.mzarnowski.infra
class Reader internal constructor(private val buffer: Buffer, private var first: Int) {
private val mask = buffer.mask
private val writer = buffer.writer
private var available = 0
fun position(): Int = first
fun claim(amount: Int): Int {
if (available < amount) {
available = (writer.position() - first) and mask
}
return available
}
fun read(offset: Int): A = buffer.read((first + offset) and mask)
fun readAll(): Array {
val available = claim(Int.MAX_VALUE)
return buffer.read(first, available).also {
release(available)
}
}
fun release(n: Int) {
val to = (first + n) and mask
// should be done ASAP to unblock writer
buffer.readers.replace(first, to)
available -= n
first = to
}
fun dispose() {
buffer.readers.decrease(first)
}
}