First implementation for protobuf converter

This commit is contained in:
Alexander Nozik 2024-06-10 21:22:00 +03:00
parent 332d38df77
commit 7fa6617e7e
4 changed files with 35 additions and 6 deletions

View File

@ -13,6 +13,8 @@
### Removed ### Removed
### Fixed ### Fixed
- Fixed NameToken parsing.
- Top level string list meta conversion.
### Security ### Security

View File

@ -163,11 +163,15 @@ public fun JsonObject.toMeta(descriptor: MetaDescriptor? = null): SealedMeta {
public fun JsonElement.toMeta(descriptor: MetaDescriptor? = null): SealedMeta = when (this) { public fun JsonElement.toMeta(descriptor: MetaDescriptor? = null): SealedMeta = when (this) {
is JsonPrimitive -> Meta(toValue(descriptor)) is JsonPrimitive -> Meta(toValue(descriptor))
is JsonObject -> toMeta(descriptor) is JsonObject -> toMeta(descriptor)
is JsonArray -> SealedMeta(null, is JsonArray -> if (any { it is JsonObject }) {
SealedMeta(null,
linkedMapOf<NameToken, SealedMeta>().apply { linkedMapOf<NameToken, SealedMeta>().apply {
addJsonElement(Meta.JSON_ARRAY_KEY, this@toMeta, null) addJsonElement(Meta.JSON_ARRAY_KEY, this@toMeta, null)
} }
) )
} else{
Meta(map { it.toValueOrNull(descriptor) ?: kotlin.error("Unreachable: should not contain objects") }.asValue())
}
} }
// //

View File

@ -116,6 +116,12 @@ public interface MetaConverter<T>: MetaReader<T> {
override fun convert(obj: E): Meta = Meta(obj.asValue()) override fun convert(obj: E): Meta = Meta(obj.asValue())
} }
public val stringList: MetaConverter<List<String>> = object : MetaConverter<List<String>> {
override fun convert(obj: List<String>): Meta = Meta(obj.map { it.asValue() }.asValue())
override fun readOrNull(source: Meta): List<String>? = source.stringList
}
public fun <T> valueList( public fun <T> valueList(
writer: (T) -> Value = { Value.of(it) }, writer: (T) -> Value = { Value.of(it) },
reader: (Value) -> T, reader: (Value) -> T,

View File

@ -0,0 +1,17 @@
package space.kscience.dataforge.meta
import kotlin.test.Test
import kotlin.test.assertEquals
class ConvertersTest {
@Test
fun stringListConversion() {
val list = listOf("A", "B", "C")
val meta = MetaConverter.stringList.convert(list)
val json = meta.toJson()
val reconstructedMeta = json.toMeta()
val reconstructed = MetaConverter.stringList.read(reconstructedMeta)
assertEquals(list,reconstructed)
}
}