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

net.dankito.utils.extensions.BufferExtensions.kt Maven / Gradle / Ivy

There is a newer version: 1.0.20
Show newest version
package net.dankito.utils.extensions

import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.channels.SeekableByteChannel


val Buffer.isFull: Boolean
    get() = this.position() == this.capacity()

/**
 * Flips a buffer (= sets it from writing to reading mode), ensures all buffer data gets written to channel and then
 * clears the buffer.
 */
fun ByteBuffer.writeToChannel(channel: SeekableByteChannel) {
    if (this.position() > 0) {
        this.flip()
    }

    while (this.hasRemaining()) {
        channel.write(this)
    }

    this.clear()
}


fun ByteBuffer.putString(string: String) {
    for (char in string) {
        this.putChar(char)
    }
}

fun ByteBuffer.putStringAndFlip(string: String) {
    putString(string)

    this.flip()
}

fun ByteBuffer.getString(): String {
    val stringBuilder = StringBuilder()

    while (this.hasRemaining()) {
        stringBuilder.append(this.char)
    }

    return stringBuilder.toString()
}

fun ByteBuffer.flipAndGetString(): String {
    this.flip()

    return getString()
}

fun ByteBuffer.flipGetStringAndClear(): String {
    val string = flipAndGetString()

    this.clear()

    return string
}


fun ByteBuffer.getData(): ByteArray {
    val data = ByteArray(this.limit())

    this.get(data)

    return data
}

fun ByteBuffer.flipAndGetData(): ByteArray {
    this.flip()

    return getData()
}

fun ByteBuffer.flipGetDataAndClear(): ByteArray {
    val data = flipAndGetData()

    this.clear()

    return data
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy