All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlinx.io.nio.Input.kt Maven / Gradle / Ivy

There is a newer version: 0.1.16
Show newest version
package kotlinx.io.nio

import kotlinx.io.core.*
import kotlinx.io.pool.*
import java.nio.*
import java.nio.channels.*

private class ChannelAsInput(private val channel: ReadableByteChannel, pool: ObjectPool) :
    AbstractInput(pool = pool), Input {
    init {
        require(channel !is SelectableChannel || !channel.isBlocking) { "Non-blocking channels as not supported" }
    }

    override fun fill(): IoBuffer? {
        val buffer: IoBuffer = pool.borrow()
        try {
            var rc = -1

            buffer.writeDirect(1) { bb: ByteBuffer ->
                rc = channel.read(bb)
            }

            if (rc == -1) {
                buffer.release(pool)
                return null
            }

            return buffer
        } catch (t: Throwable) {
            buffer.release(pool)
            throw t
        }
    }

    override fun closeSource() {
        channel.close()
    }
}

fun ReadableByteChannel.asInput(pool: ObjectPool = IoBuffer.Pool): Input = ChannelAsInput(this, pool)





© 2015 - 2025 Weber Informatics LLC | Privacy Policy