refs #35 caching moved to level above objec serializing so we can cache strings, etc that are not Obj instances

This commit is contained in:
sergeych committed 2025-07-12 11:48:14 +03:00
1 parent f26ee7cd7c
commit 77f9191387
7 files changed
+78 -59

No files matched your search

@@ -4,27 +4,31 @@ import net.sergeych.lyng.Scope
import net.sergeych.lyng.obj.Obj
import net.sergeych.lyng.obj.ObjClass
open class LynonDecoder(private val bin: BitInput) {
open class LynonDecoder(val bin: BitInput) {
val cache = mutableListOf<Obj>()
fun unpackObject(scope: Scope, type: ObjClass): Obj {
inline fun decodeCached(f: LynonDecoder.() -> Obj): Obj {
return if( bin.getBit() == 0 ) {
// unpack and cache
val cached = bin.getBool()
type.deserialize(scope, this).also {
f().also {
if( cached ) cache.add(it)
}
}
else {
// get cache reference
val size = sizeInBits(cache.size)
val id = bin.getBitsOrNull(size)?.toInt() ?: scope.raiseError("Invalid object id: unexpected end of stream")
if( id >= cache.size ) scope.raiseError("Invalid object id: $id should be in 0..<${cache.size}")
val id = bin.getBitsOrNull(size)?.toInt() ?: throw RuntimeException("Invalid object id: unexpected end of stream")
if( id >= cache.size ) throw RuntimeException("Invalid object id: $id should be in 0..<${cache.size}")
cache[id]
}
}
fun unpackObject(scope: Scope, type: ObjClass): Obj {
return decodeCached { type.deserialize(scope, this) }
}
fun unpackBinaryData(): ByteArray? {
val size = bin.unpackUnsigned()
return bin.getBytes(size.toInt())