diff --git a/docs/topics/usage.md b/docs/topics/usage.md index 5ad65b9..531f3f8 100644 --- a/docs/topics/usage.md +++ b/docs/topics/usage.md @@ -49,6 +49,47 @@ val store: KStore = storeOf( ``` { collapsible="true" collapsed-title="val store: KStore = storeOf" } +You can also use binary codecs for storage (e.g. Protobuf, Cbor) + +```kotlin +// Boilerplate implementation for a BinaryCodec +public class BinaryCodec( + private val key: String, + private val format: BinaryFormat, + private val serializer: KSerializer, + private val storage: Storage, +) : Codec { + override suspend fun encode(value: T?) { + if (value != null) storage[key] = format.encodeToByteArray(serializer, value) + else storage.remove(key) + } + + override suspend fun decode(): T? = storage[key] + ?.let { format.decodeFromByteArray(serializer, it) } +} + +// Protobuf implementation +public inline fun ProtobufCodec( + key: String, + // Other formats can be found here: https://kotlinlang.org/api/kotlinx.serialization/ + format: BinaryFormat = Protobuf, + storage: Storage = localStorage, +): BinaryCodec = BinaryCodec( + key = key, + format = format, + serializer = format.serializersModule.serializer(), + storage = storage, +) + +// Use the `Codec` to create a store +val store = KStore = storeOf( + codec = ProtobufCodec, + default = Pet(), + enableCache = true +) +``` +{ collapsible="true" collapsed-title="// Boilerplate implementation for a BinaryCodec" } + ## Use your store Given that you have a `@Serializable` model and a value @@ -92,4 +133,4 @@ You can also reset a value back to its default (if set, see [here](#other-config ```kotlin store.reset() -``` \ No newline at end of file +```