Skip to content

Commit

Permalink
Add convenience reified functions for de-/encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
sschuberth committed Sep 9, 2024
1 parent 7459b5f commit 45a455c
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/commonMain/kotlin/com/charleskorn/kaml/Yaml.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.StringFormat
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.serializer
import okio.Buffer
import okio.BufferedSink
import okio.Sink
Expand All @@ -40,6 +41,9 @@ public class Yaml(
public val default: Yaml = Yaml()
}

public inline fun <reified T> decodeFromYamlNode(node: YamlNode): T =
decodeFromYamlNode(serializer<T>(), node)

public fun <T> decodeFromYamlNode(
deserializer: DeserializationStrategy<T>,
node: YamlNode,
Expand All @@ -48,13 +52,19 @@ public class Yaml(
return input.decodeSerializableValue(deserializer)
}

public inline fun <reified T> decodeFromString(string: String): T =
decodeFromString(serializersModule.serializer<T>(), string)

override fun <T> decodeFromString(
deserializer: DeserializationStrategy<T>,
string: String,
): T {
return decodeFromSource(deserializer, string.bufferedSource())
}

public inline fun <reified T> decodeFromSource(source: Source): T =
decodeFromSource(serializersModule.serializer<T>(), source)

public fun <T> decodeFromSource(
deserializer: DeserializationStrategy<T>,
source: Source,
Expand All @@ -77,6 +87,9 @@ public class Yaml(
return node
}

public inline fun <reified T> encodeToSink(value: T, sink: Sink): Unit =
encodeToSink(serializersModule.serializer<T>(), value, sink)

public fun <T> encodeToSink(
serializer: SerializationStrategy<T>,
value: T,
Expand All @@ -85,6 +98,9 @@ public class Yaml(
encodeToBufferedSink(serializer, value, sink.buffer())
}

public inline fun <reified T> encodeToString(value: T): String =
encodeToString(serializersModule.serializer<T>(), value)

override fun <T> encodeToString(
serializer: SerializationStrategy<T>,
value: T,
Expand All @@ -94,7 +110,11 @@ public class Yaml(
return buffer.readUtf8().trimEnd()
}

private fun <T> encodeToBufferedSink(
public inline fun <reified T> encodeToBufferedSink(value: T, sink: BufferedSink): Unit =
encodeToBufferedSink(serializersModule.serializer<T>(), value, sink)

@PublishedApi
internal fun <T> encodeToBufferedSink(
serializer: SerializationStrategy<T>,
value: T,
sink: BufferedSink,
Expand Down

0 comments on commit 45a455c

Please sign in to comment.