Last active
October 27, 2020 19:22
-
-
Save mguilherme/884dfd85b08f7b4e91b6fb151d9bbc8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
plugins { | |
... | |
kotlin("plugin.serialization") version "1.4.10" | |
} | |
dependencies { | |
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0") | |
implementation("org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.0.0") | |
} | |
*/ | |
fun main(args: Array<String>) { | |
val content = Content(UUID.randomUUID().toString(), "my-body") | |
val order = Order(UUID.randomUUID().toString(), "my title", content) | |
val bytes = ProtoBuf.encodeToByteArray(order) | |
println(bytes.toAsciiHexString()) | |
val obj = ProtoBuf.decodeFromByteArray<Order>(bytes) | |
println(obj) | |
// Prints: | |
// {0A}$d06f6392-1b9d-43de-88ea-c822b8f402f9{12}{08}my title{1A}/{0A}$d81bf9cf-65ee-4741-882c-51ca4248e0e4{12}{07}my-body | |
// Order(id=d06f6392-1b9d-43de-88ea-c822b8f402f9, title=my title, content=Content(id=d81bf9cf-65ee-4741-882c-51ca4248e0e4, body=my-body)) | |
} | |
fun ByteArray.toAsciiHexString() = joinToString("") { | |
if (it in 32..127) it.toChar().toString() else | |
"{${it.toUByte().toString(16).padStart(2, '0').toUpperCase()}}" | |
} | |
@Serializable | |
data class Order(val id: String, val title: String, val content: Content) | |
@Serializable | |
data class Content(val id: String, val body: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment