Skip to content

Commit

Permalink
feat: Add a way to reorder elements during encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Chuckame committed Jun 23, 2024
1 parent 0013192 commit ef214ec
Show file tree
Hide file tree
Showing 2 changed files with 318 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
/*
* Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.encoding

import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.modules.*


/**
* Encodes composite elements in a specific order managed by [mapElementIndex].
*
* This encoder will replicate the behavior of a standard encoding, but calling the `encode*Element` methods in
* the order defined by [mapElementIndex]. It first buffers each `encode*Element` calls in an array following
* the given indexes using [mapElementIndex], then when [endStructure] is called, it encodes the buffered calls
* in the expected order by replaying the previous calls on the given [compositeEncoderDelegate].
*
* @param compositeEncoderDelegate the [CompositeEncoder] to be used to encode the given descriptor's elements in the expected order.
* @param structureDescriptor descriptor of the structure being encoded and reordered
* @param mapElementIndex maps the element index to a new positional zero-based index. If this mapper provides the same index for multiple elements, only the last one will be encoded as the previous ones will be overridden. The mapped index just helps to reorder the elements, but the reordered `encode*Element` method calls will still pass the original element index.
*/
@ExperimentalSerializationApi
internal class ReorderingCompositeEncoder(
structureDescriptor: SerialDescriptor,
private val compositeEncoderDelegate: CompositeEncoder,
private val mapElementIndex: (SerialDescriptor, Int) -> Int,
) : CompositeEncoder {
private var bufferedCalls = Array<BufferedCall?>(structureDescriptor.elementsCount) { null }

override val serializersModule: SerializersModule
// No need to return a serializers module as it's not used during buffering
get() = EmptySerializersModule()

private data class BufferedCall(
val originalElementIndex: Int,
val encoder: () -> Unit,
)

private fun bufferEncoding(
descriptor: SerialDescriptor,
index: Int,
encoder: () -> Unit
) {
bufferedCalls[mapElementIndex(descriptor, index)] = BufferedCall(index, encoder)
}

override fun endStructure(descriptor: SerialDescriptor) {
encodeBufferedFields(descriptor)
}

private fun encodeBufferedFields(descriptor: SerialDescriptor) {
bufferedCalls.filterNotNull().forEach { fieldToEncode ->
fieldToEncode.encoder()
}
compositeEncoderDelegate.endStructure(descriptor)
}

override fun encodeBooleanElement(descriptor: SerialDescriptor, index: Int, value: Boolean) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeBooleanElement(descriptor, index, value)
}
}

override fun encodeByteElement(descriptor: SerialDescriptor, index: Int, value: Byte) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeByteElement(descriptor, index, value)
}
}

override fun encodeCharElement(descriptor: SerialDescriptor, index: Int, value: Char) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeCharElement(descriptor, index, value)
}
}

override fun encodeDoubleElement(descriptor: SerialDescriptor, index: Int, value: Double) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeDoubleElement(descriptor, index, value)
}
}

override fun encodeFloatElement(descriptor: SerialDescriptor, index: Int, value: Float) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeFloatElement(descriptor, index, value)
}
}

override fun encodeIntElement(descriptor: SerialDescriptor, index: Int, value: Int) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeIntElement(descriptor, index, value)
}
}

override fun encodeLongElement(descriptor: SerialDescriptor, index: Int, value: Long) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeLongElement(descriptor, index, value)
}
}

override fun <T : Any> encodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T?
) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeNullableSerializableElement(descriptor, index, serializer, value)
}
}

override fun <T> encodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T
) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeSerializableElement(descriptor, index, serializer, value)
}
}

override fun encodeShortElement(descriptor: SerialDescriptor, index: Int, value: Short) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeShortElement(descriptor, index, value)
}
}

override fun encodeStringElement(descriptor: SerialDescriptor, index: Int, value: String) {
bufferEncoding(descriptor, index) {
compositeEncoderDelegate.encodeStringElement(descriptor, index, value)
}
}

override fun encodeInlineElement(descriptor: SerialDescriptor, index: Int): Encoder {
return BufferingInlineEncoder(descriptor, index)
}

override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean {
return compositeEncoderDelegate.shouldEncodeElementDefault(descriptor, index)
}

private inner class BufferingInlineEncoder(
private val descriptor: SerialDescriptor,
private val elementIndex: Int,
) : Encoder {
private var encodeNotNullMarkCalled = false

override val serializersModule: SerializersModule
get() = this@ReorderingCompositeEncoder.serializersModule

private fun bufferEncoding(encoder: Encoder.() -> Unit) {
bufferEncoding(descriptor, elementIndex) {
compositeEncoderDelegate.encodeInlineElement(descriptor, elementIndex).apply {
if (encodeNotNullMarkCalled) {
encodeNotNullMark()
}
encoder()
}
}
}

override fun encodeNotNullMark() {
encodeNotNullMarkCalled = true
}

override fun <T : Any> encodeNullableSerializableValue(serializer: SerializationStrategy<T>, value: T?) {
bufferEncoding { encodeNullableSerializableValue(serializer, value) }
}

override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
bufferEncoding { encodeSerializableValue(serializer, value) }
}

override fun encodeBoolean(value: Boolean) {
bufferEncoding { encodeBoolean(value) }
}

override fun encodeByte(value: Byte) {
bufferEncoding { encodeByte(value) }
}

override fun encodeChar(value: Char) {
bufferEncoding { encodeChar(value) }
}

override fun encodeDouble(value: Double) {
bufferEncoding { encodeDouble(value) }
}

override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) {
bufferEncoding { encodeEnum(enumDescriptor, index) }
}

override fun encodeFloat(value: Float) {
bufferEncoding { encodeFloat(value) }
}

override fun encodeInt(value: Int) {
bufferEncoding { encodeInt(value) }
}

override fun encodeLong(value: Long) {
bufferEncoding { encodeLong(value) }
}

@ExperimentalSerializationApi
override fun encodeNull() {
bufferEncoding { encodeNull() }
}

override fun encodeShort(value: Short) {
bufferEncoding { encodeShort(value) }
}

override fun encodeString(value: String) {
bufferEncoding { encodeString(value) }
}

override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
invalidCall("beginStructure")
}

override fun encodeInline(descriptor: SerialDescriptor): Encoder {
invalidCall("encodeInline")
}

private fun invalidCall(methodName: String): Nothing {
// This method is normally called by encodeSerializableValue or encodeNullableSerializableValue that is buffered, so we should never go here during buffering as it will be delegated to the concrete CompositeEncoder
throw UnsupportedOperationException("$methodName should not be called when reordering fields, as it should be done by encodeSerializableValue or encodeNullableSerializableValue")
}
}
}

/**
* Encodes the [structureDescriptor] elements in a specific order provided by [elementIndexMapper].
*
* @param structureDescriptor descriptor of the structure being encoded and reordered
* @param elementIndexMapper maps the element index to a new positional zero-based index. If this mapper provides the same index for multiple elements, only the last one will be encoded as the previous ones will be overridden. The mapped index just helps to reorder the elements, but the reordered `encode*Element` method calls will still pass the original element index.
*/
@ExperimentalSerializationApi
public fun CompositeEncoder.encodeReorderingElements(
structureDescriptor: SerialDescriptor,
elementIndexMapper: (SerialDescriptor, Int) -> Int,
): CompositeEncoder = ReorderingCompositeEncoder(structureDescriptor, this, elementIndexMapper)
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.encoding

import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.modules.*
import kotlin.jvm.*
import kotlin.test.*

class ReorderingCompositeEncoderTest {
@Test
fun shouldReorderWell() {
val first = 42
val second = "string"
val third = true
val value = OuterToBeReordered(Middle(Inner(second, third)), first)

val encoder = ReorderingEncoder().apply {
encodeSerializableValue(OuterToBeReordered.serializer(), value)
}

assertContentEquals(actual = encoder.encodedValues, expected = listOf(first, second, third))
}

private class ReorderingEncoder(
val encodedValues: MutableList<Any?> = mutableListOf()
) : AbstractEncoder() {
override val serializersModule: SerializersModule
get() = EmptySerializersModule()

override fun encodeValue(value: Any) {
encodedValues.add(value)
}

override fun encodeNull() {
encodedValues.add(null)
}

override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
return BasicCompositeEncoder().encodeReorderingElements(descriptor) { _, index ->
// invert fields
if (index == 0) 1 else 0
}
}

private inner class BasicCompositeEncoder : AbstractEncoder() {
override val serializersModule: SerializersModule
get() = EmptySerializersModule()

override fun encodeValue(value: Any) {
encodedValues.add(value)
}

override fun encodeNull() {
encodedValues.add(null)
}
}
}

@Serializable
private data class OuterToBeReordered(val a: Middle, val b: Int)

@JvmInline
@Serializable
private value class Middle(val i: Inner)

@Serializable
private data class Inner(val c: String, val d: Boolean)
}

0 comments on commit ef214ec

Please sign in to comment.