net.dankito.utils.extensions.BufferExtensions.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
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
}