All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.avrokotlin.avro4k.AvroOkioExtensions.kt Maven / Gradle / Ivy

Go to download

Avro binary format support for kotlin, built on top of kotlinx-serialization

The newest version!
package com.github.avrokotlin.avro4k

import com.github.avrokotlin.avro4k.internal.decodeWithBinaryDecoder
import com.github.avrokotlin.avro4k.internal.encodeWithBinaryEncoder
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.serializer
import okio.BufferedSink
import okio.BufferedSource
import org.apache.avro.Schema
import org.apache.avro.io.DecoderFactory
import org.apache.avro.io.EncoderFactory

@ExperimentalSerializationApi
public fun  Avro.encodeToSink(
    writerSchema: Schema,
    serializer: SerializationStrategy,
    value: T,
    sink: BufferedSink,
) {
    val avroEncoder =
        EncoderFactory.get().directBinaryEncoder(sink.outputStream(), null).let {
            if (configuration.validateSerialization) {
                EncoderFactory.get().validatingEncoder(writerSchema, it)
            } else {
                it
            }
        }

    encodeWithBinaryEncoder(writerSchema, serializer, value, avroEncoder)

    avroEncoder.flush()
}

@ExperimentalSerializationApi
public inline fun  Avro.encodeToSink(
    value: T,
    sink: BufferedSink,
) {
    val serializer = serializersModule.serializer()
    encodeToSink(schema(serializer), serializer, value, sink)
}

@ExperimentalSerializationApi
public inline fun  Avro.encodeToSink(
    writerSchema: Schema,
    value: T,
    sink: BufferedSink,
) {
    val serializer = serializersModule.serializer()
    encodeToSink(writerSchema, serializer, value, sink)
}

@ExperimentalSerializationApi
public fun  Avro.decodeFromSource(
    writerSchema: Schema,
    deserializer: DeserializationStrategy,
    source: BufferedSource,
): T {
    val avroDecoder =
        DecoderFactory.get().directBinaryDecoder(source.inputStream(), null).let {
            if (configuration.validateSerialization) {
                DecoderFactory.get().validatingDecoder(writerSchema, it)
            } else {
                it
            }
        }

    return decodeWithBinaryDecoder(writerSchema, deserializer, avroDecoder)
}

@ExperimentalSerializationApi
public inline fun  Avro.decodeFromSource(source: BufferedSource): T {
    val serializer = serializersModule.serializer()
    return decodeFromSource(schema(serializer.descriptor), serializer, source)
}

@ExperimentalSerializationApi
public inline fun  Avro.decodeFromSource(
    writerSchema: Schema,
    source: BufferedSource,
): T {
    val serializer = serializersModule.serializer()
    return decodeFromSource(writerSchema, serializer, source)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy