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
### Fixed
- Fixed NameToken parsing.
- Top level string list meta conversion.
### 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) {
is JsonPrimitive -> Meta(toValue(descriptor))
is JsonObject -> toMeta(descriptor)
is JsonArray -> SealedMeta(null,
is JsonArray -> if (any { it is JsonObject }) {
SealedMeta(null,
linkedMapOf<NameToken, SealedMeta>().apply {
addJsonElement(Meta.JSON_ARRAY_KEY, this@toMeta, null)
}
)
} else{
Meta(map { it.toValueOrNull(descriptor) ?: kotlin.error("Unreachable: should not contain objects") }.asValue())
}
}
//

View File

@ -11,7 +11,7 @@ import space.kscience.dataforge.misc.DFExperimental
/**
* A converter of generic object to and from [Meta]
*/
public interface MetaConverter<T>: MetaReader<T> {
public interface MetaConverter<T> : MetaReader<T> {
/**
* A descriptor for resulting meta
@ -116,6 +116,12 @@ public interface MetaConverter<T>: MetaReader<T> {
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(
writer: (T) -> Value = { Value.of(it) },
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)
}
}