Skip to content

Instantly share code, notes, and snippets.

@camdenorrb camdenorrb/simpleNBT.kt
Last active Oct 2, 2019

Embed
What would you like to do?
/*
MIT License
Copyright (c) 2019 Camden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package me.camdenorrb.afancehmcserverimpl.mc.nmc
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class NBT(val name: String, map: Map<String, Any>) {
val map = map.toMutableMap()
operator fun <T> invoke(key: String): Accessor<T> {
return Accessor(key)
}
fun <T> get(key: String): T {
return map[key] as T
}
fun push(output: File) {
output.parentFile?.mkdirs()
output.createNewFile()
DataOutputStream(GZIPOutputStream(output.outputStream().buffered())).use {
push(it)
}
}
fun push(output: DataOutputStream) {
output.writeByte(10) // Compound ID
output.writeUTF(name) // Compound Name
map.forEach { (name, value) ->
val id = idFor(value)
// Is not compound
if (id != 10) {
output.writeByte(idFor(value))
output.writeUTF(name)
}
push(output, value)
}
output.writeByte(0) // End tag
}
// Push without ID
private fun push(output: DataOutputStream, value: Any): Unit = when(value) {
is Byte -> output.writeByte(value.toInt())
is Short -> output.writeShort(value.toInt())
is Int -> output.writeInt(value)
is Long -> output.writeLong(value)
is Float -> output.writeFloat(value)
is Double -> output.writeDouble(value)
is ByteArray -> output.write(value)
is String -> output.writeUTF(value)
is List<*> -> {
val id = value.firstOrNull()?.let { idFor(it) } ?: 0
output.writeByte(id)
output.writeInt(value.size)
value.forEach {
push(output, it!!)
}
}
is NBT -> value.push(output)
is IntArray -> value.forEach { output.writeInt(it) }
is LongArray -> value.forEach { output.writeLong(it) }
else -> error("Unknown tag: [${value::class.simpleName}] $name = $value")
}
private fun idFor(value: Any) = when(value) {
is Byte -> 1
is Short -> 2
is Int -> 3
is Long -> 4
is Float -> 5
is Double -> 6
is ByteArray -> 7
is String -> 8
is List<*> -> 9
is NBT -> 10
is IntArray -> 11
is LongArray -> 12
else -> error("Unknown tag: [${value::class.simpleName}] $name = $value")
}
override fun toString(): String {
return map.entries.joinToString("\n", "{\n", "\n}") { (name, value) ->
val valueText = if (value is NBT) value.toString() else "$value"
"[${value::class.simpleName}] $name = $valueText".prependIndent(" ")
}
}
companion object {
fun pull(input: File): NBT {
DataInputStream(GZIPInputStream(input.inputStream().buffered())).use {
return pull(it)
}
}
// Don't forget to close yourself
// Provide a buffered stream please <3
fun pull(input: DataInputStream): NBT {
return Reader.read(input)
}
}
inner class Accessor<T> internal constructor(val key: String) : ReadOnlyProperty<Any?, T> {
var value: T? = null
private set
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (value == null) {
value = map[key] as T
}
return value!!
}
}
internal object Reader {
fun read(input: DataInputStream, readID: Boolean = true, name: String? = null): NBT {
if (readID) {
check(input.readByte() == 10.toByte()) {
"Expected a compound, didn't get one :C"
}
}
val nbt = NBT(name ?: input.readUTF(), mapOf())
while (true) {
val inID = input.readByte().toInt()
val inName = if (inID != 0) input.readUTF() else ""
// Is end
if (inID == 0) {
break
}
nbt.map[inName] = readTag(input, inID, inName)
}
return nbt
}
private fun readList(input: DataInputStream): List<*> {
val inID = input.readByte().toInt()
val size = input.readInt()
return List(size) {
readTag(input, inID, "")
}
}
private fun readTag(input: DataInputStream, id: Int, name: String? = null): Any = when(id) {
1 -> input.readByte()
2 -> input.readShort()
3 -> input.readInt()
4 -> input.readLong()
5 -> input.readFloat()
6 -> input.readDouble()
7 -> ByteArray(input.readInt()) { input.readByte() }
8 -> input.readUTF()
9 -> readList(input)
10 -> read(input, false, name)
11 -> IntArray(input.readInt()) { input.readInt() }
12 -> LongArray(input.readInt()) { input.readLong() }
else -> error("Invalid NBT id: $id")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.