Last active
February 2, 2022 10:17
-
-
Save elizarov/deeb940c427ff014caf1a2a33472a2fc to your computer and use it in GitHub Desktop.
Trying to serialization sequence coroutine state with Java Serialization
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
import java.io.* | |
fun main() { | |
// test sequence -- 15 fibonacci numbers | |
val seq = sequence { | |
var prev = 0 | |
var cur = 1 | |
repeat(15) { | |
yield(cur) | |
cur += prev.also { prev = cur } | |
} | |
} | |
// update its state | |
val original = seq.iterator() | |
println("Iterate first 5") | |
repeat(5) { | |
println(original.next().toString().padStart(10)) | |
} | |
println("Serializing...") | |
// serialize bytes | |
val bytesOutput = ByteArrayOutputStream() | |
val output = ObjectOutputStream(bytesOutput) | |
output.writeObject(original) | |
val bytes = bytesOutput.toByteArray() | |
println("Got ${bytes.size} bytes: ${bytes.joinToString("") { it.toUByte().toString(16).padStart(2, '0') }}") | |
// deserialize bytes | |
val input = ObjectInputStream(ByteArrayInputStream(bytes)) | |
val result = input.readObject() as Iterator<*> | |
// test the result | |
println("Iterate the rest of deserialized iterator, size-by-side with original one") | |
println("${"original".padStart(10)} ${"result".padStart(10)}") | |
do { | |
val originalNext = if (original.hasNext()) original.next() else null | |
val resultNext = if (result.hasNext()) result.next() else null | |
println("${originalNext.toString().padStart(10)} ${resultNext.toString().padStart(10)}") | |
} while (originalNext != null || resultNext != null) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment