Skip to content

Add kotlin.time.Instant serializers #2945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions core/api/kotlinx-serialization-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,19 @@ public final class kotlinx/serialization/builtins/BuiltinSerializersKt {
public static final fun serializer (Lkotlin/jvm/internal/ShortCompanionObject;)Lkotlinx/serialization/KSerializer;
public static final fun serializer (Lkotlin/jvm/internal/StringCompanionObject;)Lkotlinx/serialization/KSerializer;
public static final fun serializer (Lkotlin/time/Duration$Companion;)Lkotlinx/serialization/KSerializer;
public static final fun serializer (Lkotlin/time/Instant$Companion;)Lkotlinx/serialization/KSerializer;
public static final fun serializer (Lkotlin/uuid/Uuid$Companion;)Lkotlinx/serialization/KSerializer;
}

public final class kotlinx/serialization/builtins/InstantComponentSerializer : kotlinx/serialization/KSerializer {
public static final field INSTANCE Lkotlinx/serialization/builtins/InstantComponentSerializer;
public synthetic fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Ljava/lang/Object;
public fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Lkotlin/time/Instant;
public fun getDescriptor ()Lkotlinx/serialization/descriptors/SerialDescriptor;
public synthetic fun serialize (Lkotlinx/serialization/encoding/Encoder;Ljava/lang/Object;)V
public fun serialize (Lkotlinx/serialization/encoding/Encoder;Lkotlin/time/Instant;)V
}

public final class kotlinx/serialization/builtins/LongAsStringSerializer : kotlinx/serialization/KSerializer {
public static final field INSTANCE Lkotlinx/serialization/builtins/LongAsStringSerializer;
public fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Ljava/lang/Long;
Expand Down Expand Up @@ -795,6 +805,15 @@ public final class kotlinx/serialization/internal/InlineClassDescriptorKt {
public static final fun InlinePrimitiveDescriptor (Ljava/lang/String;Lkotlinx/serialization/KSerializer;)Lkotlinx/serialization/descriptors/SerialDescriptor;
}

public final class kotlinx/serialization/internal/InstantSerializer : kotlinx/serialization/KSerializer {
public static final field INSTANCE Lkotlinx/serialization/internal/InstantSerializer;
public synthetic fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Ljava/lang/Object;
public fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Lkotlin/time/Instant;
public fun getDescriptor ()Lkotlinx/serialization/descriptors/SerialDescriptor;
public synthetic fun serialize (Lkotlinx/serialization/encoding/Encoder;Ljava/lang/Object;)V
public fun serialize (Lkotlinx/serialization/encoding/Encoder;Lkotlin/time/Instant;)V
}

public final class kotlinx/serialization/internal/IntArrayBuilder : kotlinx/serialization/internal/PrimitiveArrayBuilder {
public synthetic fun build$kotlinx_serialization_core ()Ljava/lang/Object;
}
Expand Down
17 changes: 17 additions & 0 deletions core/api/kotlinx-serialization-core.klib.api
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,14 @@ sealed class kotlinx.serialization.modules/SerializersModule { // kotlinx.serial
final fun <#A1: kotlin/Any> getContextual(kotlin.reflect/KClass<#A1>): kotlinx.serialization/KSerializer<#A1>? // kotlinx.serialization.modules/SerializersModule.getContextual|getContextual(kotlin.reflect.KClass<0:0>){0§<kotlin.Any>}[0]
}

final object kotlinx.serialization.builtins/InstantComponentSerializer : kotlinx.serialization/KSerializer<kotlin.time/Instant> { // kotlinx.serialization.builtins/InstantComponentSerializer|null[0]
final val descriptor // kotlinx.serialization.builtins/InstantComponentSerializer.descriptor|{}descriptor[0]
final fun <get-descriptor>(): kotlinx.serialization.descriptors/SerialDescriptor // kotlinx.serialization.builtins/InstantComponentSerializer.descriptor.<get-descriptor>|<get-descriptor>(){}[0]

final fun deserialize(kotlinx.serialization.encoding/Decoder): kotlin.time/Instant // kotlinx.serialization.builtins/InstantComponentSerializer.deserialize|deserialize(kotlinx.serialization.encoding.Decoder){}[0]
final fun serialize(kotlinx.serialization.encoding/Encoder, kotlin.time/Instant) // kotlinx.serialization.builtins/InstantComponentSerializer.serialize|serialize(kotlinx.serialization.encoding.Encoder;kotlin.time.Instant){}[0]
}

final object kotlinx.serialization.builtins/LongAsStringSerializer : kotlinx.serialization/KSerializer<kotlin/Long> { // kotlinx.serialization.builtins/LongAsStringSerializer|null[0]
final val descriptor // kotlinx.serialization.builtins/LongAsStringSerializer.descriptor|{}descriptor[0]
final fun <get-descriptor>(): kotlinx.serialization.descriptors/SerialDescriptor // kotlinx.serialization.builtins/LongAsStringSerializer.descriptor.<get-descriptor>|<get-descriptor>(){}[0]
Expand Down Expand Up @@ -956,6 +964,14 @@ final object kotlinx.serialization.internal/FloatSerializer : kotlinx.serializat
final fun serialize(kotlinx.serialization.encoding/Encoder, kotlin/Float) // kotlinx.serialization.internal/FloatSerializer.serialize|serialize(kotlinx.serialization.encoding.Encoder;kotlin.Float){}[0]
}

final object kotlinx.serialization.internal/InstantSerializer : kotlinx.serialization/KSerializer<kotlin.time/Instant> { // kotlinx.serialization.internal/InstantSerializer|null[0]
final val descriptor // kotlinx.serialization.internal/InstantSerializer.descriptor|{}descriptor[0]
final fun <get-descriptor>(): kotlinx.serialization.descriptors/SerialDescriptor // kotlinx.serialization.internal/InstantSerializer.descriptor.<get-descriptor>|<get-descriptor>(){}[0]

final fun deserialize(kotlinx.serialization.encoding/Decoder): kotlin.time/Instant // kotlinx.serialization.internal/InstantSerializer.deserialize|deserialize(kotlinx.serialization.encoding.Decoder){}[0]
final fun serialize(kotlinx.serialization.encoding/Encoder, kotlin.time/Instant) // kotlinx.serialization.internal/InstantSerializer.serialize|serialize(kotlinx.serialization.encoding.Encoder;kotlin.time.Instant){}[0]
}

final object kotlinx.serialization.internal/IntArraySerializer : kotlinx.serialization.internal/PrimitiveArraySerializer<kotlin/Int, kotlin/IntArray, kotlinx.serialization.internal/IntArrayBuilder>, kotlinx.serialization/KSerializer<kotlin/IntArray> // kotlinx.serialization.internal/IntArraySerializer|null[0]

final object kotlinx.serialization.internal/IntSerializer : kotlinx.serialization/KSerializer<kotlin/Int> { // kotlinx.serialization.internal/IntSerializer|null[0]
Expand Down Expand Up @@ -1074,6 +1090,7 @@ final val kotlinx.serialization.modules/EmptySerializersModule // kotlinx.serial
final fun <get-EmptySerializersModule>(): kotlinx.serialization.modules/SerializersModule // kotlinx.serialization.modules/EmptySerializersModule.<get-EmptySerializersModule>|<get-EmptySerializersModule>(){}[0]

final fun (kotlin.time/Duration.Companion).kotlinx.serialization.builtins/serializer(): kotlinx.serialization/KSerializer<kotlin.time/Duration> // kotlinx.serialization.builtins/serializer|[email protected](){}[0]
final fun (kotlin.time/Instant.Companion).kotlinx.serialization.builtins/serializer(): kotlinx.serialization/KSerializer<kotlin.time/Instant> // kotlinx.serialization.builtins/serializer|[email protected](){}[0]
final fun (kotlin.uuid/Uuid.Companion).kotlinx.serialization.builtins/serializer(): kotlinx.serialization/KSerializer<kotlin.uuid/Uuid> // kotlinx.serialization.builtins/serializer|[email protected](){}[0]
final fun (kotlin/Boolean.Companion).kotlinx.serialization.builtins/serializer(): kotlinx.serialization/KSerializer<kotlin/Boolean> // kotlinx.serialization.builtins/serializer|[email protected](){}[0]
final fun (kotlin/Byte.Companion).kotlinx.serialization.builtins/serializer(): kotlinx.serialization/KSerializer<kotlin/Byte> // kotlinx.serialization.builtins/serializer|[email protected](){}[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import kotlinx.serialization.internal.*
import kotlin.reflect.*
import kotlinx.serialization.descriptors.*
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
import kotlin.time.Instant
import kotlin.uuid.*

/**
Expand Down Expand Up @@ -245,12 +247,30 @@ public fun UShort.Companion.serializer(): KSerializer<UShort> = UShortSerializer

/**
* Returns serializer for [Duration].
* It is serialized as a string that represents a duration in the ISO-8601-2 format.
* It is serialized as a string that represents a duration in the format used by [Duration.toIsoString],
* that is, the ISO-8601-2 format.
*
* The result of serialization is similar to calling [Duration.toIsoString], for deserialization is [Duration.parseIsoString].
* For deserialization, [Duration.parseIsoString] is used.
*
* @see Duration.toIsoString
* @see Duration.parseIsoString
*/
public fun Duration.Companion.serializer(): KSerializer<Duration> = DurationSerializer

/**
* Returns serializer for [Instant].
* It is serialized as a string that represents an instant in the format used by [Instant.toString]
* and described in ISO-8601-1:2019, 5.4.2.1b).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* and described in ISO-8601-1:2019, 5.4.2.1b).
* and described in ISO-8601-1:2019, 5.4.2.1b.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parenthesis is not a typo, it's there because the format is called b) in that part of the ISO document.

*
* Deserialization is case-insensitive.
* More details can be found in the documentation of [Instant.toString] and [Instant.parse] functions.
*
* @see Instant.toString
* @see Instant.parse
*/
@ExperimentalTime
public fun Instant.Companion.serializer(): KSerializer<Instant> = InstantSerializer

/**
* Returns serializer for [Uuid].
* Serializer operates with a standard UUID string representation, also known as "hex-and-dash" format —
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 2025-2025 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.builtins

import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlin.time.ExperimentalTime
import kotlin.time.Instant

/**
* Serializer that encodes and decodes [Instant] as its second and nanosecond components of the Unix time.
*
* JSON example: `{"epochSeconds":1607505416,"nanosecondsOfSecond":124000}`.
*/
@ExperimentalTime
public object InstantComponentSerializer : KSerializer<Instant> {

override val descriptor: SerialDescriptor =
buildClassSerialDescriptor("kotlinx.serialization.InstantComponentSerializer") {
element<Long>("epochSeconds")
element<Long>("nanosecondsOfSecond", isOptional = true)
}

@OptIn(ExperimentalSerializationApi::class)
override fun deserialize(decoder: Decoder): Instant =
decoder.decodeStructure(descriptor) {
var epochSecondsNotSeen = true
var epochSeconds: Long = 0
var nanosecondsOfSecond = 0
while (true) {
when (val index = decodeElementIndex(descriptor)) {
0 -> {
epochSecondsNotSeen = false
epochSeconds = decodeLongElement(descriptor, 0)
}
1 -> nanosecondsOfSecond = decodeIntElement(descriptor, 1)
CompositeDecoder.DECODE_DONE -> break
else -> throw SerializationException("Unexpected index: $index")
}
}
if (epochSecondsNotSeen) throw MissingFieldException(
missingField = "epochSeconds",
serialName = descriptor.serialName
)
Instant.fromEpochSeconds(epochSeconds, nanosecondsOfSecond)
}

@OptIn(ExperimentalSerializationApi::class)
override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeStructure(descriptor) {
encodeLongElement(descriptor, 0, value.epochSeconds)
if (value.nanosecondsOfSecond != 0) {
encodeIntElement(descriptor, 1, value.nanosecondsOfSecond)
}
Comment on lines +55 to +57
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should have a call to shouldEncodeElementDefault as it is up to the format to decide whether or not to encode things (while this doesn't matter for Json it would for a fixed length format).

Copy link
Member

@sandwwraith sandwwraith Apr 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It depends on whether we really want to include nanoseconds:0 in the output even with encodeDefaults = true.

Current behavior would be equal to having @EncodeDefault(NEVER) annotation on Instant.nanosecondsOfSecond

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sandwwraith The issue is for a fixed length format that requires all attributes to be serialized (for example Android's Parcelable). In such case there must be bits written to represent the default value. It is not possible to write a placeholder as any placeholder value could be a valid value, so either the actual default is written or a marker is written (changing the wire format to add a marker byte).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sandwwraith I've played around a bit and added binary tests to the jsonTests in #2979 . This is based upon the EfficientBinaryFormat from the documentation (but cross platform), and for now only in the test code (it was not designed to be used as a production format). To make the tests actually pass it is absolutely necessary to return false to shouldEncodeElementDefault (and EncodeDefault(Mode.NEVER) is not valid for this format).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what the problem is. Descriptor says that nanosecondsOfSecond is optional, so there is no contradiction here. I would say that supporting @EncodeDefault(Mode.NEVER) is a reasonable expectation from any format, including binary. Deserializer would be also fine if format would never return 1 from the decodeElementIndex.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decoder must know whether or not nanosecondsOfSecond is written

Why? InstantComponentSerializer.deserialize() would insert 0 automatically if the decoder won't return index 1.
For the encoder/decoder, everything will happen as if this field never existed in the class.

I think you're confusing optionality support with coercion support, which is done via ElementMarker in protobuf and Json and indeed requires tracking of whether the value was read. However, it is necessary for non-optional values so nulls can be placed there automatically.

Copy link
Contributor

@pdvrieze pdvrieze Apr 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sandwwraith It will not decode 0, it will decode whatever bytes are following the epochSeconds as the format does not have the ability to know that those following bytes do not belong to the Instant.

What I am describing is a format that must be read sequentially and does not have the ability to inspect the bytestream to determine the next element (decodeElementIndex() will have to be strictly sequential: i.e. it returns sequentially: 0, 1, CompositeDecoder.DONE).

You are assuming that the decoder never returns 1 from decodeElementIndex(), but for non-self-describing formats there is nothing to indicate that the nanosecondsOfSecond is not present in the serialized form. Note at least parsing will possibly fail as serialization will attempt more bytes than present in the serialized form.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To show it breaks I have created another branch applying the binary test to the InstantSerializer:
https://github.com/pdvrieze/kotlinx.serialization/tree/pdvrieze/instant-serializers-with-binary-test

This test fails to decode because it tries to decode the nanosecondsOfSecond component.

Btw. I've also updated the branch underlying #2979. It now triggers more often (and the binary format has been rewritten to support out-of-order serialization). There were two sets of changes needed. The error message test needed to be adjusted to check the correct message. More interesting is that for JsonCustomSerializersTest all custom serializers needed to be fixed to call shouldEncodeElementDefault.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see what you mean. Do you have any real-world examples of such formats? IIRC, even binary formats with schema (such as Protobuf or Avro) have some way of denoting the id of the next element in the stream (e.g., protoId).

Still, it would mean that such a format is unable to support @EncodeDefault(NEVER), which IMO limits its usability with kotlinx.serialization.

Besides, InstantComponentSerializer is not the default. I imagine that for such a format one can easily write InstantComponentWithMandatoryNanosecondsSerializer and use it instead. I highly doubt that we should sacrifice convenience for the sake of some hypothetical ultra-fast binary format.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are quite some cases (not supported by kotlinx.serialization). I have looked at some examples:

  • Java serialization (ObjectOutputStream) - when writing primitives no class is written, only the value
  • Android Parcelable - again just writes the values, not types where not required
  • FlatBuffers - It is aimed at access without parsing. The "Structs" type just groups the members.

It is also common in many binary file formats (e.g. PNG, ZIP) or binary network protocols (IP/TCP/TLS/HTTP2.0/dbus) - but even textual line separated formats (e.g. Advent of code data) would may not be self-describing. The EfficientBinaryFormat was actually taken from the documentation (and it has this property). The key factor is whether the format is self-describing (in other words, can be parsed without access to a schema).

The fix for this case would be where the format can influence behaviour (by default it returns false and constant folding should be able to easily optimize the call away):

if (value.nanosecondsOfSecond != 0 || shouldEncodeElementDefault(descriptor, 1)) {

As to @EncodeDefault(NEVER), I would say this has been implemented incorrectly (and possibly misnamed - AVOID would be better). The implementation would be better if shouldEncodeElementDefault were invoked in all cases, but this being an overload that passes the "never" (or avoid) value. The format could then return true if the storage is invalid when defaults are omitted. This approach is probably preferable over requiring a SerializationStrategy to somehow be able to produce default values on request (and certainly more binary compatible).

}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
import kotlin.time.Instant
import kotlin.uuid.*


Expand Down Expand Up @@ -39,6 +41,20 @@ internal object NothingSerializer : KSerializer<Nothing> {
}
}

@PublishedApi
@ExperimentalTime
internal object InstantSerializer : KSerializer<Instant> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("kotlin.time.Instant", PrimitiveKind.STRING)

override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeString(value.toString())
}

override fun deserialize(decoder: Decoder): Instant {
return Instant.parse(decoder.decodeString())
}
}

@PublishedApi
@ExperimentalUuidApi
internal object UuidSerializer: KSerializer<Uuid> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.encoding.CompositeDecoder.Companion.UNKNOWN_NAME
import kotlinx.serialization.modules.*
import kotlinx.serialization.test.*
import kotlin.test.*
import kotlin.time.Duration

Expand Down
4 changes: 3 additions & 1 deletion core/jsMain/src/kotlinx/serialization/internal/Platform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ private val KClass<*>.isInterface: Boolean
return js.asDynamic().`$metadata$`?.kind == "interface"
}

@OptIn(ExperimentalUnsignedTypes::class, ExperimentalUuidApi::class, ExperimentalSerializationApi::class)
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalUuidApi::class, ExperimentalSerializationApi::class,
ExperimentalTime::class)
internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = mapOf(
String::class to String.serializer(),
Char::class to Char.serializer(),
Expand Down Expand Up @@ -111,5 +112,6 @@ internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = mapOf(
Unit::class to Unit.serializer(),
Nothing::class to NothingSerializer(),
Duration::class to Duration.serializer(),
Instant::class to Instant.serializer(),
Uuid::class to Uuid.serializer()
)
3 changes: 3 additions & 0 deletions core/jvmMain/src/kotlinx/serialization/internal/Platform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@ internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = buildMap {
}
@OptIn(ExperimentalUuidApi::class)
loadSafe { put(Uuid::class, Uuid.serializer()) }

@OptIn(ExperimentalTime::class)
loadSafe { put(Instant::class, Instant.serializer()) }
}

// Reference classes in [block] ignoring any exceptions related to class loading
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ private fun <T> arrayOfAnyNulls(size: Int): Array<T> = arrayOfNulls<Any>(size) a

internal actual fun isReferenceArray(rootClass: KClass<Any>): Boolean = rootClass == Array::class

@OptIn(ExperimentalUnsignedTypes::class, ExperimentalUuidApi::class, ExperimentalSerializationApi::class)
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalUuidApi::class, ExperimentalSerializationApi::class,
ExperimentalTime::class)
internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = mapOf(
String::class to String.serializer(),
Char::class to Char.serializer(),
Expand Down Expand Up @@ -105,5 +106,6 @@ internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = mapOf(
Unit::class to Unit.serializer(),
Nothing::class to NothingSerializer(),
Duration::class to Duration.serializer(),
Instant::class to Instant.serializer(),
Uuid::class to Uuid.serializer()
)
4 changes: 3 additions & 1 deletion core/wasmMain/src/kotlinx/serialization/internal/Platform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ internal actual fun <T : Any, E : T?> ArrayList<E>.toNativeArrayImpl(eClass: KCl

internal actual fun isReferenceArray(rootClass: KClass<Any>): Boolean = rootClass == Array::class

@OptIn(ExperimentalUnsignedTypes::class, ExperimentalUuidApi::class, ExperimentalSerializationApi::class)
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalUuidApi::class, ExperimentalSerializationApi::class,
ExperimentalTime::class)
internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = mapOf(
String::class to String.serializer(),
Char::class to Char.serializer(),
Expand Down Expand Up @@ -95,5 +96,6 @@ internal actual fun initBuiltins(): Map<KClass<*>, KSerializer<*>> = mapOf(
Unit::class to Unit.serializer(),
Nothing::class to NothingSerializer(),
Duration::class to Duration.serializer(),
Instant::class to Instant.serializer(),
Uuid::class to Uuid.serializer()
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2025-2025 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.builtins.*
import kotlin.time.*
import kotlin.test.*
import kotlin.reflect.typeOf

@OptIn(ExperimentalTime::class)
class InstantSerializationTest: JsonTestBase() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It may be worthwhile to also test on another format that is not Json (or JsonLike)

private fun iso8601Serialization(serializer: KSerializer<Instant>) {
for ((instant, json) in listOf(
Pair(Instant.fromEpochSeconds(1607505416, 124000),
"\"2020-12-09T09:16:56.000124Z\""),
Pair(Instant.fromEpochSeconds(-1607505416, -124000),
"\"1919-01-23T14:43:03.999876Z\""),
Pair(Instant.fromEpochSeconds(987654321, 123456789),
"\"2001-04-19T04:25:21.123456789Z\""),
Pair(Instant.fromEpochSeconds(987654321, 0),
"\"2001-04-19T04:25:21Z\""),
Comment on lines +17 to +25
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should include some values with non-utc timezones (especially ones with strange offsets like India). And include the fraction handling with millis, or less than 3 digits in the fraction of seconds.

)) {
assertJsonFormAndRestored(serializer, instant, json)
}
for ((instant, json) in listOf(
Pair(Instant.fromEpochSeconds(987654321, 123456789),
"\"2001-04-19T07:55:21.123456789+03:30\""),
Pair(Instant.fromEpochSeconds(987654321, 123456789),
"\"2001-04-19T00:55:21.123456789-03:30\""),
)) {
assertRestoredFromJsonForm(serializer, json, instant)
}
}

private fun componentSerialization(serializer: KSerializer<Instant>) {
for ((instant, json) in listOf(
Pair(Instant.fromEpochSeconds(1607505416, 124000),
"{\"epochSeconds\":1607505416,\"nanosecondsOfSecond\":124000}"),
Pair(Instant.fromEpochSeconds(-1607505416, -124000),
"{\"epochSeconds\":-1607505417,\"nanosecondsOfSecond\":999876000}"),
Pair(Instant.fromEpochSeconds(987654321, 123456789),
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":123456789}"),
Pair(Instant.fromEpochSeconds(987654321, 0),
"{\"epochSeconds\":987654321}"),
)) {
assertJsonFormAndRestored(serializer, instant, json)
}
// check that having a `"nanosecondsOfSecond": 0` field doesn't break deserialization
assertEquals(Instant.fromEpochSeconds(987654321, 0),
Json.decodeFromString(serializer,
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":0}"))
// "epochSeconds" should always be present
assertFailsWith<SerializationException> { Json.decodeFromString(serializer, "{}") }
assertFailsWith<SerializationException> { Json.decodeFromString(serializer, "{\"nanosecondsOfSecond\":3}") }
}

@Test
fun testIso8601Serialization() {
iso8601Serialization(Instant.serializer())
}

@Test
fun testComponentSerialization() {
componentSerialization(InstantComponentSerializer)
}

@Test
fun testDefaultSerializers() {
// should be the same as the ISO 8601
@Suppress("UNCHECKED_CAST")
iso8601Serialization(serializer(typeOf<Instant>()) as KSerializer<Instant>)
// iso8601Serialization(serializer()) TODO: uncomment when the compiler adds KT-75759
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -190,4 +190,15 @@ abstract class JsonTestBase {
assertTrue("Failed with streaming = $jsonTestingMode\n\tsource value =$data\n\tdeserialized value=$deserialized") { check(data, deserialized) }
}
}

internal fun <T> assertRestoredFromJsonForm(
serializer: KSerializer<T>,
jsonForm: String,
expected: T,
) {
parametrizedTest { jsonTestingMode ->
val deserialized: T = Json.decodeFromString(serializer, jsonForm, jsonTestingMode)
assertEquals(expected, deserialized, "Failed with streaming = $jsonTestingMode")
}
}
}
2 changes: 0 additions & 2 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,3 @@ org.gradle.kotlin.dsl.allWarningsAsErrors=true
kotlin.native.distribution.type=prebuilt

org.gradle.jvmargs="-XX:+HeapDumpOnOutOfMemoryError"

org.jetbrains.dokka.experimental.tryK2=true
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[versions]
kotlin = "2.1.20"
kover = "0.8.2"
dokka = "2.0.0-Beta"
dokka = "2.0.0"
knit = "0.5.0"
bcv = "0.16.2"
animalsniffer = "1.7.1"
Expand Down