Skip to content

Commit

Permalink
Support strings and utf8 when decoding enums
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Apr 27, 2024
1 parent 6c20f0a commit 99d397a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.sksamuel.centurion.avro.decoders

import org.apache.avro.Schema
import org.apache.avro.generic.GenericEnumSymbol
import org.apache.avro.util.Utf8
import kotlin.reflect.KClass

class EnumDecoder<T : Enum<T>>(kclass: KClass<T>) : Decoder<Enum<T>> {
Expand All @@ -20,6 +21,8 @@ class EnumDecoder<T : Enum<T>>(kclass: KClass<T>) : Decoder<Enum<T>> {
require(schema.type == Schema.Type.ENUM)
return when (value) {
is GenericEnumSymbol<*> -> java.lang.Enum.valueOf(j, value.toString())
is String -> java.lang.Enum.valueOf(j, value)
is Utf8 -> java.lang.Enum.valueOf(j, value.toString())
else -> error("Unsupported enum type $value")
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.sksamuel.centurion.avro.decoders

import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import org.apache.avro.Schema
import org.apache.avro.generic.GenericData
import org.apache.avro.util.Utf8

class EnumDecoderTest : FunSpec({

val schema = Schema.createEnum("W", null, null, listOf("Wobble", "Wibble"))

test("support GenericEnumSymbol") {
EnumDecoder(W::class).decode(schema, GenericData.get().createEnum("Wibble", schema)) shouldBe W.Wibble
}

test("support strings") {
EnumDecoder(W::class).decode(schema, "Wibble") shouldBe W.Wibble
}

test("support UTF8s") {
EnumDecoder(W::class).decode(schema, Utf8("Wibble")) shouldBe W.Wibble
}

})

private enum class W { Wibble, Wobble }

0 comments on commit 99d397a

Please sign in to comment.