summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt
diff options
context:
space:
mode:
authorDico <dico.karssiens@gmail.com>2018-09-23 20:42:14 +0100
committerDico <dico.karssiens@gmail.com>2018-09-23 20:42:14 +0100
commitb0d1fab486e04a415f971bb02f5ba76b83a62351 (patch)
tree0ebdb67ef24142a69c97dc945e4f76b0e26353b9 /src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt
parent535df42c54bd95960ea7e1bd1a81fd6012c24f11 (diff)
Do some work on interactables
Diffstat (limited to 'src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt')
-rw-r--r--src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt b/src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt
new file mode 100644
index 0000000..80f41b2
--- /dev/null
+++ b/src/main/kotlin/io/dico/parcels2/storage/DataConverters.kt
@@ -0,0 +1,38 @@
+package io.dico.parcels2.storage
+
+import java.lang.IllegalArgumentException
+import java.nio.ByteBuffer
+import java.util.UUID
+
+/* For putting it into the database */
+fun UUID.toByteArray(): ByteArray =
+ ByteBuffer.allocate(16).apply {
+ putLong(mostSignificantBits)
+ putLong(leastSignificantBits)
+ }.array()
+
+/* For getting it out of the database */
+fun ByteArray.toUUID(): UUID =
+ ByteBuffer.wrap(this).run {
+ val mostSignificantBits = getLong()
+ val leastSignificantBits = getLong()
+ UUID(mostSignificantBits, leastSignificantBits)
+ }
+
+/* For putting it into the database */
+fun IntArray.toByteArray(): ByteArray =
+ ByteBuffer.allocate(size * Int.SIZE_BYTES).also { buf ->
+ buf.asIntBuffer().put(this)
+ }.array()
+
+/* For getting it out of the database */
+fun ByteArray.toIntArray(): IntArray {
+ if (this.size % Int.SIZE_BYTES != 0)
+ throw IllegalArgumentException("Size must be divisible by ${Int.SIZE_BYTES}")
+
+ return ByteBuffer.wrap(this).run {
+ IntArray(remaining() / 4).also { array ->
+ asIntBuffer().get(array)
+ }
+ }
+} \ No newline at end of file