From 74653e74c6a6974db3cf51b658e289173a98fbb4 Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Wed, 11 Dec 2019 15:06:18 +0300 Subject: [PATCH] Direct memory for file reading. --- .../kotlin/scientifik/memory/ByteBufferMemory.kt | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/kmath-memory/src/jvmMain/kotlin/scientifik/memory/ByteBufferMemory.kt b/kmath-memory/src/jvmMain/kotlin/scientifik/memory/ByteBufferMemory.kt index 30a87228a..df2e9847a 100644 --- a/kmath-memory/src/jvmMain/kotlin/scientifik/memory/ByteBufferMemory.kt +++ b/kmath-memory/src/jvmMain/kotlin/scientifik/memory/ByteBufferMemory.kt @@ -1,6 +1,10 @@ package scientifik.memory import java.nio.ByteBuffer +import java.nio.channels.FileChannel +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption /** @@ -11,7 +15,7 @@ actual fun Memory.Companion.allocate(length: Int): Memory { return ByteBufferMemory(buffer) } -class ByteBufferMemory( +private class ByteBufferMemory( val buffer: ByteBuffer, val startOffset: Int = 0, override val size: Int = buffer.limit() @@ -90,4 +94,13 @@ class ByteBufferMemory( } override fun writer(): MemoryWriter = writer +} + +/** + * Use direct memory-mapped buffer from file to read something and close it afterwards. + */ +fun Path.readAsMemory(position: Long = 0, size: Long = Files.size(this), block: Memory.() -> R): R { + return FileChannel.open(this, StandardOpenOption.READ).use { + ByteBufferMemory(it.map(FileChannel.MapMode.READ_ONLY, position, size)).block() + } } \ No newline at end of file