Skip to content

Instantly share code, notes, and snippets.

@nothendev
Created October 12, 2022 07:55
Show Gist options
  • Save nothendev/e9fca4a95be330e31ac6ee5d13900b93 to your computer and use it in GitHub Desktop.
Save nothendev/e9fca4a95be330e31ac6ee5d13900b93 to your computer and use it in GitHub Desktop.
Hephaistos kotlinx.serialization
object NBT {
@OptIn(ExperimentalSerializationApi::class)
val json = Json {
isLenient = true
ignoreUnknownKeys = true
coerceInputValues = true
explicitNulls = false
}
@Internal
fun decode(reader: NBTReader) = json.parseToJsonElement(reader.read().toSNBT())
@Internal
fun encode(element: JsonElement) = SNBTParser(element.toString().reader()).parse()
/**
* **Note** It is caller's responsibility to close the [reader]
*/
inline fun <reified T> read(reader: NBTReader): T = json.decodeFromJsonElement(decode(reader))
/**
* **Note** It is caller's responsibility to close the [writer]
*/
inline fun <reified T> write(value: T, writer: NBTWriter, name: String = "") = writer.writeNamed(name, encode(json.encodeToJsonElement(value)))
/**
* A helper function that automatically closes the [writer].
*/
inline fun <reified T> useWrite(writer: NBTWriter, value: T, name: String = "") = writer.use { write(value, it, name) }
/**
* A helper function that automatically closes the [reader].
*/
inline fun <reified T> useRead(reader: NBTReader): T = reader.use { read(it) }
}
inline fun <reified T> NBTWriter.write(value: T) = NBT.useWrite(this, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment