
KMPBuffer - Kotlin Multiplatform ByteBuffer Implementation
A Kotlin Multiplatform library providing a cross-platform ByteBuffer implementation compatible with Java NIO semantics, supporting Android, iOS, JVM.
Features
- Multiplatform Support: Write once, run on Android, iOS, JVM
- NIO Compatibility: Familiar API matching Java's
ByteBuffer interface
- Memory Efficiency:
- Direct memory allocation (off-heap) support
- Heap-backed buffers for managed memory
- Endianness Control: Configurable byte order (Big/Little Endian)
- Buffer Operations:
- Absolute/relative get/put methods
- Bulk transfer operations
- Buffer slicing and duplication
- Compact, flip, rewind, and clear operations
- Type Support: Primitive type handling (Char, Short, Int, Long, Float, Double, etc.)
Installation
Add to your build.gradle.kts:
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("io.github.hehua2008:kmpbuffer:0.9.0")
}
}
}
}
Usage
Basic Example
val buffer = allocateDirectByteBuffer(1024)
buffer.putInt(42)
buffer.putDouble(3.14159)
val strBytes = "Hello".encodeToByteArray()
buffer.put(strBytes, 0, strBytes.size)
buffer.flip()
val intValue = buffer.getInt()
val doubleValue = buffer.getDouble()
val byteArray = ByteArray(buffer.remaining()) { buffer.() }
str = byteArray.decodeToString()
buffer.release()
Buffer Allocation
val heapBuffer = allocateHeapByteBuffer(512)
val directBuffer = allocateDirectByteBuffer(1024)
val wrappedBuffer = byteArrayOf(1,2,3,4).wrapInHeapByteBuffer()
Platform-Specific Notes
Building from Source
- Clone the repository
- Build with Gradle:
./gradlew assemble
Contributing
Contributions welcome!
License
Apache License 2.0 - See LICENSE for details