package ru.dbotthepony.kstarbound.api import java.io.* import java.nio.ByteBuffer interface IVFS { fun pathExists(path: String): Boolean fun read(path: String): ByteBuffer { return readOrNull(path) ?: throw FileNotFoundException("No such file $path") } fun readOrNull(path: String): ByteBuffer? fun readString(path: String): String { return read(path).array().toString(Charsets.UTF_8) } fun getReader(path: String): Reader { return InputStreamReader(ByteArrayInputStream(read(path).array())) } fun listFiles(path: String): Collection fun readDirect(path: String): ByteBuffer { val read = read(path) val buf = ByteBuffer.allocateDirect(read.capacity()) read.position(0) for (i in 0 until read.capacity()) { buf.put(read[i]) } buf.position(0) return buf } } class PhysicalFS(root: File) : IVFS { val root: File = root.absoluteFile override fun pathExists(path: String): Boolean { if (path.contains("..")) { return false } return File(root.absolutePath, path).exists() } override fun readOrNull(path: String): ByteBuffer? { if (path.contains("..")) { return null } val fpath = File(root.path, path) if (!fpath.exists()) { return null } val reader = fpath.inputStream() val buf = ByteBuffer.allocate(reader.channel.size().toInt()) reader.read(buf.array()) return buf } override fun listFiles(path: String): List { if (path.contains("..")) { return listOf() } val fpath = File(root.absolutePath, path) return fpath.listFiles()?.map { it.path.replace('\\', '/').substring(root.path.length) } ?: return listOf() } }