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

nativeCommonMain.com.arkivanov.mvikotlin.timetravel.proto.internal.io.WriterThread.kt Maven / Gradle / Ivy

There is a newer version: 4.2.0
Show newest version
package com.arkivanov.mvikotlin.timetravel.proto.internal.io

import com.arkivanov.mvikotlin.timetravel.proto.internal.data.ProtoObject
import com.arkivanov.mvikotlin.timetravel.proto.internal.thread.LooperThread
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.convert
import kotlinx.cinterop.get
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.value
import platform.posix.close
import platform.posix.write

class WriterThread(
    private val socket: Int,
    private val onDisconnected: () -> Unit = {},
    private val onError: (Throwable) -> Unit = {}
) : LooperThread() {

    override fun run(message: ProtoObject) {
        try {
            getEncoder().encode(message)
        } catch (e: Throwable) {
            onError(e)
            close(socket)
            interrupt()
            onDisconnected()
        }
    }

    private fun getEncoder(): ProtoEncoder {
        val frameEncoder =
            ProtoFrameEncoder { data, size ->
                memScoped {
                    val buff = allocArray(size) { value = data[it] }
                    write(socket, buff, size.convert())
                }
            }

        return ProtoEncoder(frameEncoder::accept)
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy