-
Notifications
You must be signed in to change notification settings - Fork 636
/
Copy pathInstantComponentSerializer.kt
51 lines (44 loc) · 1.94 KB
/
InstantComponentSerializer.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* 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
@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 epochSeconds: Long? = null
var nanosecondsOfSecond = 0
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
0 -> epochSeconds = decodeLongElement(descriptor, 0)
1 -> nanosecondsOfSecond = decodeIntElement(descriptor, 1)
CompositeDecoder.DECODE_DONE -> break@loop // https://youtrack.jetbrains.com/issue/KT-42262
else -> throw SerializationException("Unexpected index: $index")
}
}
if (epochSeconds == null) throw MissingFieldException(
missingField = "epochSeconds",
serialName = descriptor.serialName
)
Instant.fromEpochSeconds(epochSeconds, nanosecondsOfSecond)
}
override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeStructure(descriptor) {
encodeLongElement(descriptor, 0, value.epochSeconds)
if (value.nanosecondsOfSecond != 0) {
encodeIntElement(descriptor, 1, value.nanosecondsOfSecond)
}
}
}
}