Skip to content

Commit

Permalink
Add a serializer to sort collections upon serialization (#117)
Browse files Browse the repository at this point in the history
* Add a serializer to sort collections upon serialization

Resolves #112.

* Opt-in for experimental `tupleSerializer()` to avoid compiler warnings
  • Loading branch information
sschuberth authored Feb 27, 2024
1 parent 803369f commit bbb0866
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package io.ks3.standard

import io.ks3.core.ExperimentalKs3
import kotlinx.serialization.KSerializer
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.serializer

/**
* Serializers that sort collections / lists / sets with the given [comparator] upon serialization.
*
* Example:
* ```kotlin
* class SortedStringListSerializer :
* KSerializer<List<String>> by sortedListSerializer(compareBy { it })
*
* @Serializable
* data class Friends(
* @Serializable(SortedStringListSerializer::class)
* val names: List<String>
* )
* ```
*/
@ExperimentalKs3
inline fun <reified T> sortedCollectionSerializer(comparator: Comparator<in T>): KSerializer<Collection<T>> {
val delegate = serializer<Collection<T>>()
return object : KSerializer<Collection<T>> by delegate {
override fun serialize(
encoder: Encoder,
value: Collection<T>,
) = delegate.serialize(encoder, value.sortedWith(comparator))
}
}

@ExperimentalKs3
inline fun <reified T> sortedListSerializer(comparator: Comparator<in T>): KSerializer<List<T>> {
val delegate = serializer<List<T>>()
return object : KSerializer<List<T>> by delegate {
override fun serialize(
encoder: Encoder,
value: List<T>,
) = delegate.serialize(encoder, value.sortedWith(comparator))
}
}

@ExperimentalKs3
inline fun <reified T> sortedSetSerializer(comparator: Comparator<in T>): KSerializer<Set<T>> {
val delegate = serializer<Set<T>>()
return object : KSerializer<Set<T>> by delegate {
override fun serialize(
encoder: Encoder,
value: Set<T>,
) = delegate.serialize(encoder, value.sortedWith(comparator).toSet())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package io.ks3.standard

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.ks3.core.ExperimentalKs3
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@OptIn(ExperimentalKs3::class)
class SortedCollectionSerializerTest : StringSpec(
{
val json = Json

"A list of strings can be serialized by natural ordering" {
json.encodeToString(
sortedListSerializer<String>(
compareBy { it },
),
listOf("c", "b", "a"),
) shouldBe
"""
["a","b","c"]
""".trimIndent()
}

"A list of non-comparable objects can be serialized by custom ordering" {
@Serializable
data class Friend(val name: String, val age: Int)

val friends =
listOf(
Friend("Alice", 20),
Friend("Bob", 30),
Friend("Charles", 40),
)

json.encodeToString(sortedListSerializer<Friend>(compareByDescending { it.age }), friends) shouldBe
"""
[{"name":"Charles","age":40},{"name":"Bob","age":30},{"name":"Alice","age":20}]
""".trimIndent()
}
},
)
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ data class CoordinatesDetails(
constructor(x: Int, y: Int) : this(x, y, "red", true)
}

@OptIn(ExperimentalSerializationApi::class)
object CoordinatesDetailsSerializer : KSerializer<CoordinatesDetails> by tupleSerializer(CoordinatesDetails::x, CoordinatesDetails::y)

@Serializable(with = CoordinatesDetailsWithDefaultsSerializer::class)
Expand All @@ -43,6 +44,7 @@ data class CoordinatesDetailsWithDefaults(
val active: Boolean = true,
)

@OptIn(ExperimentalSerializationApi::class)
object CoordinatesDetailsWithDefaultsSerializer :
KSerializer<CoordinatesDetailsWithDefaults> by tupleSerializer(CoordinatesDetailsWithDefaults::x, CoordinatesDetailsWithDefaults::y)

Expand Down

0 comments on commit bbb0866

Please sign in to comment.