Skip to content

Commit

Permalink
Add comment explaining reason for disallowing duplicated fields
Browse files Browse the repository at this point in the history
  • Loading branch information
lukellmann committed Mar 11, 2024
1 parent 766a60e commit ec4f55e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
14 changes: 9 additions & 5 deletions gateway/src/commonMain/kotlin/Event.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,21 @@ public sealed class Event {
}

override fun deserialize(decoder: Decoder): Event = decoder.decodeStructure(descriptor) {
// Correctly interpreting the d field depends on the value of the other fields. If we wanted to allow
// duplicated fields by letting the last value win (like generated serializers seem to do), we would have to
// make a tradeoff. Because it could be the case that op, t or s are duplicated, we would always have to
// defer interpreting d until all fields are decoded. This would mean always decoding d to a JsonElement and
// then again to the appropriate Event subtype.
// By disallowing duplicated fields, this intermediate step can be skipped in the case that op, t and s
// appear before d.
var opCode: OpCode? = null
var seenEventName = false
var eventName: String? = null
var seenSequence = false
var sequence: Int? = null
// only one of event and rawEventData will be assigned, depending on the encounter order of the fields:
// - event, if ALL other fields (op, t, s) appeared before d
// - rawEventData, otherwise (an event will be created after all fields have been decoded)
var seenEventData = false
var event: Event? = null
var rawEventData: JsonElement? = null
var event: Event? = null // assigned if op, t and s appear before d
var rawEventData: JsonElement? = null // assigned otherwise
while (true) {
when (val index = decodeElementIndex(descriptor)) {
CompositeDecoder.DECODE_DONE -> break
Expand Down
6 changes: 3 additions & 3 deletions gateway/src/commonTest/kotlin/json/SerializationTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,13 @@ class SerializationTest {
Json.decodeFromString(Event.DeserializationStrategy, """{"op":0,"op":1}""")
}
assertFailsWith<SerializationException> {
Json.decodeFromString(Event.DeserializationStrategy, """{"s":0,"s":1}""")
Json.decodeFromString(Event.DeserializationStrategy, """{"op":0,"s":0,"s":1}""")
}
assertFailsWith<SerializationException> {
Json.decodeFromString(Event.DeserializationStrategy, """{"t":"A","t":"B"}""")
Json.decodeFromString(Event.DeserializationStrategy, """{"op":0,"t":"A","t":"B"}""")
}
assertFailsWith<SerializationException> {
Json.decodeFromString(Event.DeserializationStrategy, """{"d":true,"d":false}""")
Json.decodeFromString(Event.DeserializationStrategy, """{"op":0,"d":true,"d":false}""")
}
}

Expand Down

0 comments on commit ec4f55e

Please sign in to comment.