From 080eac2e1aec319eed5ff50f5737dc7eba03a8c0 Mon Sep 17 00:00:00 2001 From: sergeych Date: Fri, 5 Dec 2025 11:47:42 +0100 Subject: [PATCH] fix #77 Instant.toJson --- .../net/sergeych/lyng/obj/ObjInstant.kt | 5 +++++ lynglib/src/commonTest/kotlin/ScriptTest.kt | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lynglib/src/commonMain/kotlin/net/sergeych/lyng/obj/ObjInstant.kt b/lynglib/src/commonMain/kotlin/net/sergeych/lyng/obj/ObjInstant.kt index 11a091a..cb2e3d4 100644 --- a/lynglib/src/commonMain/kotlin/net/sergeych/lyng/obj/ObjInstant.kt +++ b/lynglib/src/commonMain/kotlin/net/sergeych/lyng/obj/ObjInstant.kt @@ -21,6 +21,8 @@ import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.datetime.isDistantFuture import kotlinx.datetime.isDistantPast +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive import net.sergeych.lyng.Scope import net.sergeych.lynon.LynonDecoder import net.sergeych.lynon.LynonEncoder @@ -89,6 +91,9 @@ class ObjInstant(val instant: Instant,val truncateMode: LynonSettings.InstantTru } } + override suspend fun toJson(scope: Scope): JsonElement = JsonPrimitive(instant.toString()) + + companion object { val distantFuture by lazy { ObjInstant(Instant.DISTANT_FUTURE) diff --git a/lynglib/src/commonTest/kotlin/ScriptTest.kt b/lynglib/src/commonTest/kotlin/ScriptTest.kt index 757e58e..c9471c2 100644 --- a/lynglib/src/commonTest/kotlin/ScriptTest.kt +++ b/lynglib/src/commonTest/kotlin/ScriptTest.kt @@ -23,6 +23,8 @@ import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout +import kotlinx.datetime.Clock +import kotlinx.datetime.Instant import kotlinx.serialization.Serializable import net.sergeych.lyng.* import net.sergeych.lyng.obj.* @@ -3842,6 +3844,25 @@ class ScriptTest { assertEquals(JSTest1("bar", 1, true), x.decodeSerializable()) } + @Test + fun testJsonTime() = runTest { + val now = Clock.System.now() + val x = eval(""" + import lyng.time + Instant.now().truncateToSecond() + """.trimIndent()).decodeSerializable() + println(x) + assertIs(x) + assertTrue( (now - x).absoluteValue < 2.seconds) + } + + @Test + fun testJsonNull() = runTest { + val x = eval("""null""".trimIndent()).decodeSerializable() + println(x) + assertNull(x) + } + @Test fun testInstanceVars() = runTest { var x = eval(