package net.sergeych.lynon import net.sergeych.lyng.Scope import net.sergeych.lyng.obj.Obj import net.sergeych.lyng.obj.ObjClass import net.sergeych.lyng.obj.ObjString open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSettings.default) { fun getBitsAsInt(bitsSize: Int): Int { return bin.getBits(bitsSize).toInt() } fun unpackUnsignedInt(): Int = bin.unpackUnsigned().toInt() fun decompress() = bin.decompress() val cache = mutableListOf() inline fun decodeCached(f: LynonDecoder.() -> T): T { return if (bin.getBit() == 0) { // unpack and cache f().also { // println("decode: cache miss: ${cache.size}: $it:${it::class.simpleName}") if (settings.shouldCache(it)) cache.add(it) } } else { // get cache reference val size = sizeInBits(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}") // println("decode: cache hit ${id}: ${cache[id]}:${cache[id]::class.simpleName}") // @Suppress("UNCHECKED_CAST") cache[id] as T } } suspend fun decodeAny(scope: Scope): Obj = decodeCached { val type = LynonType.entries[bin.getBits(4).toInt()] if (type != LynonType.Other) { type.objClass.deserialize(scope, this, type) } else { decodeClassObj(scope).deserialize(scope, this, null) } } private suspend fun decodeClassObj(scope: Scope): ObjClass { val className = decodeObject(scope, ObjString.type, null) as ObjString println("expected class name $className") return scope.get(className.value)?.value?.let { if (it !is ObjClass) scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}") it } ?: scope.raiseSymbolNotFound("can't deserialize: not found type $className") } suspend fun decodeAnyList(scope: Scope,fixedSize: Int?=null): MutableList { return if (bin.getBit() == 1) { // homogenous val type = LynonType.entries[getBitsAsInt(4)] val list = mutableListOf() val objClass = if (type == LynonType.Other) decodeClassObj(scope).also { println("detected class obj: $it") } else type.objClass val size = fixedSize ?: bin.unpackUnsigned().toInt() println("detected homogenous list type $type, $size items") for (i in 0..