Skip to content

Instantly share code, notes, and snippets.

@cancel-cloud
Created April 12, 2022 16:31
Show Gist options
  • Save cancel-cloud/e33f630f3a8a2aa161e50f4f6aeb336f to your computer and use it in GitHub Desktop.
Save cancel-cloud/e33f630f3a8a2aa161e50f4f6aeb336f to your computer and use it in GitHub Desktop.
package de.cancelcloud.utils
import org.bukkit.inventory.ItemStack
import org.bukkit.util.io.BukkitObjectInputStream
import org.bukkit.util.io.BukkitObjectOutputStream
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
object Base64 {
@Throws(IOException::class)
fun itemStackArrayFromBase64(data: String?): Array<ItemStack?> {
return try {
val inputStream = ByteArrayInputStream(Base64Coder.decodeLines(data))
val dataInput = BukkitObjectInputStream(inputStream)
val items = arrayOfNulls<ItemStack>(dataInput.readInt())
// Read the serialized inventory
for (i in items.indices) {
items[i] = dataInput.readObject() as ItemStack?
}
dataInput.close()
items
} catch (e: ClassNotFoundException) {
throw IOException("Unable to decode class type.", e)
}
}
@Throws(IllegalStateException::class)
fun itemStackArrayToBase64(items: Array<ItemStack>): String? {
return try {
val outputStream = ByteArrayOutputStream()
val dataOutput = BukkitObjectOutputStream(outputStream)
// Write the size of the inventory
dataOutput.writeInt(items.size)
// Save every element in the list
for (i in items.indices) {
dataOutput.writeObject(items[i])
}
// Serialize that array
dataOutput.close()
Base64Coder.encodeLines(outputStream.toByteArray())
} catch (e: Exception) {
throw IllegalStateException("Unable to save item stacks.", e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment