Skip to content

Commit

Permalink
Map decoder should support UTF8 strings
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Apr 26, 2024
1 parent 7119ef5 commit 3f58b96
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,13 @@ class MapDecoder<T>(private val decoder: Decoder<T>) : Decoder<Map<String, T>> {
override fun decode(schema: Schema, value: Any?): Map<String, T> {
require(schema.type == Schema.Type.MAP)
return when (value) {
is Map<*, *> -> value.map { (k, v) -> Pair(k as String, decoder.decode(schema.valueType, v)) }.toMap()
is Map<*, *> -> value.map { (k, v) ->
Pair(
StringDecoder.decode(StringDecoder.STRING_SCHEMA, k),
decoder.decode(schema.valueType, v)
)
}.toMap()

else -> error("Unsupported map type $value")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import java.nio.ByteBuffer
* the schema, but are nevertheless usable.
*/
object StringDecoder : Decoder<String> {

val STRING_SCHEMA = Schema.create(Schema.Type.STRING)

override fun decode(schema: Schema, value: Any?): String {
return when (value) {
is Utf8 -> value.toString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,22 @@ class SpecificRecordDecoderTest : FunSpec({
SpecificRecordDecoder(Foo::class, schema).decode(schema, record) shouldBe Foo(map)
}

test("maps using UTF8") {
data class Foo(val map: Map<String, Int>)

val schema = SchemaBuilder.record("Foo").namespace(Foo::class.java.packageName)
.fields()
.name("map").type().map().values().intType().noDefault()
.endRecord()

val map = mapOf(Utf8("a") to 1, "b" to 2)

val record = GenericData.Record(schema)
record.put("map", map)

SpecificRecordDecoder(Foo::class, schema).decode(schema, record) shouldBe Foo(mapOf("a" to 1, "b" to 2))
}

test("maps of maps") {
data class Foo(val map: Map<String, Map<String, Int>>)

Expand Down

0 comments on commit 3f58b96

Please sign in to comment.