Skip to content
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

Support other SerialFormats in LongOrStringSerializer #937

Merged
merged 1 commit into from
Apr 13, 2024
Merged
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
6 changes: 6 additions & 0 deletions common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ kotlin {
implementation(projects.kspAnnotations)
}
}
jvmTest {
dependencies {
implementation(libs.bson)
implementation(libs.kbson)
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.long

internal object LongOrStringSerializer : KSerializer<String> {
private val backingSerializer = JsonPrimitive.serializer()

/*
* Delegating serializers should not reuse descriptors:
* https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#delegating-serializers
*
* however `SerialDescriptor("...", backingSerializer.descriptor)` will throw since
* `JsonPrimitive.serializer().kind` is `PrimitiveKind.STRING` (`SerialDescriptor()` does not allow
* however `SerialDescriptor("...", JsonPrimitive.serializer().descriptor)` will throw since
* `JsonPrimitive.serializer().descriptor.kind` is `PrimitiveKind.STRING` (`SerialDescriptor()` does not allow
* `PrimitiveKind`)
* -> use `PrimitiveSerialDescriptor("...", PrimitiveKind.STRING)` instead
*/
Expand All @@ -26,12 +26,21 @@ internal object LongOrStringSerializer : KSerializer<String> {
)

override fun serialize(encoder: Encoder, value: String) {
val jsonPrimitive = value.toLongOrNull()?.let { JsonPrimitive(it) } ?: JsonPrimitive(value)
encoder.encodeSerializableValue(backingSerializer, jsonPrimitive)
if (encoder is JsonEncoder) {
val jsonPrimitive = value.toLongOrNull()?.let { JsonPrimitive(it) } ?: JsonPrimitive(value)
encoder.encodeJsonElement(jsonPrimitive)
} else {
// fall back to a String for non-Json formats
encoder.encodeString(value)
}
}

override fun deserialize(decoder: Decoder): String {
val jsonPrimitive = decoder.decodeSerializableValue(backingSerializer)
return if (jsonPrimitive.isString) jsonPrimitive.content else jsonPrimitive.long.toString()
}
override fun deserialize(decoder: Decoder): String =
if (decoder is JsonDecoder) {
val jsonPrimitive = decoder.decodeSerializableValue(JsonPrimitive.serializer())
if (jsonPrimitive.isString) jsonPrimitive.content else jsonPrimitive.long.toString()
} else {
// fall back to a String for non-Json formats
decoder.decodeString()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package dev.kord.common.serialization

import com.github.jershell.kbson.KBson
import dev.kord.common.entity.Permission.*
import dev.kord.common.entity.Permissions
import kotlinx.serialization.Serializable
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals

class LongOrStringSerializerBsonTest {

@Serializable
private data class SomeObject(
@Serializable(with = LongOrStringSerializer::class) val someLong: String,
@Serializable(with = LongOrStringSerializer::class) val someString: String,
val somePermissions: Permissions,
)

private val someObject = SomeObject(
someLong = Random.nextLong().toString(),
someString = "some totally random string",
somePermissions = Permissions(DeafenMembers, ManageThreads, SendTTSMessages, ModerateMembers),
)

@Test
fun `test Bson serialization and deserialization with LongOrStringSerializer`() {
val kBson = KBson.default
assertEquals(
expected = someObject,
actual = kBson.load(SomeObject.serializer(), kBson.stringify(SomeObject.serializer(), someObject)),
)
assertEquals(
expected = someObject,
actual = kBson.load(SomeObject.serializer(), kBson.dump(SomeObject.serializer(), someObject)),
)
}
}
4 changes: 4 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ kotlinpoet = "1.16.0" # https://github.com/square/kotlinpoet
# tests
junit5 = "5.10.2" # https://github.com/junit-team/junit5
mockk = "1.13.10" # https://github.com/mockk/mockk
bson = "5.0.1" # https://github.com/mongodb/mongo-java-driver
kbson = "0.5.0" # https://github.com/jershell/kbson

# plugins
dokka = "1.9.20" # https://github.com/Kotlin/dokka
Expand Down Expand Up @@ -78,6 +80,8 @@ kotlin-test-junit5 = { module = "org.jetbrains.kotlin:kotlin-test-junit5", versi
junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit5" }
mockk = { module = "io.mockk:mockk", version.ref = "mockk" }
slf4j-simple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" }
bson = { module = "org.mongodb:bson", version.ref = "bson" }
kbson = { module = "com.github.jershell:kbson", version.ref = "kbson" }

# actually plugins, not libraries, but used is 'buildSrc/build.gradle.kts' as implementation dependencies:
# https://docs.gradle.org/current/userguide/custom_plugins.html#applying_external_plugins_in_precompiled_script_plugins
Expand Down