Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4165da5e81 | ||
|
|
af463163bb | ||
|
|
6df06a6911 | ||
|
|
f805e1ee82 | ||
|
|
790cce0d24 | ||
|
|
2339130241 | ||
|
|
d7bd159fcb | ||
|
|
12b209c724 | ||
|
|
20181c63a1 |
No files matched your search
@@ -14,3 +14,4 @@ xcuserdata
|
||||
.gigaide
|
||||
/kotlin-js-store/yarn.lock
|
||||
/test.lyng
|
||||
/sample_texts/1.txt.gz
|
||||
+4
-2
@@ -7,12 +7,14 @@ Important thing is that maps can't contain `null`: it is used to return from mis
|
||||
|
||||
Constructed map instance is of class `Map` and implements `Collection` (and therefore `Iterable`)
|
||||
|
||||
val map = Map( ["foo", 1], ["bar", "buzz"] )
|
||||
val map = Map( "foo" => 1, "bar" => "buzz" )
|
||||
assert(map is Map)
|
||||
assert(map.size == 2)
|
||||
assert(map is Iterable)
|
||||
>>> void
|
||||
|
||||
Notice usage of the `=>` operator that creates `MapEntry`, which implements also [Collection] of
|
||||
two items, first, at index zero, is a key, second, at index 1, is the value. You can use lists too.
|
||||
Map keys could be any objects (hashable, e.g. with reasonable hashCode, most of standard types are). You can access elements with indexing operator:
|
||||
|
||||
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||
@@ -31,7 +33,7 @@ To remove item from the collection. use `remove`. It returns last removed item o
|
||||
hold nulls in the map - this is not a recommended practice when using `remove` returned value. `clear()`
|
||||
removes all.
|
||||
|
||||
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||
val map = Map( "foo" => 1, "bar" => "buzz", [42, "answer"] )
|
||||
assertEquals( 1, map.remove("foo") )
|
||||
assert( map.getOrNull("foo") == null)
|
||||
assert( map.size == 2 )
|
||||
|
||||
@@ -4,7 +4,7 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
group = "net.sergeych"
|
||||
version = "0.7.4-SNAPSHOT"
|
||||
version = "0.8.0-SNAPSHOT"
|
||||
|
||||
buildscript {
|
||||
repositories {
|
||||
|
||||
@@ -2,6 +2,7 @@ package net.sergeych.lyng
|
||||
|
||||
import net.sergeych.lyng.obj.Obj
|
||||
import net.sergeych.lyng.obj.ObjList
|
||||
import net.sergeych.lyng.obj.ObjRecord
|
||||
|
||||
/**
|
||||
* List of argument declarations in the __definition__ of the lambda, class constructor,
|
||||
@@ -22,17 +23,20 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
||||
}
|
||||
|
||||
/**
|
||||
* parse args and create local vars in a given context
|
||||
* parse args and create local vars in a given context properly interpreting
|
||||
* ellipsis args and default values
|
||||
*/
|
||||
suspend fun assignToContext(
|
||||
scope: Scope,
|
||||
arguments: Arguments = scope.args,
|
||||
defaultAccessType: AccessType = AccessType.Var,
|
||||
defaultVisibility: Visibility = Visibility.Public
|
||||
defaultVisibility: Visibility = Visibility.Public,
|
||||
defaultRecordType: ObjRecord.Type = ObjRecord.Type.ConstructorField
|
||||
) {
|
||||
fun assign(a: Item, value: Obj) {
|
||||
scope.addItem(a.name, (a.accessType ?: defaultAccessType).isMutable, value,
|
||||
a.visibility ?: defaultVisibility)
|
||||
a.visibility ?: defaultVisibility,
|
||||
recordType = defaultRecordType)
|
||||
}
|
||||
|
||||
// will be used with last lambda arg fix
|
||||
|
||||
@@ -1122,7 +1122,7 @@ class Compiler(
|
||||
thisObj
|
||||
}
|
||||
// inheritance must alter this code:
|
||||
val newClass = ObjClass(className).apply {
|
||||
val newClass = ObjInstanceClass(className).apply {
|
||||
instanceConstructor = constructorCode
|
||||
constructorMeta = constructorArgsDeclaration
|
||||
}
|
||||
@@ -1630,7 +1630,7 @@ class Compiler(
|
||||
// create a separate copy:
|
||||
val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull
|
||||
|
||||
context.addItem(name, isMutable, initValue, visibility)
|
||||
context.addItem(name, isMutable, initValue, visibility, recordType = ObjRecord.Type.Field)
|
||||
initValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,9 +116,10 @@ open class Scope(
|
||||
name: String,
|
||||
isMutable: Boolean,
|
||||
value: Obj,
|
||||
visibility: Visibility = Visibility.Public
|
||||
visibility: Visibility = Visibility.Public,
|
||||
recordType: ObjRecord.Type = ObjRecord.Type.Other
|
||||
): ObjRecord {
|
||||
return ObjRecord(value, isMutable, visibility).also { objects[name] = it }
|
||||
return ObjRecord(value, isMutable, visibility,type = recordType).also { objects[name] = it }
|
||||
}
|
||||
|
||||
fun getOrCreateNamespace(name: String): ObjClass {
|
||||
|
||||
@@ -131,6 +131,12 @@ class Script(
|
||||
if( a.compareTo(this, b) != 0 )
|
||||
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} == ${b.inspect()}"))
|
||||
}
|
||||
addVoidFn("assertNotEquals") {
|
||||
val a = requiredArg<Obj>(0)
|
||||
val b = requiredArg<Obj>(1)
|
||||
if( a.compareTo(this, b) == 0 )
|
||||
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} != ${b.inspect()}"))
|
||||
}
|
||||
addFn("assertThrows") {
|
||||
val code = requireOnlyArg<Statement>()
|
||||
val result =try {
|
||||
|
||||
@@ -57,13 +57,20 @@ open class Obj {
|
||||
args: Arguments = Arguments.EMPTY
|
||||
): T = invokeInstanceMethod(scope, name, args) as T
|
||||
|
||||
/**
|
||||
* Invoke a method of the object if exists
|
||||
* it [onNotFoundResult] is not null, it returns it when symbol is not found
|
||||
* otherwise throws [ObjSymbolNotDefinedException] object exception
|
||||
*/
|
||||
open suspend fun invokeInstanceMethod(
|
||||
scope: Scope,
|
||||
name: String,
|
||||
args: Arguments = Arguments.EMPTY
|
||||
args: Arguments = Arguments.EMPTY,
|
||||
onNotFoundResult: Obj?=null
|
||||
): Obj =
|
||||
// note that getInstanceMember traverses the hierarchy
|
||||
objClass.getInstanceMember(scope.pos, name).value.invoke(scope, this, args)
|
||||
objClass.getInstanceMemberOrNull(name)?.value?.invoke(scope, this, args)
|
||||
?: onNotFoundResult
|
||||
?: scope.raiseSymbolNotFound(name)
|
||||
|
||||
open suspend fun getInstanceMethod(
|
||||
scope: Scope,
|
||||
@@ -341,7 +348,7 @@ object ObjNull : Obj() {
|
||||
scope.raiseNPE()
|
||||
}
|
||||
|
||||
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj {
|
||||
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments, onNotFoundResult: Obj?): Obj {
|
||||
scope.raiseNPE()
|
||||
}
|
||||
|
||||
@@ -366,6 +373,7 @@ object ObjNull : Obj() {
|
||||
override suspend fun lynonType(): LynonType {
|
||||
return LynonType.Null
|
||||
}
|
||||
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
if (lynonType == null) {
|
||||
encoder.putBit(0)
|
||||
|
||||
@@ -82,9 +82,7 @@ open class ObjBuffer(val byteArray: UByteArray) : Obj() {
|
||||
override suspend fun lynonType(): LynonType = LynonType.Buffer
|
||||
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
encoder.encodeCached(byteArray) {
|
||||
bout.compress(byteArray.asByteArray())
|
||||
}
|
||||
encoder.encodeCachedBytes(byteArray.asByteArray())
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -11,6 +11,8 @@ open class ObjClass(
|
||||
vararg parents: ObjClass,
|
||||
) : Obj() {
|
||||
|
||||
val classNameObj by lazy { ObjString(className) }
|
||||
|
||||
var constructorMeta: ArgsDeclaration? = null
|
||||
var instanceConstructor: Statement? = null
|
||||
|
||||
@@ -95,11 +97,14 @@ open class ObjClass(
|
||||
return super.readField(scope, name)
|
||||
}
|
||||
|
||||
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj {
|
||||
return classMembers[name]?.value?.invoke(scope, this, args) ?: super.invokeInstanceMethod(scope, name, args)
|
||||
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
|
||||
onNotFoundResult: Obj?): Obj {
|
||||
return classMembers[name]?.value?.invoke(scope, this, args)
|
||||
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||
}
|
||||
|
||||
open suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj = scope.raiseNotImplemented()
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package net.sergeych.lyng.obj
|
||||
|
||||
import net.sergeych.lyng.Arguments
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lynon.LynonDecoder
|
||||
import net.sergeych.lynon.LynonEncoder
|
||||
import net.sergeych.lynon.LynonType
|
||||
|
||||
@@ -29,14 +30,15 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
||||
} ?: super.writeField(scope, name, newValue)
|
||||
}
|
||||
|
||||
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj =
|
||||
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
|
||||
onNotFoundResult: Obj?): Obj =
|
||||
instanceScope[name]?.let {
|
||||
if (it.visibility.isPublic)
|
||||
it.value.invoke(scope, this, args)
|
||||
else
|
||||
scope.raiseError(ObjAccessException(scope, "can't invoke non-public method $name"))
|
||||
}
|
||||
?: super.invokeInstanceMethod(scope, name, args)
|
||||
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||
|
||||
private val publicFields: Map<String, ObjRecord>
|
||||
get() = instanceScope.objects.filter { it.value.visibility.isPublic }
|
||||
@@ -49,19 +51,51 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
val meta = objClass.constructorMeta
|
||||
?: scope.raiseError("can't serialize non-serializable object (no constructor meta)")
|
||||
for( p in meta.params) {
|
||||
val r = readField(scope, p.name)
|
||||
println("serialize ${p.name}=${r.value}")
|
||||
TODO()
|
||||
// encoder.encodeObj(scope, r.value)
|
||||
// actual constructor can vary, for example, adding new fields with default
|
||||
// values, so we save size of the construction:
|
||||
|
||||
// using objlist allow for some optimizations:
|
||||
val params = meta.params.map { readField(scope, it.name).value }
|
||||
encoder.encodeAnyList(scope, params)
|
||||
serializeStateVars(scope, encoder)
|
||||
}
|
||||
|
||||
protected val instanceVars: Map<String, ObjRecord> by lazy {
|
||||
instanceScope.objects.filter { it.value.type.serializable }
|
||||
}
|
||||
|
||||
protected suspend fun serializeStateVars(scope: Scope,encoder: LynonEncoder) {
|
||||
val vars = instanceVars.values.map { it.value }
|
||||
if( vars.isNotEmpty()) {
|
||||
encoder.encodeAnyList(scope, vars)
|
||||
println("serialized state vars $vars")
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun deserializeStateVars(scope: Scope, decoder: LynonDecoder) {
|
||||
val localVars = instanceVars.values.toList()
|
||||
if( localVars.isNotEmpty() ) {
|
||||
println("gonna read vars")
|
||||
val vars = decoder.decodeAnyList(scope)
|
||||
if (vars.size > instanceVars.size)
|
||||
scope.raiseIllegalArgument("serialized vars has bigger size than instance vars")
|
||||
println("deser state vars $vars")
|
||||
for ((i, v) in vars.withIndex()) {
|
||||
localVars[i].value = vars[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected val comparableVars: Map<String, ObjRecord> by lazy {
|
||||
instanceScope.objects.filter {
|
||||
it.value.type.comparable
|
||||
}
|
||||
// todo: possible vars?
|
||||
}
|
||||
|
||||
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||
if (other !is ObjInstance) return -1
|
||||
if (other.objClass != objClass) return -1
|
||||
for (f in publicFields) {
|
||||
for (f in comparableVars) {
|
||||
val a = f.value.value
|
||||
val b = other.instanceScope[f.key]!!.value
|
||||
val d = a.compareTo(scope, b)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package net.sergeych.lyng.obj
|
||||
|
||||
import net.sergeych.lyng.Arguments
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lynon.LynonDecoder
|
||||
import net.sergeych.lynon.LynonType
|
||||
|
||||
/**
|
||||
* Special variant of [ObjClass] to be used in [ObjInstance], e.g. for Lyng compiled classes
|
||||
*/
|
||||
class ObjInstanceClass(val name: String) : ObjClass(name) {
|
||||
|
||||
// val onDeserilaized =
|
||||
|
||||
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||
val args = decoder.decodeAnyList(scope)
|
||||
println("deserializing constructor $name, $args params")
|
||||
val actualSize = constructorMeta?.params?.size ?: 0
|
||||
if( args.size > actualSize )
|
||||
scope.raiseIllegalArgument("constructor $name has only $actualSize but serialized version has ${args.size}")
|
||||
val newScope = scope.copy(args = Arguments(args))
|
||||
return (callOn(newScope) as ObjInstance).apply {
|
||||
deserializeStateVars(scope,decoder)
|
||||
invokeInstanceMethod(scope, "onDeserialized", onNotFoundResult = ObjVoid)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -117,6 +117,7 @@ class ObjInt(var value: Long, override val isConst: Boolean = false) : Obj(), Nu
|
||||
LynonType.Int0 -> {}
|
||||
LynonType.IntPositive -> encoder.encodeUnsigned(value.toULong())
|
||||
LynonType.IntNegative -> encoder.encodeUnsigned((-value).toULong())
|
||||
LynonType.IntSigned -> encoder.encodeSigned(value)
|
||||
else -> scope.raiseIllegalArgument("Unsupported lynon type code for Int: $lynonType")
|
||||
}
|
||||
}
|
||||
@@ -131,6 +132,7 @@ class ObjInt(var value: Long, override val isConst: Boolean = false) : Obj(), Nu
|
||||
LynonType.Int0 -> Zero
|
||||
LynonType.IntPositive -> ObjInt(decoder.unpackUnsigned().toLong())
|
||||
LynonType.IntNegative -> ObjInt(-decoder.unpackUnsigned().toLong())
|
||||
LynonType.IntSigned -> ObjInt(decoder.unpackSigned())
|
||||
else -> scope.raiseIllegalState("illegal type code for Int: $lynonType")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ package net.sergeych.lyng.obj
|
||||
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lyng.statement
|
||||
import net.sergeych.lynon.LynonDecoder
|
||||
import net.sergeych.lynon.LynonEncoder
|
||||
import net.sergeych.lynon.LynonType
|
||||
|
||||
class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||
|
||||
@@ -125,9 +128,18 @@ class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||
return list == other.list
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("List", ObjArray).apply {
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
encoder.encodeAnyList(scope,list)
|
||||
}
|
||||
|
||||
override suspend fun lynonType(): LynonType = LynonType.List
|
||||
|
||||
companion object {
|
||||
val type = object : ObjClass("List", ObjArray) {
|
||||
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||
return ObjList(decoder.decodeAnyList(scope))
|
||||
}
|
||||
}.apply {
|
||||
createField("size",
|
||||
statement {
|
||||
(thisObj as ObjList).list.size.toObj()
|
||||
|
||||
@@ -2,6 +2,9 @@ package net.sergeych.lyng.obj
|
||||
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lyng.Statement
|
||||
import net.sergeych.lynon.LynonDecoder
|
||||
import net.sergeych.lynon.LynonEncoder
|
||||
import net.sergeych.lynon.LynonType
|
||||
|
||||
class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
|
||||
|
||||
@@ -12,6 +15,14 @@ class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
|
||||
return value.compareTo(scope, other.value)
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return key.hashCode() + value.hashCode()
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
return other is ObjMapEntry && key == other.key && value == other.value
|
||||
}
|
||||
|
||||
override suspend fun getAt(scope: Scope, index: Obj): Obj = when (index.toInt()) {
|
||||
0 -> key
|
||||
1 -> value
|
||||
@@ -24,11 +35,23 @@ class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
|
||||
|
||||
override val objClass = type
|
||||
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
encoder.encodeAny(scope,key)
|
||||
encoder.encodeAny(scope,value)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type = object : ObjClass("MapEntry", ObjArray) {
|
||||
override suspend fun callOn(scope: Scope): Obj {
|
||||
return ObjMapEntry(scope.requiredArg<Obj>(0), scope.requiredArg<Obj>(1))
|
||||
}
|
||||
|
||||
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||
return ObjMapEntry(
|
||||
decoder.decodeAny(scope),
|
||||
decoder.decodeAny(scope)
|
||||
)
|
||||
}
|
||||
}.apply {
|
||||
addFn("key") { thisAs<ObjMapEntry>().key }
|
||||
addFn("value") { thisAs<ObjMapEntry>().value }
|
||||
@@ -71,6 +94,15 @@ class ObjMap(val map: MutableMap<Obj, Obj> = mutableMapOf()) : Obj() {
|
||||
return map == other.map
|
||||
}
|
||||
|
||||
override suspend fun lynonType(): LynonType = LynonType.Map
|
||||
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
val keys = map.keys.map { it.toObj() }
|
||||
val values = map.values.map { it.toObj() }
|
||||
encoder.encodeAnyList(scope, keys)
|
||||
encoder.encodeAnyList(scope, values, fixedSize = true)
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
suspend fun listToMap(scope: Scope, list: List<Obj>): MutableMap<Obj, Obj> {
|
||||
@@ -98,6 +130,13 @@ class ObjMap(val map: MutableMap<Obj, Obj> = mutableMapOf()) : Obj() {
|
||||
override suspend fun callOn(scope: Scope): Obj {
|
||||
return ObjMap(listToMap(scope, scope.args.list))
|
||||
}
|
||||
|
||||
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||
val keys = decoder.decodeAnyList(scope)
|
||||
val values = decoder.decodeAnyList(scope,fixedSize = keys.size)
|
||||
if( keys.size != values.size) scope.raiseIllegalArgument("map keys and values should be same size")
|
||||
return ObjMap(keys.zip(values).toMap().toMutableMap())
|
||||
}
|
||||
}.apply {
|
||||
addFn("getOrNull") {
|
||||
val key = args.firstAndOnly(pos)
|
||||
|
||||
@@ -10,8 +10,17 @@ data class ObjRecord(
|
||||
var value: Obj,
|
||||
val isMutable: Boolean,
|
||||
val visibility: Visibility = Visibility.Public,
|
||||
var importedFrom: Scope? = null
|
||||
var importedFrom: Scope? = null,
|
||||
val isTransient: Boolean = false,
|
||||
val type: Type = Type.Other
|
||||
) {
|
||||
enum class Type(val comparable: Boolean = false,val serializable: Boolean = false) {
|
||||
Field(true, true),
|
||||
@Suppress("unused")
|
||||
Fun,
|
||||
ConstructorField(true, true),
|
||||
Other
|
||||
}
|
||||
@Suppress("unused")
|
||||
fun qualifiedName(name: String): String =
|
||||
"${importedFrom?.packageName ?: "anonymous"}.$name"
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package net.sergeych.lyng.obj
|
||||
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lynon.LynonDecoder
|
||||
import net.sergeych.lynon.LynonEncoder
|
||||
import net.sergeych.lynon.LynonType
|
||||
|
||||
class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() {
|
||||
|
||||
@@ -80,6 +83,12 @@ class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() {
|
||||
return set == other.set
|
||||
}
|
||||
|
||||
override suspend fun lynonType(): LynonType = LynonType.Set
|
||||
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
encoder.encodeAnyList(scope, set.toList())
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
|
||||
@@ -87,6 +96,9 @@ class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() {
|
||||
override suspend fun callOn(scope: Scope): Obj {
|
||||
return ObjSet(scope.args.list.toMutableSet())
|
||||
}
|
||||
|
||||
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
||||
ObjSet(decoder.decodeAnyList(scope).toMutableSet())
|
||||
}.apply {
|
||||
addFn("size") {
|
||||
thisAs<ObjSet>().set.size.toObj()
|
||||
|
||||
@@ -84,21 +84,13 @@ data class ObjString(val value: String) : Obj() {
|
||||
override suspend fun lynonType(): LynonType = LynonType.String
|
||||
|
||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||
if( lynonType == null )
|
||||
encoder.encodeCached(this) { encoder.encodeBinaryData(value.encodeToByteArray()) }
|
||||
else
|
||||
encoder.encodeBinaryData(value.encodeToByteArray())
|
||||
}
|
||||
|
||||
|
||||
companion object {
|
||||
val type = object : ObjClass("String") {
|
||||
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
||||
if( lynonType == null )
|
||||
decoder.decodeCached {
|
||||
ObjString(decoder.unpackBinaryData().decodeToString())
|
||||
}
|
||||
else ObjString(decoder.unpackBinaryData().decodeToString())
|
||||
}.apply {
|
||||
addFn("toInt") {
|
||||
ObjInt(thisAs<ObjString>().value.toLong())
|
||||
|
||||
@@ -3,6 +3,7 @@ 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) {
|
||||
|
||||
@@ -17,10 +18,11 @@ open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSe
|
||||
val cache = mutableListOf<Any>()
|
||||
|
||||
|
||||
inline fun <T : Any>decodeCached(f: LynonDecoder.() -> T): T {
|
||||
inline fun <reified T : Any> 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 {
|
||||
@@ -29,19 +31,55 @@ open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSe
|
||||
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}")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// todo: rewrite/remove?
|
||||
suspend fun unpackObject(scope: Scope, type: ObjClass): Obj {
|
||||
return type.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<Obj> {
|
||||
return if (bin.getBit() == 1) {
|
||||
// homogenous
|
||||
val type = LynonType.entries[getBitsAsInt(4)]
|
||||
val list = mutableListOf<Obj>()
|
||||
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..<size) {
|
||||
list += decodeObject(scope, objClass, type).also {
|
||||
println("decoded: $it")
|
||||
}
|
||||
}
|
||||
list
|
||||
} else {
|
||||
val size = fixedSize ?: unpackUnsigned().toInt()
|
||||
(0..<size).map { decodeAny(scope) }.toMutableList()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun decodeObject(scope: Scope, type: ObjClass, overrideType: LynonType? = null): Obj {
|
||||
return decodeCached { type.deserialize(scope, this, overrideType) }
|
||||
}
|
||||
|
||||
fun unpackBinaryData(): ByteArray = bin.decompress()
|
||||
|
||||
@@ -4,21 +4,45 @@ import net.sergeych.bintools.ByteChunk
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lyng.obj.*
|
||||
|
||||
enum class LynonType(val objClass: ObjClass) {
|
||||
Null(ObjNull.objClass),
|
||||
Int0(ObjInt.type),
|
||||
IntNegative(ObjInt.type),
|
||||
IntPositive(ObjInt.type),
|
||||
String(ObjString.type),
|
||||
enum class LynonType(val objClass: ObjClass, val defaultFrequency: Int = 1) {
|
||||
Null(ObjNull.objClass, 80),
|
||||
Int0(ObjInt.type, 70),
|
||||
IntNegative(ObjInt.type, 50),
|
||||
IntPositive(ObjInt.type, 100),
|
||||
IntSigned(ObjInt.type, 30),
|
||||
String(ObjString.type, 100),
|
||||
Real(ObjReal.type),
|
||||
Bool(ObjBool.type),
|
||||
List(ObjList.type),
|
||||
Map(ObjMap.type),
|
||||
Bool(ObjBool.type, 80),
|
||||
List(ObjList.type, 70),
|
||||
Map(ObjMap.type, 40),
|
||||
Set(ObjSet.type),
|
||||
Buffer(ObjBuffer.type),
|
||||
Instant(ObjInstant.type),
|
||||
Buffer(ObjBuffer.type, 50),
|
||||
Instant(ObjInstant.type, 30),
|
||||
Duration(ObjDuration.type),
|
||||
Other(Obj.rootObjectType);
|
||||
Other(Obj.rootObjectType, 60);
|
||||
|
||||
fun generalizeTo(other: LynonType): LynonType? {
|
||||
if (this == other) return this
|
||||
return (if (this.isInt && other.isInt) {
|
||||
when {
|
||||
this == Int0 -> other // upgrade 0 to some other int
|
||||
other == Int0 -> this // 0 is member of our class, ignore
|
||||
// different signum propagate to signed
|
||||
else -> IntSigned
|
||||
}
|
||||
} else
|
||||
// impossible to generalize
|
||||
null
|
||||
).also { println("Gen $this + $other -> $it") }
|
||||
}
|
||||
|
||||
val isInt by lazy {
|
||||
when (this) {
|
||||
Int0, IntSigned, IntPositive, IntNegative -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = LynonSettings.default) {
|
||||
@@ -29,14 +53,20 @@ open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = Lynon
|
||||
|
||||
suspend fun serializeAndCache(key: Any = item) {
|
||||
cache[key]?.let { cacheId ->
|
||||
// println("encode: Cache hit: ${cacheId}: $item: ${item::class.simpleName}")
|
||||
val size = sizeInBits(cache.size)
|
||||
bout.putBit(1)
|
||||
bout.putBits(cacheId.toULong(), size)
|
||||
} ?: run {
|
||||
bout.putBit(0)
|
||||
if (settings.shouldCache(item))
|
||||
cache[key] = cache.size
|
||||
if (settings.shouldCache(item)) {
|
||||
// println("encode add cache: ${cache.size}: $item: ${item::class.simpleName}")
|
||||
packer()
|
||||
cache[key] = cache.size
|
||||
} else {
|
||||
// println("encode but not cache $item")
|
||||
packer()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,20 +83,78 @@ open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = Lynon
|
||||
*
|
||||
* Caching is used automatically.
|
||||
*/
|
||||
suspend fun encodeAny(scope: Scope, value: Obj) {
|
||||
encodeCached(value) {
|
||||
val type = value.lynonType()
|
||||
putType(type)
|
||||
value.serialize(scope, this, type)
|
||||
suspend fun encodeAny(scope: Scope, obj: Obj) {
|
||||
encodeCached(obj) {
|
||||
val type = putTypeRecord(scope, obj, obj.lynonType())
|
||||
obj.serialize(scope, this, type)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun putTypeRecord(scope: Scope, obj: Obj, type: LynonType): LynonType {
|
||||
putType(type)
|
||||
if( type == LynonType.Other) {
|
||||
encodeObject(scope, obj.objClass.classNameObj)
|
||||
}
|
||||
return type
|
||||
}
|
||||
|
||||
private fun putType(type: LynonType) {
|
||||
bout.putBits(type.ordinal.toULong(), 4)
|
||||
}
|
||||
|
||||
suspend fun encodeObj(scope: Scope, obj: Obj) {
|
||||
obj.serialize(scope, this, null)
|
||||
/**
|
||||
* AnyList could be homogenous (first bit=1) and heterogeneous (first bit=0). Homogenous list
|
||||
* has a single type record that precedes the list, heterogeneous hash typed record
|
||||
* for each item.
|
||||
*
|
||||
*/
|
||||
suspend fun encodeAnyList(scope: Scope, list: List<Obj>,fixedSize: Boolean = false) {
|
||||
if( list.isEmpty()) {
|
||||
// any-typed, empty, save space
|
||||
putBit(0)
|
||||
encodeUnsigned(0u)
|
||||
}
|
||||
else {
|
||||
val objClass = list[0].objClass
|
||||
var type = list[0].lynonType()
|
||||
var isHomogeneous = true
|
||||
for (i in list.drop(1))
|
||||
if (i.objClass != objClass) {
|
||||
isHomogeneous = false
|
||||
break
|
||||
} else {
|
||||
// same class but type might need generalization
|
||||
type = type.generalizeTo(i.lynonType())
|
||||
?: scope.raiseError("inner error: can't generalize lynon type $type to ${i.lynonType()}")
|
||||
}
|
||||
if (isHomogeneous) {
|
||||
putBit(1)
|
||||
putTypeRecord(scope, list[0], type)
|
||||
if (!fixedSize)
|
||||
encodeUnsigned(list.size.toULong())
|
||||
for (i in list) encodeObject(scope, i, type)
|
||||
} else {
|
||||
putBit(0)
|
||||
if (!fixedSize)
|
||||
encodeUnsigned(list.size.toULong())
|
||||
for (i in list) encodeAny(scope, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object _with no type record_: type is known
|
||||
*/
|
||||
suspend fun encodeObject(scope: Scope, obj: Obj,overrideType: LynonType? = null) {
|
||||
encodeCached(obj) {
|
||||
obj.serialize(scope, this, overrideType)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun encodeCachedBytes(bytes: ByteArray) {
|
||||
encodeCached(bytes) {
|
||||
bout.compress(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fun encodeBinaryData(data: ByteArray) {
|
||||
|
||||
@@ -1,38 +1,68 @@
|
||||
package net.sergeych.lynon
|
||||
|
||||
import net.sergeych.collections.SortedList
|
||||
import net.sergeych.lynon.Huffman.Alphabet
|
||||
|
||||
|
||||
/**
|
||||
* Experimental, reference implementation of Huffman trees and encoding.
|
||||
*
|
||||
* This is a reference huffman encoding implementation not yet ready;
|
||||
* it was used to experiment with LZW, at the moment, LZW won the competition
|
||||
* for compressed module format for its speed and sufficiently small size/
|
||||
*
|
||||
* This is byte-based compressor which makes it not too interesting.
|
||||
*
|
||||
* TODO: convert to use various source dictionary
|
||||
*
|
||||
* reason: version thant compress bytes is not too interesting; particular alphabets
|
||||
* are often longer than byte bits and are often sparse, that requires another
|
||||
* codes serialization implementation
|
||||
* Generic huffman encoding implementation using bits input/output and abstract [Alphabet].
|
||||
*/
|
||||
object Huffman {
|
||||
|
||||
/**
|
||||
* Alphabet interface: source can be variable bit size codes, not just bytes,
|
||||
* so the Huffman encoding is not limited to bytes. It works with any alphabet
|
||||
* using its _ordinals_; encoding between source symbols and ordinals are
|
||||
* performed by the alphabet. See [byteAlphabet] for example.
|
||||
*/
|
||||
interface Alphabet<T> {
|
||||
val maxOrdinal: Int
|
||||
|
||||
/**
|
||||
* Write correct symbol for the [ordinal] to the [bout]. This is
|
||||
* the inverse of [ordinalOf] but as [T] could be variable bit size,
|
||||
* we provide output bit stream.
|
||||
*/
|
||||
fun decodeOrdinalTo(bout: BitOutput, ordinal: Int)
|
||||
|
||||
/**
|
||||
* Find the ordinal of the source symbol
|
||||
*/
|
||||
fun ordinalOf(value: T): Int
|
||||
|
||||
operator fun get(ordinal: Int): T
|
||||
}
|
||||
|
||||
/**
|
||||
* Alphabet for unsigned bytes, allows to encode bytes easily
|
||||
*/
|
||||
val byteAlphabet = object : Alphabet<UByte> {
|
||||
override val maxOrdinal: Int
|
||||
get() = 256
|
||||
|
||||
override fun decodeOrdinalTo(bout: BitOutput, ordinal: Int) {
|
||||
bout.putBits(ordinal, 8)
|
||||
}
|
||||
|
||||
override fun ordinalOf(value: UByte): Int = value.toInt()
|
||||
|
||||
override operator fun get(ordinal: Int): UByte = ordinal.toUByte()
|
||||
}
|
||||
|
||||
sealed class Node(val freq: Int) : Comparable<Node> {
|
||||
override fun compareTo(other: Node): Int {
|
||||
return freq.compareTo(other.freq)
|
||||
}
|
||||
|
||||
abstract fun decode(bin: BitInput): Int?
|
||||
abstract fun decodeOrdinal(bin: BitInput): Int?
|
||||
|
||||
class Leaf(val value: Int, freq: Int) : Node(freq) {
|
||||
class Leaf(val ordinal: Int, freq: Int) : Node(freq) {
|
||||
override fun toString(): String {
|
||||
return "[$value:$freq]"
|
||||
return "[$ordinal:$freq]"
|
||||
}
|
||||
|
||||
override fun decode(bin: BitInput): Int {
|
||||
return value//.also { println(": ${Char(value)}") }
|
||||
override fun decodeOrdinal(bin: BitInput): Int {
|
||||
return ordinal//.also { println(": ${Char(value)}") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,33 +71,33 @@ object Huffman {
|
||||
return "[${left.freq}<- :<$freq>: ->${right.freq}]"
|
||||
}
|
||||
|
||||
override fun decode(bin: BitInput): Int? {
|
||||
override fun decodeOrdinal(bin: BitInput): Int? {
|
||||
return when (bin.getBitOrNull().also { print("$it") }) {
|
||||
1 -> left.decode(bin)
|
||||
0 -> right.decode(bin)
|
||||
1 -> left.decodeOrdinal(bin)
|
||||
0 -> right.decodeOrdinal(bin)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class Code(val symbol: Int, val bits: TinyBits) {
|
||||
data class Code(val ordinal: Int, val bits: TinyBits) {
|
||||
|
||||
val size by bits::size
|
||||
|
||||
override fun toString(): String {
|
||||
return "[${Char(symbol)}:$size:$bits]"
|
||||
return "[$ordinal:$size:$bits]"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private fun generateCanonicCodes(tree: Node): List<Code?> {
|
||||
val codes = MutableList<Code?>(256) { null }
|
||||
private fun generateCanonicCodes(tree: Node, alphabet: Alphabet<*>): List<Code?> {
|
||||
val codes = MutableList<Code?>(alphabet.maxOrdinal) { null }
|
||||
|
||||
fun traverse(node: Node, code: TinyBits) {
|
||||
when (node) {
|
||||
is Node.Leaf ->
|
||||
codes[node.value] = (Code(node.value, code))
|
||||
codes[node.ordinal] = (Code(node.ordinal, code))
|
||||
|
||||
is Node.Internal -> {
|
||||
traverse(node.left, code.insertBit(1))
|
||||
@@ -77,17 +107,17 @@ object Huffman {
|
||||
}
|
||||
traverse(tree, TinyBits())
|
||||
|
||||
return makeCanonical(codes)
|
||||
return makeCanonical(codes, alphabet)
|
||||
}
|
||||
|
||||
private fun makeCanonical(source: List<Code?>): List<Code?> {
|
||||
private fun makeCanonical(source: List<Code?>,alphabet: Alphabet<*>): List<Code?> {
|
||||
val sorted = source.filterNotNull().sortedWith(canonicComparator)
|
||||
|
||||
val canonical = MutableList<Code?>(256) { null }
|
||||
val canonical = MutableList<Code?>(alphabet.maxOrdinal) { null }
|
||||
|
||||
val first = sorted[0]
|
||||
val prevValue = first.copy(bits = TinyBits(0UL, first.bits.size))
|
||||
canonical[first.symbol] = prevValue
|
||||
canonical[first.ordinal] = prevValue
|
||||
var prev = prevValue.bits
|
||||
|
||||
for (i in 1..<sorted.size) {
|
||||
@@ -96,7 +126,7 @@ object Huffman {
|
||||
while (code.bits.size > bits.size) {
|
||||
bits = bits.insertBit(0)
|
||||
}
|
||||
canonical[code.symbol] = code.copy(bits = bits)//.also { println("$it") }
|
||||
canonical[code.ordinal] = code.copy(bits = bits)//.also { println("$it") }
|
||||
prev = bits
|
||||
}
|
||||
return canonical
|
||||
@@ -104,18 +134,21 @@ object Huffman {
|
||||
|
||||
private val canonicComparator = { a: Code, b: Code ->
|
||||
if (a.bits.size == b.bits.size) {
|
||||
a.symbol.compareTo(b.symbol)
|
||||
a.ordinal.compareTo(b.ordinal)
|
||||
} else {
|
||||
a.bits.size.compareTo(b.bits.size)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildTree(data: UByteArray): Node {
|
||||
// println(data.toDump())
|
||||
val frequencies = Array(256) { 0 }
|
||||
data.forEach { frequencies[it.toInt()]++ }
|
||||
private fun buildTree(data: Iterable<Int>,alphabet: Alphabet<*>): Node {
|
||||
val frequencies = buildFrequencies(alphabet, data)
|
||||
return buildTree(frequencies)
|
||||
}
|
||||
|
||||
val list = SortedList<Node>(*frequencies.mapIndexed { index, i -> Node.Leaf(index, i) }.filter { it.freq > 0 }
|
||||
private fun buildTree(frequencies: Array<Int>): Node {
|
||||
// println(data.toDump())
|
||||
|
||||
val list: SortedList<Node> = SortedList(*frequencies.mapIndexed { index, frequency -> Node.Leaf(index, frequency) }.filter { it.freq > 0 }
|
||||
.toTypedArray())
|
||||
|
||||
// build the tree
|
||||
@@ -127,8 +160,18 @@ object Huffman {
|
||||
return list[0]
|
||||
}
|
||||
|
||||
fun decompressUsingCodes(bin: BitInput, codes: List<Code?>): UByteArray {
|
||||
val result = mutableListOf<UByte>()
|
||||
private fun buildFrequencies(
|
||||
alphabet: Alphabet<*>,
|
||||
data: Iterable<Int>
|
||||
): Array<Int> {
|
||||
val maxOrdinal = alphabet.maxOrdinal
|
||||
val frequencies = Array(maxOrdinal) { 0 }
|
||||
data.forEach { frequencies[it]++ }
|
||||
return frequencies
|
||||
}
|
||||
|
||||
fun decompressUsingCodes(bin: BitInput, codes: List<Code?>, alphabet: Alphabet<*>): BitArray {
|
||||
val result = MemoryBitOutput()
|
||||
val table = codes.filterNotNull().associateBy { it.bits }
|
||||
|
||||
outer@ while (true) {
|
||||
@@ -139,12 +182,12 @@ object Huffman {
|
||||
val data = table[input]
|
||||
if (data != null) {
|
||||
// println("Code found: ${data.bits} -> [${data.symbol.toChar()}]")
|
||||
result.add(data.symbol.toUByte())
|
||||
alphabet.decodeOrdinalTo(result,data.ordinal)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.toUByteArray()
|
||||
return result.toBitArray()
|
||||
}
|
||||
|
||||
private fun serializeCanonicCodes(bout: BitOutput, codes: List<Code?>) {
|
||||
@@ -167,11 +210,11 @@ object Huffman {
|
||||
}
|
||||
}
|
||||
|
||||
fun deserializeCanonicCodes(bin: BitInput): List<Code?> {
|
||||
fun deserializeCanonicCodes(bin: BitInput, alphabet: Alphabet<*>): List<Code?> {
|
||||
val minSize = bin.unpackUnsigned().toInt()
|
||||
val sizeInBits = bin.unpackUnsigned().toInt()
|
||||
val sorted = mutableListOf<Code>().also { codes ->
|
||||
for (i in 0..<256) {
|
||||
for (i in 0..<alphabet.maxOrdinal) {
|
||||
val s = bin.getBits(sizeInBits).toInt()
|
||||
if (s > 0) {
|
||||
codes.add(Code(i, TinyBits(0U, s - 1 + minSize)))
|
||||
@@ -179,66 +222,53 @@ object Huffman {
|
||||
}
|
||||
}.sortedWith(canonicComparator)
|
||||
|
||||
val result = MutableList<Code?>(256) { null }
|
||||
val result = MutableList<Code?>(alphabet.maxOrdinal) { null }
|
||||
var prev = sorted[0].copy(bits = TinyBits(0U, sorted[0].bits.size))
|
||||
result[prev.symbol] = prev
|
||||
result[prev.ordinal] = prev
|
||||
|
||||
for (i in 1..<sorted.size) {
|
||||
val code = sorted[i]
|
||||
var bits = TinyBits(prev.bits.value + 1u, prev.bits.size)
|
||||
while (bits.size < code.bits.size) bits = bits.insertBit(0)
|
||||
result[code.symbol] = code.copy(bits = bits).also {
|
||||
result[code.ordinal] = code.copy(bits = bits).also {
|
||||
prev = it
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun compress(data: UByteArray): BitArray {
|
||||
// fun generateCanonicalCodes(frequencies: Iterable<Int>): List<Code?> {
|
||||
//
|
||||
// }
|
||||
|
||||
val root = buildTree(data)
|
||||
fun generateCanonicalCodes(frequencies: Array<Int>,alphabet: Alphabet<*>): List<Code?> =
|
||||
generateCanonicCodes(buildTree(frequencies), alphabet)
|
||||
|
||||
val codes = generateCanonicCodes(root)
|
||||
fun <T>compress(plain: Iterable<T>,alphabet: Alphabet<T>): BitArray {
|
||||
|
||||
val source = plain.map { alphabet.ordinalOf(it) }
|
||||
val root = buildTree(source,alphabet)
|
||||
|
||||
val codes = generateCanonicCodes(root, alphabet)
|
||||
|
||||
// serializa table
|
||||
|
||||
// test encode:
|
||||
val bout = MemoryBitOutput()
|
||||
serializeCanonicCodes(bout, codes)
|
||||
for (i in data) {
|
||||
val code = codes[i.toInt()]!!
|
||||
for (i in source) {
|
||||
val code = codes[i]!!
|
||||
// println(">> $code")
|
||||
bout.putBits(code.bits)
|
||||
}
|
||||
// println(bout.toBitArray().bytes.toDump())
|
||||
val compressed = bout.toBitArray()
|
||||
// println("Size: ${compressed.bytes.size / data.size.toDouble() }")
|
||||
// println("compression ratio: ${compressed.bytes.size / data.size.toDouble() }")
|
||||
|
||||
// test decompress
|
||||
// val bin = MemoryBitInput(compressed)
|
||||
// val codes2 = deserializeCanonicCodes(bin)
|
||||
// for ((a, b) in codes.zip(codes2)) {
|
||||
// if (a != b) {
|
||||
// println("Codes mismatch: $a != $b")
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// require(codes == codes2)
|
||||
// val result = decompressUsingCodes(bin, codes2)
|
||||
//
|
||||
//// println(result.toUByteArray().toDump())
|
||||
// check(data contentEquals result.toUByteArray())
|
||||
// if( !(data contentEquals result.toUByteArray()) )
|
||||
// throw RuntimeException("Data mismatch")
|
||||
// println(data.toDump())
|
||||
//
|
||||
return compressed
|
||||
}
|
||||
|
||||
fun decompress(bin: BitInput): UByteArray {
|
||||
val codes = deserializeCanonicCodes(bin)
|
||||
return decompressUsingCodes(bin, codes)
|
||||
fun <T>decompress(bin: BitInput,alphabet: Alphabet<T>): UByteArray {
|
||||
val codes = deserializeCanonicCodes(bin, alphabet)
|
||||
return decompressUsingCodes(bin, codes, alphabet).asUbyteArray()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2242,6 +2242,14 @@ class ScriptTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSet2() = runTest {
|
||||
eval("""
|
||||
assertEquals( Set( ...[1,2,3]), Set(1,2,3) )
|
||||
assertEquals( Set( ...[1,false,"ok"]), Set("ok", 1, false) )
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testLet() = runTest {
|
||||
eval(
|
||||
|
||||
@@ -50,4 +50,27 @@ class TypesTest {
|
||||
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUserClassCompareTo() = runTest {
|
||||
eval("""
|
||||
class Point(val a,b)
|
||||
|
||||
assertEquals(Point(0,1), Point(0,1) )
|
||||
assertNotEquals(Point(0,1), Point(1,1) )
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUserClassCompareTo2() = runTest {
|
||||
eval("""
|
||||
class Point(val a,b) {
|
||||
var c = 0
|
||||
}
|
||||
assertEquals(Point(0,1), Point(0,1) )
|
||||
assertEquals(Point(0,1).apply { c = 2 }, Point(0,1).apply { c = 2 } )
|
||||
assertNotEquals(Point(0,1), Point(1,1) )
|
||||
assertNotEquals(Point(0,1), Point(0,1).apply { c = 1 } )
|
||||
""".trimIndent())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import junit.framework.TestCase.*
|
||||
import junit.framework.TestCase.assertNotSame
|
||||
import junit.framework.TestCase.assertSame
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import net.sergeych.bintools.encodeToHex
|
||||
import net.sergeych.lyng.Scope
|
||||
@@ -9,6 +10,9 @@ import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class LynonTests {
|
||||
|
||||
@Test
|
||||
@@ -53,6 +57,7 @@ class LynonTests {
|
||||
assertEquals(1, bin.getBit())
|
||||
assertEquals(null, bin.getBitOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testBitOutputMedium() {
|
||||
val bout = MemoryBitOutput()
|
||||
@@ -144,34 +149,43 @@ class LynonTests {
|
||||
assertEquals(1471792L, bin.unpackSigned())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testObjStringAndStringKeys() = runTest {
|
||||
val s = "foo"
|
||||
val sobj = ObjString("foo")
|
||||
val map = mutableMapOf(s to 1, sobj to 2)
|
||||
assertEquals(1, map[s])
|
||||
assertEquals(2, map[sobj])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCache1() = runTest {
|
||||
val bout = MemoryBitOutput()
|
||||
val encoder = LynonEncoder(bout)
|
||||
val s = "Hello, World!".toObj()
|
||||
val scope = Scope()
|
||||
encoder.encodeObj(scope, s) // 1
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObj(scope, s) // 8
|
||||
encoder.encodeObject(scope, s) // 1
|
||||
encoder.encodeObject(scope, s)
|
||||
encoder.encodeObject(scope, s)
|
||||
encoder.encodeObject(scope, s)
|
||||
encoder.encodeObject(scope, s)
|
||||
encoder.encodeObject(scope, s)
|
||||
encoder.encodeObject(scope, s)
|
||||
encoder.encodeObject(scope, s) // 8
|
||||
|
||||
val decoder = LynonDecoder(MemoryBitInput(bout))
|
||||
val s1 = decoder.unpackObject(scope, ObjString.type) // 1
|
||||
val s1 = decoder.decodeObject(scope, ObjString.type) // 1
|
||||
assertEquals(s, s1)
|
||||
assertNotSame(s, s1)
|
||||
val s2 = decoder.unpackObject(scope, ObjString.type)
|
||||
val s2 = decoder.decodeObject(scope, ObjString.type)
|
||||
assertEquals(s, s2)
|
||||
assertSame(s1, s2)
|
||||
assertSame(s1, decoder.unpackObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.unpackObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.unpackObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.unpackObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.unpackObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) // 8
|
||||
assertSame(s1, decoder.decodeObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.decodeObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.decodeObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.decodeObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.decodeObject(scope, ObjString.type))
|
||||
assertSame(s1, decoder.decodeObject(scope, ObjString.type)) // 8
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -182,12 +196,12 @@ class LynonTests {
|
||||
val encoder = LynonPacker()
|
||||
val scope = Scope()
|
||||
for (s in source) {
|
||||
encoder.encodeObj(scope, s)
|
||||
encoder.encodeObject(scope, s)
|
||||
}
|
||||
val decoder = LynonUnpacker(encoder)
|
||||
val restored = mutableListOf<Obj>()
|
||||
for (i in source.indices) {
|
||||
restored.add(decoder.unpackObject(scope, ObjString.type))
|
||||
restored.add(decoder.decodeObject(scope, ObjString.type))
|
||||
}
|
||||
assertEquals(restored, source)
|
||||
}
|
||||
@@ -196,58 +210,59 @@ class LynonTests {
|
||||
fun testUnpackBoolean() = runTest {
|
||||
val scope = Scope()
|
||||
val decoder = LynonUnpacker(LynonPacker().apply {
|
||||
encodeObj(scope, ObjBool(true))
|
||||
encodeObj(scope, ObjBool(false))
|
||||
encodeObj(scope, ObjBool(true))
|
||||
encodeObj(scope, ObjBool(true))
|
||||
encodeObject(scope, ObjBool(true))
|
||||
encodeObject(scope, ObjBool(false))
|
||||
encodeObject(scope, ObjBool(true))
|
||||
encodeObject(scope, ObjBool(true))
|
||||
})
|
||||
assertEquals(ObjTrue, decoder.unpackObject(scope, ObjBool.type))
|
||||
assertEquals(ObjFalse, decoder.unpackObject(scope, ObjBool.type))
|
||||
assertEquals(ObjTrue, decoder.unpackObject(scope, ObjBool.type))
|
||||
assertEquals(ObjTrue, decoder.unpackObject(scope, ObjBool.type))
|
||||
assertEquals(ObjTrue, decoder.decodeObject(scope, ObjBool.type))
|
||||
assertEquals(ObjFalse, decoder.decodeObject(scope, ObjBool.type))
|
||||
assertEquals(ObjTrue, decoder.decodeObject(scope, ObjBool.type))
|
||||
assertEquals(ObjTrue, decoder.decodeObject(scope, ObjBool.type))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUnpackReal() = runTest {
|
||||
val scope = Scope()
|
||||
val decoder = LynonUnpacker(LynonPacker().apply {
|
||||
encodeObj(scope, ObjReal(-Math.PI))
|
||||
encodeObj(scope, ObjReal(Math.PI))
|
||||
encodeObj(scope, ObjReal(-Math.PI))
|
||||
encodeObj(scope, ObjReal(Math.PI))
|
||||
encodeObj(scope, ObjReal(Double.NaN))
|
||||
encodeObj(scope, ObjReal(Double.NEGATIVE_INFINITY))
|
||||
encodeObj(scope, ObjReal(Double.POSITIVE_INFINITY))
|
||||
encodeObj(scope, ObjReal(Double.MIN_VALUE))
|
||||
encodeObj(scope, ObjReal(Double.MAX_VALUE))
|
||||
encodeObject(scope, ObjReal(-Math.PI))
|
||||
encodeObject(scope, ObjReal(Math.PI))
|
||||
encodeObject(scope, ObjReal(-Math.PI))
|
||||
encodeObject(scope, ObjReal(Math.PI))
|
||||
encodeObject(scope, ObjReal(Double.NaN))
|
||||
encodeObject(scope, ObjReal(Double.NEGATIVE_INFINITY))
|
||||
encodeObject(scope, ObjReal(Double.POSITIVE_INFINITY))
|
||||
encodeObject(scope, ObjReal(Double.MIN_VALUE))
|
||||
encodeObject(scope, ObjReal(Double.MAX_VALUE))
|
||||
})
|
||||
assertEquals(ObjReal(-Math.PI), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Math.PI), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(-Math.PI), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Math.PI), decoder.unpackObject(scope, ObjReal.type))
|
||||
assert((decoder.unpackObject(scope, ObjReal.type)).toDouble().isNaN())
|
||||
assertEquals(ObjReal(Double.NEGATIVE_INFINITY), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Double.POSITIVE_INFINITY), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Double.MIN_VALUE), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Double.MAX_VALUE), decoder.unpackObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(-Math.PI), decoder.decodeObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Math.PI), decoder.decodeObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(-Math.PI), decoder.decodeObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Math.PI), decoder.decodeObject(scope, ObjReal.type))
|
||||
assert((decoder.decodeObject(scope, ObjReal.type)).toDouble().isNaN())
|
||||
assertEquals(ObjReal(Double.NEGATIVE_INFINITY), decoder.decodeObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Double.POSITIVE_INFINITY), decoder.decodeObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Double.MIN_VALUE), decoder.decodeObject(scope, ObjReal.type))
|
||||
assertEquals(ObjReal(Double.MAX_VALUE), decoder.decodeObject(scope, ObjReal.type))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUnpackInt() = runTest {
|
||||
val scope = Scope()
|
||||
val decoder = LynonUnpacker(LynonPacker().apply {
|
||||
encodeObj(scope, ObjInt(0))
|
||||
encodeObj(scope, ObjInt(-1))
|
||||
encodeObj(scope, ObjInt(23))
|
||||
encodeObj(scope, ObjInt(Long.MIN_VALUE))
|
||||
encodeObj(scope, ObjInt(Long.MAX_VALUE))
|
||||
encodeObj(scope, ObjInt(Long.MAX_VALUE))
|
||||
encodeObject(scope, ObjInt(0))
|
||||
encodeObject(scope, ObjInt(-1))
|
||||
encodeObject(scope, ObjInt(23))
|
||||
encodeObject(scope, ObjInt(Long.MIN_VALUE))
|
||||
encodeObject(scope, ObjInt(Long.MAX_VALUE))
|
||||
encodeObject(scope, ObjInt(Long.MAX_VALUE))
|
||||
})
|
||||
assertEquals(ObjInt(0), decoder.unpackObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(-1), decoder.unpackObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(23), decoder.unpackObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(Long.MIN_VALUE), decoder.unpackObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(Long.MAX_VALUE), decoder.unpackObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(Long.MAX_VALUE), decoder.unpackObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(0), decoder.decodeObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(-1), decoder.decodeObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(23), decoder.decodeObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(Long.MIN_VALUE), decoder.decodeObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(Long.MAX_VALUE), decoder.decodeObject(scope, ObjInt.type))
|
||||
assertEquals(ObjInt(Long.MAX_VALUE), decoder.decodeObject(scope, ObjInt.type))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -273,10 +288,12 @@ class LynonTests {
|
||||
|
||||
@Test
|
||||
fun testEncodeNullsAndInts() = runTest {
|
||||
testScope().eval("""
|
||||
testScope().eval(
|
||||
"""
|
||||
testEncode(null)
|
||||
testEncode(0)
|
||||
""".trimIndent())
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -290,7 +307,9 @@ class LynonTests {
|
||||
}
|
||||
|
||||
suspend fun testScope() =
|
||||
Scope().apply { eval("""
|
||||
Scope().apply {
|
||||
eval(
|
||||
"""
|
||||
import lyng.serialization
|
||||
fun testEncode(value) {
|
||||
val encoded = Lynon.encode(value)
|
||||
@@ -298,21 +317,25 @@ class LynonTests {
|
||||
println("Encoded size %d: %s"(encoded.size, value))
|
||||
assertEquals( value, Lynon.decode(encoded) )
|
||||
}
|
||||
""".trimIndent())
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun testUnaryMinus() = runTest {
|
||||
eval("""
|
||||
eval(
|
||||
"""
|
||||
assertEquals( -1 * π, 0 - π )
|
||||
assertEquals( -1 * π, -π )
|
||||
""".trimIndent())
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSimpleTypes() = runTest {
|
||||
testScope().eval("""
|
||||
testScope().eval(
|
||||
"""
|
||||
testEncode(null)
|
||||
testEncode(0)
|
||||
testEncode(47)
|
||||
@@ -330,7 +353,8 @@ class LynonTests {
|
||||
testEncode("Hello, world".encodeUtf8())
|
||||
testEncode("Hello, world")
|
||||
|
||||
""".trimIndent())
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -382,16 +406,37 @@ class LynonTests {
|
||||
println("Original : ${x.size}")
|
||||
val lzw = LZW.compress(x).bytes
|
||||
println("LZW : ${lzw.size}")
|
||||
val ba = Huffman.compress(x)
|
||||
val ba = Huffman.compress(x, Huffman.byteAlphabet)
|
||||
val huff = ba.bytes
|
||||
println("Huffman : ${huff.size}")
|
||||
val lzwhuff = Huffman.compress(lzw).bytes
|
||||
val lzwhuff = Huffman.compress(lzw, Huffman.byteAlphabet).bytes
|
||||
println("LZW+HUFF : ${lzwhuff.size}")
|
||||
val compressed = Huffman.compress(x)
|
||||
val decompressed = Huffman.decompress(compressed.toBitInput())
|
||||
val compressed = Huffman.compress(x, Huffman.byteAlphabet)
|
||||
val decompressed = Huffman.decompress(compressed.toBitInput(), Huffman.byteAlphabet)
|
||||
assertContentEquals(x, decompressed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGenerateCanonicalHuffmanCodes() {
|
||||
val frequencies = LynonType.entries.map { it.defaultFrequency }.toTypedArray()
|
||||
val alphabet = object : Huffman.Alphabet<LynonType> {
|
||||
override val maxOrdinal = LynonType.entries.size
|
||||
|
||||
override fun decodeOrdinalTo(bout: BitOutput, ordinal: Int) {
|
||||
throw NotImplementedError()
|
||||
}
|
||||
|
||||
override fun get(ordinal: Int): LynonType {
|
||||
return LynonType.entries[ordinal]
|
||||
}
|
||||
|
||||
override fun ordinalOf(value: LynonType): Int = value.ordinal
|
||||
}
|
||||
for (code in Huffman.generateCanonicalCodes(frequencies, alphabet)) {
|
||||
println("${code?.bits}: ${code?.ordinal?.let { LynonType.entries[it] }}")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testBitListSmall() {
|
||||
var t = TinyBits()
|
||||
@@ -451,5 +496,143 @@ class LynonTests {
|
||||
assertEquals(src3, bin.decompressString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testIntList() = runTest {
|
||||
testScope().eval(
|
||||
"""
|
||||
testEncode([1,2,3])
|
||||
testEncode([-1,-2,-3])
|
||||
testEncode([1,-2,-3])
|
||||
testEncode([0,1])
|
||||
testEncode([0,0,0])
|
||||
testEncode(["the", "the", "wall", "the", "wall", "wall"])
|
||||
testEncode([1,2,3, "the", "wall", "wall"])
|
||||
testEncode([false, false, false, true,true])
|
||||
testEncode([])
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNamedObject() = runTest {
|
||||
val s = testScope()
|
||||
val x = s.eval("""5 => 6""")
|
||||
assert(x is ObjMapEntry)
|
||||
val bout = MemoryBitOutput()
|
||||
val e = LynonEncoder(bout)
|
||||
e.encodeAny(s, x)
|
||||
val bin = bout.toBitInput()
|
||||
val d = LynonDecoder(bin)
|
||||
val x2 = d.decodeAny(s)
|
||||
println(x)
|
||||
println(x2)
|
||||
assertTrue { x.compareTo(s, x2) == 0}
|
||||
assertEquals(x, x2)
|
||||
|
||||
s.eval("""
|
||||
testEncode( 1 => "one" )
|
||||
testEncode( [1 => "one", 1 => "one"] )
|
||||
testEncode( [1 => "one", 1 => "one", "foo" => "MapEntry"] )
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testHomogenousMap() = runTest {
|
||||
val s = testScope()
|
||||
s.eval("""
|
||||
testEncode( Map("one" => 1, "two" => 2) )
|
||||
testEncode( Map() )
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testHeterogeneousMap() = runTest {
|
||||
val s = testScope()
|
||||
s.eval("""
|
||||
testEncode(["one", 2])
|
||||
testEncode([1, "2"])
|
||||
testEncode( Map("one" => 1, 2 => 2) )
|
||||
testEncode( Map("one" => 1, 2 => "2") )
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSetSerialization() = runTest {
|
||||
testScope().eval("""
|
||||
testEncode( Set("one", "two") )
|
||||
testEncode( Set() )
|
||||
testEncode( Set(1, "one", false) )
|
||||
testEncode( Set(true, true, false) )
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testClassSerializationNoInstanceVars() = runTest {
|
||||
testScope().eval("""
|
||||
import lyng.serialization
|
||||
|
||||
class Point(x,y)
|
||||
|
||||
// println( Lynon.encode(Point(0,0)).toDump() )
|
||||
testEncode(Point(0,0))
|
||||
testEncode(Point(10,11))
|
||||
testEncode(Point(-1,2))
|
||||
testEncode(Point(-1,-2))
|
||||
testEncode(Point("point!",-2))
|
||||
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testClassSerializationWithInstanceVars() = runTest {
|
||||
testScope().eval("""
|
||||
import lyng.serialization
|
||||
|
||||
class Point(x=0) {
|
||||
var y = 0
|
||||
}
|
||||
|
||||
testEncode(Point())
|
||||
testEncode(Point(1))
|
||||
testEncode(Point(1).apply { y = 2 })
|
||||
testEncode(Point(10).also { it.y = 11 })
|
||||
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testClassSerializationWithInstanceVars2() = runTest {
|
||||
testScope().eval("""
|
||||
import lyng.serialization
|
||||
|
||||
var onInitComment = null
|
||||
|
||||
class Point(x=0) {
|
||||
var y = 0
|
||||
var comment = null
|
||||
|
||||
fun onDeserialized() {
|
||||
onInitComment = comment
|
||||
}
|
||||
}
|
||||
|
||||
testEncode(Point())
|
||||
testEncode(Point(1))
|
||||
testEncode(Point(1).apply { y = 2 })
|
||||
testEncode(Point(10).also { it.y = 11 })
|
||||
|
||||
// important: class init is called before setting non-constructor fields
|
||||
// this is decessary, so deserialized fields are only available
|
||||
// after onDeserialized() call (if exists):
|
||||
// deserialized:
|
||||
testEncode(Point(10).also { it.y = 11; it.comment = "comment" })
|
||||
println("-- on init comment "+onInitComment)
|
||||
assertEquals("comment", onInitComment)
|
||||
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user