// This file was autogenerated by some hot garbage in the `uniffi` crate.
// Trust me, you don't want to mess with it!

@file:Suppress("NAME_SHADOWING")

package cn.qmai.socket;

// Common helper code.
//
// Ideally this would live in a separate .kt file where it can be unittested etc
// in isolation, and perhaps even published as a re-useable package.
//
// However, it's important that the detils of how this helper code works (e.g. the
// way that different builtin types are passed across the FFI) exactly match what's
// expected by the Rust code on the other side of the interface. In practice right
// now that means coming from the exact some version of `uniffi` that was used to
// compile the Rust component. The easiest way to ensure this is to bundle the Kotlin
// helpers directly inline like we're doing here.

import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
import com.sun.jna.ptr.ByReference
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong

// This is a helper for safely working with byte buffers returned from the Rust code.
// A rust-owned buffer is represented by its capacity, its current length, and a
// pointer to the underlying data.

@Structure.FieldOrder("capacity", "len", "data")
open class RustBuffer : Structure() {
    @JvmField var capacity: Int = 0
    @JvmField var len: Int = 0
    @JvmField var data: Pointer? = null

    class ByValue : RustBuffer(), Structure.ByValue
    class ByReference : RustBuffer(), Structure.ByReference

    companion object {
        internal fun alloc(size: Int = 0) = rustCall() { status ->
            _UniFFILib.INSTANCE.ffi_NativeSocket_8a33_rustbuffer_alloc(size, status).also {
                if(it.data == null) {
                   throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})")
               }
            }
        }

        internal fun free(buf: RustBuffer.ByValue) = rustCall() { status ->
            _UniFFILib.INSTANCE.ffi_NativeSocket_8a33_rustbuffer_free(buf, status)
        }
    }

    @Suppress("TooGenericExceptionThrown")
    fun asByteBuffer() =
        this.data?.getByteBuffer(0, this.len.toLong())?.also {
            it.order(ByteOrder.BIG_ENDIAN)
        }
}

/**
 * The equivalent of the `*mut RustBuffer` type.
 * Required for callbacks taking in an out pointer.
 *
 * Size is the sum of all values in the struct.
 */
class RustBufferByReference : ByReference(16) {
    /**
     * Set the pointed-to `RustBuffer` to the given value.
     */
    fun setValue(value: RustBuffer.ByValue) {
        // NOTE: The offsets are as they are in the C-like struct.
        val pointer = getPointer()
        pointer.setInt(0, value.capacity)
        pointer.setInt(4, value.len)
        pointer.setPointer(8, value.data)
    }
}

// This is a helper for safely passing byte references into the rust code.
// It's not actually used at the moment, because there aren't many things that you
// can take a direct pointer to in the JVM, and if we're going to copy something
// then we might as well copy it into a `RustBuffer`. But it's here for API
// completeness.

@Structure.FieldOrder("len", "data")
open class ForeignBytes : Structure() {
    @JvmField var len: Int = 0
    @JvmField var data: Pointer? = null

    class ByValue : ForeignBytes(), Structure.ByValue
}
// The FfiConverter interface handles converter types to and from the FFI
//
// All implementing objects should be public to support external types.  When a
// type is external we need to import it's FfiConverter.
public interface FfiConverter<KotlinType, FfiType> {
    // Convert an FFI type to a Kotlin type
    fun lift(value: FfiType): KotlinType

    // Convert an Kotlin type to an FFI type
    fun lower(value: KotlinType): FfiType

    // Read a Kotlin type from a `ByteBuffer`
    fun read(buf: ByteBuffer): KotlinType

    // Calculate bytes to allocate when creating a `RustBuffer`
    //
    // This must return at least as many bytes as the write() function will
    // write. It can return more bytes than needed, for example when writing
    // Strings we can't know the exact bytes needed until we the UTF-8
    // encoding, so we pessimistically allocate the largest size possible (3
    // bytes per codepoint).  Allocating extra bytes is not really a big deal
    // because the `RustBuffer` is short-lived.
    fun allocationSize(value: KotlinType): Int

    // Write a Kotlin type to a `ByteBuffer`
    fun write(value: KotlinType, buf: ByteBuffer)

    // Lower a value into a `RustBuffer`
    //
    // This method lowers a value into a `RustBuffer` rather than the normal
    // FfiType.  It's used by the callback interface code.  Callback interface
    // returns are always serialized into a `RustBuffer` regardless of their
    // normal FFI type.
    fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue {
        val rbuf = RustBuffer.alloc(allocationSize(value))
        try {
            val bbuf = rbuf.data!!.getByteBuffer(0, rbuf.capacity.toLong()).also {
                it.order(ByteOrder.BIG_ENDIAN)
            }
            write(value, bbuf)
            rbuf.writeField("len", bbuf.position())
            return rbuf
        } catch (e: Throwable) {
            RustBuffer.free(rbuf)
            throw e
        }
    }

    // Lift a value from a `RustBuffer`.
    //
    // This here mostly because of the symmetry with `lowerIntoRustBuffer()`.
    // It's currently only used by the `FfiConverterRustBuffer` class below.
    fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType {
        val byteBuf = rbuf.asByteBuffer()!!
        try {
           val item = read(byteBuf)
           if (byteBuf.hasRemaining()) {
               throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!")
           }
           return item
        } finally {
            RustBuffer.free(rbuf)
        }
    }
}

// FfiConverter that uses `RustBuffer` as the FfiType
public interface FfiConverterRustBuffer<KotlinType>: FfiConverter<KotlinType, RustBuffer.ByValue> {
    override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value)
    override fun lower(value: KotlinType) = lowerIntoRustBuffer(value)
}
// A handful of classes and functions to support the generated data structures.
// This would be a good candidate for isolating in its own ffi-support lib.
// Error runtime.
@Structure.FieldOrder("code", "error_buf")
internal open class RustCallStatus : Structure() {
    @JvmField var code: Int = 0
    @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue()

    fun isSuccess(): Boolean {
        return code == 0
    }

    fun isError(): Boolean {
        return code == 1
    }

    fun isPanic(): Boolean {
        return code == 2
    }
}

class InternalException(message: String) : Exception(message)

// Each top-level error class has a companion object that can lift the error from the call status's rust buffer
interface CallStatusErrorHandler<E> {
    fun lift(error_buf: RustBuffer.ByValue): E;
}

// Helpers for calling Rust
// In practice we usually need to be synchronized to call this safely, so it doesn't
// synchronize itself

// Call a rust function that returns a Result<>.  Pass in the Error class companion that corresponds to the Err
private inline fun <U, E: Exception> rustCallWithError(errorHandler: CallStatusErrorHandler<E>, callback: (RustCallStatus) -> U): U {
    var status = RustCallStatus();
    val return_value = callback(status)
    if (status.isSuccess()) {
        return return_value
    } else if (status.isError()) {
        throw errorHandler.lift(status.error_buf)
    } else if (status.isPanic()) {
        // when the rust code sees a panic, it tries to construct a rustbuffer
        // with the message.  but if that code panics, then it just sends back
        // an empty buffer.
        if (status.error_buf.len > 0) {
            throw InternalException(FfiConverterString.lift(status.error_buf))
        } else {
            throw InternalException("Rust panic")
        }
    } else {
        throw InternalException("Unknown rust call status: $status.code")
    }
}

// CallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR
object NullCallStatusErrorHandler: CallStatusErrorHandler<InternalException> {
    override fun lift(error_buf: RustBuffer.ByValue): InternalException {
        RustBuffer.free(error_buf)
        return InternalException("Unexpected CALL_ERROR")
    }
}

// Call a rust function that returns a plain value
private inline fun <U> rustCall(callback: (RustCallStatus) -> U): U {
    return rustCallWithError(NullCallStatusErrorHandler, callback);
}

// Contains loading, initialization code,
// and the FFI Function declarations in a com.sun.jna.Library.
@Synchronized
private fun findLibraryName(componentName: String): String {
    val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride")
    if (libOverride != null) {
        return libOverride
    }
    return "socket"
}

private inline fun <reified Lib : Library> loadIndirect(
    componentName: String
): Lib {
    return Native.load<Lib>(findLibraryName(componentName), Lib::class.java)
}

// A JNA Library to expose the extern-C FFI definitions.
// This is an implementation detail which will be called internally by the public API.

internal interface _UniFFILib : Library {
    companion object {
        internal val INSTANCE: _UniFFILib by lazy {
            loadIndirect<_UniFFILib>(componentName = "NativeSocket")
            
        }
    }

    fun ffi_NativeSocket_8a33_NativeSocketBuilder_object_free(`ptr`: Pointer,
    _uniffi_out_err: RustCallStatus
    ): Unit

    fun NativeSocket_8a33_NativeSocketBuilder_new(
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_host(`ptr`: Pointer,`host`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_token(`ptr`: Pointer,`token`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_brand(`ptr`: Pointer,`brand`: Int,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_store(`ptr`: Pointer,`store`: Int,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_device(`ptr`: Pointer,`device`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_ty(`ptr`: Pointer,`type`: Int,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_clean_start(`ptr`: Pointer,`cleanStart`: Byte,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_cache_dir(`ptr`: Pointer,`cacheDir`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_grpc(`ptr`: Pointer,`enable`: Byte,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_version(`ptr`: Pointer,`version`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): Pointer

    fun NativeSocket_8a33_NativeSocketBuilder_build(`ptr`: Pointer,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun ffi_NativeSocket_8a33_NativeSocket_object_free(`ptr`: Pointer,
    _uniffi_out_err: RustCallStatus
    ): Unit

    fun NativeSocket_8a33_NativeSocket_poll(`ptr`: Pointer,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun NativeSocket_8a33_NativeSocket_try_poll(`ptr`: Pointer,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun NativeSocket_8a33_NativeSocket_poll_timeout(`ptr`: Pointer,`timeout`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun NativeSocket_8a33_NativeSocket_invoke(`ptr`: Pointer,`input`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun ffi_NativeSocket_8a33_rustbuffer_alloc(`size`: Int,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun ffi_NativeSocket_8a33_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    fun ffi_NativeSocket_8a33_rustbuffer_free(`buf`: RustBuffer.ByValue,
    _uniffi_out_err: RustCallStatus
    ): Unit

    fun ffi_NativeSocket_8a33_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Int,
    _uniffi_out_err: RustCallStatus
    ): RustBuffer.ByValue

    
}

// Public interface members begin here.


public object FfiConverterUByte: FfiConverter<UByte, Byte> {
    override fun lift(value: Byte): UByte {
        return value.toUByte()
    }

    override fun read(buf: ByteBuffer): UByte {
        return lift(buf.get())
    }

    override fun lower(value: UByte): Byte {
        return value.toByte()
    }

    override fun allocationSize(value: UByte) = 1

    override fun write(value: UByte, buf: ByteBuffer) {
        buf.put(value.toByte())
    }
}

public object FfiConverterInt: FfiConverter<Int, Int> {
    override fun lift(value: Int): Int {
        return value
    }

    override fun read(buf: ByteBuffer): Int {
        return buf.getInt()
    }

    override fun lower(value: Int): Int {
        return value
    }

    override fun allocationSize(value: Int) = 4

    override fun write(value: Int, buf: ByteBuffer) {
        buf.putInt(value)
    }
}

public object FfiConverterLong: FfiConverter<Long, Long> {
    override fun lift(value: Long): Long {
        return value
    }

    override fun read(buf: ByteBuffer): Long {
        return buf.getLong()
    }

    override fun lower(value: Long): Long {
        return value
    }

    override fun allocationSize(value: Long) = 8

    override fun write(value: Long, buf: ByteBuffer) {
        buf.putLong(value)
    }
}

public object FfiConverterBoolean: FfiConverter<Boolean, Byte> {
    override fun lift(value: Byte): Boolean {
        return value.toInt() != 0
    }

    override fun read(buf: ByteBuffer): Boolean {
        return lift(buf.get())
    }

    override fun lower(value: Boolean): Byte {
        return if (value) 1.toByte() else 0.toByte()
    }

    override fun allocationSize(value: Boolean) = 1

    override fun write(value: Boolean, buf: ByteBuffer) {
        buf.put(lower(value))
    }
}

public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> {
    // Note: we don't inherit from FfiConverterRustBuffer, because we use a
    // special encoding when lowering/lifting.  We can use `RustBuffer.len` to
    // store our length and avoid writing it out to the buffer.
    override fun lift(value: RustBuffer.ByValue): String {
        try {
            val byteArr = ByteArray(value.len)
            value.asByteBuffer()!!.get(byteArr)
            return byteArr.toString(Charsets.UTF_8)
        } finally {
            RustBuffer.free(value)
        }
    }

    override fun read(buf: ByteBuffer): String {
        val len = buf.getInt()
        val byteArr = ByteArray(len)
        buf.get(byteArr)
        return byteArr.toString(Charsets.UTF_8)
    }

    override fun lower(value: String): RustBuffer.ByValue {
        val byteArr = value.toByteArray(Charsets.UTF_8)
        // Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us
        // to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`.
        val rbuf = RustBuffer.alloc(byteArr.size)
        rbuf.asByteBuffer()!!.put(byteArr)
        return rbuf
    }

    // We aren't sure exactly how many bytes our string will be once it's UTF-8
    // encoded.  Allocate 3 bytes per unicode codepoint which will always be
    // enough.
    override fun allocationSize(value: String): Int {
        val sizeForLength = 4
        val sizeForString = value.length * 3
        return sizeForLength + sizeForString
    }

    override fun write(value: String, buf: ByteBuffer) {
        val byteArr = value.toByteArray(Charsets.UTF_8)
        buf.putInt(byteArr.size)
        buf.put(byteArr)
    }
}


public object FfiConverterDuration: FfiConverterRustBuffer<java.time.Duration> {
    override fun read(buf: ByteBuffer): java.time.Duration {
        // Type mismatch (should be u64) but we check for overflow/underflow below
        val seconds = buf.getLong()
        // Type mismatch (should be u32) but we check for overflow/underflow below
        val nanoseconds = buf.getInt().toLong()
        if (seconds < 0) {
            throw java.time.DateTimeException("Duration exceeds minimum or maximum value supported by uniffi")
        }
        if (nanoseconds < 0) {
            throw java.time.DateTimeException("Duration nanoseconds exceed minimum or maximum supported by uniffi")
        }
        return java.time.Duration.ofSeconds(seconds, nanoseconds)
    }

    // 8 bytes for seconds, 4 bytes for nanoseconds
    override fun allocationSize(value: java.time.Duration) = 12

    override fun write(value: java.time.Duration, buf: ByteBuffer) {
        if (value.seconds < 0) {
            // Rust does not support negative Durations
            throw IllegalArgumentException("Invalid duration, must be non-negative")
        }

        if (value.nano < 0) {
            // Java docs provide guarantee that nano will always be positive, so this should be impossible
            // See: https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html
            throw IllegalArgumentException("Invalid duration, nano value must be non-negative")
        }

        // Type mismatch (should be u64) but since Rust doesn't support negative durations we should be OK
        buf.putLong(value.seconds)
        // Type mismatch (should be u32) but since values will always be between 0 and 999,999,999 it should be OK
        buf.putInt(value.nano)
    }
}


// Interface implemented by anything that can contain an object reference.
//
// Such types expose a `destroy()` method that must be called to cleanly
// dispose of the contained objects. Failure to call this method may result
// in memory leaks.
//
// The easiest way to ensure this method is called is to use the `.use`
// helper method to execute a block and destroy the object at the end.
interface Disposable {
    fun destroy()
    companion object {
        fun destroy(vararg args: Any?) {
            args.filterIsInstance<Disposable>()
                .forEach(Disposable::destroy)
        }
    }
}

inline fun <T : Disposable?, R> T.use(block: (T) -> R) =
    try {
        block(this)
    } finally {
        try {
            // N.B. our implementation is on the nullable type `Disposable?`.
            this?.destroy()
        } catch (e: Throwable) {
            // swallow
        }
    }

// The base class for all UniFFI Object types.
//
// This class provides core operations for working with the Rust `Arc<T>` pointer to
// the live Rust struct on the other side of the FFI.
//
// There's some subtlety here, because we have to be careful not to operate on a Rust
// struct after it has been dropped, and because we must expose a public API for freeing
// the Kotlin wrapper object in lieu of reliable finalizers. The core requirements are:
//
//   * Each `FFIObject` instance holds an opaque pointer to the underlying Rust struct.
//     Method calls need to read this pointer from the object's state and pass it in to
//     the Rust FFI.
//
//   * When an `FFIObject` is no longer needed, its pointer should be passed to a
//     special destructor function provided by the Rust FFI, which will drop the
//     underlying Rust struct.
//
//   * Given an `FFIObject` instance, calling code is expected to call the special
//     `destroy` method in order to free it after use, either by calling it explicitly
//     or by using a higher-level helper like the `use` method. Failing to do so will
//     leak the underlying Rust struct.
//
//   * We can't assume that calling code will do the right thing, and must be prepared
//     to handle Kotlin method calls executing concurrently with or even after a call to
//     `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`.
//
//   * We must never allow Rust code to operate on the underlying Rust struct after
//     the destructor has been called, and must never call the destructor more than once.
//     Doing so may trigger memory unsafety.
//
// If we try to implement this with mutual exclusion on access to the pointer, there is the
// possibility of a race between a method call and a concurrent call to `destroy`:
//
//    * Thread A starts a method call, reads the value of the pointer, but is interrupted
//      before it can pass the pointer over the FFI to Rust.
//    * Thread B calls `destroy` and frees the underlying Rust struct.
//    * Thread A resumes, passing the already-read pointer value to Rust and triggering
//      a use-after-free.
//
// One possible solution would be to use a `ReadWriteLock`, with each method call taking
// a read lock (and thus allowed to run concurrently) and the special `destroy` method
// taking a write lock (and thus blocking on live method calls). However, we aim not to
// generate methods with any hidden blocking semantics, and a `destroy` method that might
// block if called incorrectly seems to meet that bar.
//
// So, we achieve our goals by giving each `FFIObject` an associated `AtomicLong` counter to track
// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy`
// has been called. These are updated according to the following rules:
//
//    * The initial value of the counter is 1, indicating a live object with no in-flight calls.
//      The initial value for the flag is false.
//
//    * At the start of each method call, we atomically check the counter.
//      If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted.
//      If it is nonzero them we atomically increment it by 1 and proceed with the method call.
//
//    * At the end of each method call, we atomically decrement and check the counter.
//      If it has reached zero then we destroy the underlying Rust struct.
//
//    * When `destroy` is called, we atomically flip the flag from false to true.
//      If the flag was already true we silently fail.
//      Otherwise we atomically decrement and check the counter.
//      If it has reached zero then we destroy the underlying Rust struct.
//
// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works,
// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`.
//
// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been
// called *and* all in-flight method calls have completed, avoiding violating any of the expectations
// of the underlying Rust code.
//
// In the future we may be able to replace some of this with automatic finalization logic, such as using
// the new "Cleaner" functionaility in Java 9. The above scheme has been designed to work even if `destroy` is
// invoked by garbage-collection machinery rather than by calling code (which by the way, it's apparently also
// possible for the JVM to finalize an object while there is an in-flight call to one of its methods [1],
// so there would still be some complexity here).
//
// Sigh...all of this for want of a robust finalization mechanism.
//
// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219
//
abstract class FFIObject(
    protected val pointer: Pointer
): Disposable, AutoCloseable {

    private val wasDestroyed = AtomicBoolean(false)
    private val callCounter = AtomicLong(1)

    open protected fun freeRustArcPtr() {
        // To be overridden in subclasses.
    }

    override fun destroy() {
        // Only allow a single call to this method.
        // TODO: maybe we should log a warning if called more than once?
        if (this.wasDestroyed.compareAndSet(false, true)) {
            // This decrement always matches the initial count of 1 given at creation time.
            if (this.callCounter.decrementAndGet() == 0L) {
                this.freeRustArcPtr()
            }
        }
    }

    @Synchronized
    override fun close() {
        this.destroy()
    }

    internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R {
        // Check and increment the call counter, to keep the object alive.
        // This needs a compare-and-set retry loop in case of concurrent updates.
        do {
            val c = this.callCounter.get()
            if (c == 0L) {
                throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed")
            }
            if (c == Long.MAX_VALUE) {
                throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow")
            }
        } while (! this.callCounter.compareAndSet(c, c + 1L))
        // Now we can safely do the method call without the pointer being freed concurrently.
        try {
            return block(this.pointer)
        } finally {
            // This decrement always matches the increment we performed above.
            if (this.callCounter.decrementAndGet() == 0L) {
                this.freeRustArcPtr()
            }
        }
    }
}

public interface NativeSocketInterface {
    
    fun `poll`(): Message?
    
    fun `tryPoll`(): Message?
    
    fun `pollTimeout`(`timeout`: java.time.Duration): Message?
    
    fun `invoke`(`input`: InvokeInput): InvokeOutput
    
}

class NativeSocket(
    pointer: Pointer
) : FFIObject(pointer), NativeSocketInterface {

    /**
     * Disconnect the object from the underlying Rust object.
     *
     * It can be called more than once, but once called, interacting with the object
     * causes an `IllegalStateException`.
     *
     * Clients **must** call this method once done with the object, or cause a memory leak.
     */
    override protected fun freeRustArcPtr() {
        rustCall() { status ->
            _UniFFILib.INSTANCE.ffi_NativeSocket_8a33_NativeSocket_object_free(this.pointer, status)
        }
    }

    override fun `poll`(): Message? =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocket_poll(it,  _status)
}
        }.let {
            FfiConverterOptionalTypeMessage.lift(it)
        }
    override fun `tryPoll`(): Message? =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocket_try_poll(it,  _status)
}
        }.let {
            FfiConverterOptionalTypeMessage.lift(it)
        }
    override fun `pollTimeout`(`timeout`: java.time.Duration): Message? =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocket_poll_timeout(it, FfiConverterDuration.lower(`timeout`),  _status)
}
        }.let {
            FfiConverterOptionalTypeMessage.lift(it)
        }
    override fun `invoke`(`input`: InvokeInput): InvokeOutput =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocket_invoke(it, FfiConverterTypeInvokeInput.lower(`input`),  _status)
}
        }.let {
            FfiConverterTypeInvokeOutput.lift(it)
        }
    

    
}

public object FfiConverterTypeNativeSocket: FfiConverter<NativeSocket, Pointer> {
    override fun lower(value: NativeSocket): Pointer = value.callWithPointer { it }

    override fun lift(value: Pointer): NativeSocket {
        return NativeSocket(value)
    }

    override fun read(buf: ByteBuffer): NativeSocket {
        // The Rust code always writes pointers as 8 bytes, and will
        // fail to compile if they don't fit.
        return lift(Pointer(buf.getLong()))
    }

    override fun allocationSize(value: NativeSocket) = 8

    override fun write(value: NativeSocket, buf: ByteBuffer) {
        // The Rust code always expects pointers written as 8 bytes,
        // and will fail to compile if they don't fit.
        buf.putLong(Pointer.nativeValue(lower(value)))
    }
}




public interface NativeSocketBuilderInterface {
    
    fun `host`(`host`: String): NativeSocketBuilder
    
    fun `token`(`token`: String): NativeSocketBuilder
    
    fun `brand`(`brand`: Int): NativeSocketBuilder
    
    fun `store`(`store`: Int): NativeSocketBuilder
    
    fun `device`(`device`: String): NativeSocketBuilder
    
    fun `ty`(`type`: Int): NativeSocketBuilder
    
    fun `cleanStart`(`cleanStart`: Boolean): NativeSocketBuilder
    
    fun `cacheDir`(`cacheDir`: String): NativeSocketBuilder
    
    fun `grpc`(`enable`: Boolean): NativeSocketBuilder
    
    fun `version`(`version`: String): NativeSocketBuilder
    
    fun `build`(): NativeSocket?
    
}

class NativeSocketBuilder(
    pointer: Pointer
) : FFIObject(pointer), NativeSocketBuilderInterface {
    constructor() :
        this(
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_new( _status)
})

    /**
     * Disconnect the object from the underlying Rust object.
     *
     * It can be called more than once, but once called, interacting with the object
     * causes an `IllegalStateException`.
     *
     * Clients **must** call this method once done with the object, or cause a memory leak.
     */
    override protected fun freeRustArcPtr() {
        rustCall() { status ->
            _UniFFILib.INSTANCE.ffi_NativeSocket_8a33_NativeSocketBuilder_object_free(this.pointer, status)
        }
    }

    override fun `host`(`host`: String): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_host(it, FfiConverterString.lower(`host`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `token`(`token`: String): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_token(it, FfiConverterString.lower(`token`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `brand`(`brand`: Int): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_brand(it, FfiConverterInt.lower(`brand`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `store`(`store`: Int): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_store(it, FfiConverterInt.lower(`store`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `device`(`device`: String): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_device(it, FfiConverterString.lower(`device`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `ty`(`type`: Int): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_ty(it, FfiConverterInt.lower(`type`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `cleanStart`(`cleanStart`: Boolean): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_clean_start(it, FfiConverterBoolean.lower(`cleanStart`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `cacheDir`(`cacheDir`: String): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_cache_dir(it, FfiConverterString.lower(`cacheDir`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `grpc`(`enable`: Boolean): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_grpc(it, FfiConverterBoolean.lower(`enable`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `version`(`version`: String): NativeSocketBuilder =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_version(it, FfiConverterString.lower(`version`),  _status)
}
        }.let {
            FfiConverterTypeNativeSocketBuilder.lift(it)
        }
    override fun `build`(): NativeSocket? =
        callWithPointer {
    rustCall() { _status ->
    _UniFFILib.INSTANCE.NativeSocket_8a33_NativeSocketBuilder_build(it,  _status)
}
        }.let {
            FfiConverterOptionalTypeNativeSocket.lift(it)
        }
    

    
}

public object FfiConverterTypeNativeSocketBuilder: FfiConverter<NativeSocketBuilder, Pointer> {
    override fun lower(value: NativeSocketBuilder): Pointer = value.callWithPointer { it }

    override fun lift(value: Pointer): NativeSocketBuilder {
        return NativeSocketBuilder(value)
    }

    override fun read(buf: ByteBuffer): NativeSocketBuilder {
        // The Rust code always writes pointers as 8 bytes, and will
        // fail to compile if they don't fit.
        return lift(Pointer(buf.getLong()))
    }

    override fun allocationSize(value: NativeSocketBuilder) = 8

    override fun write(value: NativeSocketBuilder, buf: ByteBuffer) {
        // The Rust code always expects pointers written as 8 bytes,
        // and will fail to compile if they don't fit.
        buf.putLong(Pointer.nativeValue(lower(value)))
    }
}




data class Message (
    var `id`: Long, 
    var `ty`: Int, 
    var `qos`: Qos, 
    var `data`: List<UByte>?
) {
    
}

public object FfiConverterTypeMessage: FfiConverterRustBuffer<Message> {
    override fun read(buf: ByteBuffer): Message {
        return Message(
            FfiConverterLong.read(buf),
            FfiConverterInt.read(buf),
            FfiConverterTypeQos.read(buf),
            FfiConverterOptionalSequenceUByte.read(buf),
        )
    }

    override fun allocationSize(value: Message) = (
            FfiConverterLong.allocationSize(value.`id`) +
            FfiConverterInt.allocationSize(value.`ty`) +
            FfiConverterTypeQos.allocationSize(value.`qos`) +
            FfiConverterOptionalSequenceUByte.allocationSize(value.`data`)
    )

    override fun write(value: Message, buf: ByteBuffer) {
            FfiConverterLong.write(value.`id`, buf)
            FfiConverterInt.write(value.`ty`, buf)
            FfiConverterTypeQos.write(value.`qos`, buf)
            FfiConverterOptionalSequenceUByte.write(value.`data`, buf)
    }
}




sealed class InvokeInput {
    data class Start(
        val `cleanStart`: Boolean
        ) : InvokeInput()
    object Stop : InvokeInput()
    
    data class Ack(
        val `messageId`: Long
        ) : InvokeInput()
    data class Cache(
        val `messageId`: Long
        ) : InvokeInput()
    object Online : InvokeInput()
    
    data class Push(
        val `message`: Message
        ) : InvokeInput()
    object Grpc : InvokeInput()
    
    object History : InvokeInput()
    
    

    
}

public object FfiConverterTypeInvokeInput : FfiConverterRustBuffer<InvokeInput>{
    override fun read(buf: ByteBuffer): InvokeInput {
        return when(buf.getInt()) {
            1 -> InvokeInput.Start(
                FfiConverterBoolean.read(buf),
                )
            2 -> InvokeInput.Stop
            3 -> InvokeInput.Ack(
                FfiConverterLong.read(buf),
                )
            4 -> InvokeInput.Cache(
                FfiConverterLong.read(buf),
                )
            5 -> InvokeInput.Online
            6 -> InvokeInput.Push(
                FfiConverterTypeMessage.read(buf),
                )
            7 -> InvokeInput.Grpc
            8 -> InvokeInput.History
            else -> throw RuntimeException("invalid enum value, something is very wrong!!")
        }
    }

    override fun allocationSize(value: InvokeInput) = when(value) {
        is InvokeInput.Start -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterBoolean.allocationSize(value.`cleanStart`)
            )
        }
        is InvokeInput.Stop -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
            )
        }
        is InvokeInput.Ack -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterLong.allocationSize(value.`messageId`)
            )
        }
        is InvokeInput.Cache -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterLong.allocationSize(value.`messageId`)
            )
        }
        is InvokeInput.Online -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
            )
        }
        is InvokeInput.Push -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterTypeMessage.allocationSize(value.`message`)
            )
        }
        is InvokeInput.Grpc -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
            )
        }
        is InvokeInput.History -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
            )
        }
    }

    override fun write(value: InvokeInput, buf: ByteBuffer) {
        when(value) {
            is InvokeInput.Start -> {
                buf.putInt(1)
                FfiConverterBoolean.write(value.`cleanStart`, buf)
                Unit
            }
            is InvokeInput.Stop -> {
                buf.putInt(2)
                Unit
            }
            is InvokeInput.Ack -> {
                buf.putInt(3)
                FfiConverterLong.write(value.`messageId`, buf)
                Unit
            }
            is InvokeInput.Cache -> {
                buf.putInt(4)
                FfiConverterLong.write(value.`messageId`, buf)
                Unit
            }
            is InvokeInput.Online -> {
                buf.putInt(5)
                Unit
            }
            is InvokeInput.Push -> {
                buf.putInt(6)
                FfiConverterTypeMessage.write(value.`message`, buf)
                Unit
            }
            is InvokeInput.Grpc -> {
                buf.putInt(7)
                Unit
            }
            is InvokeInput.History -> {
                buf.putInt(8)
                Unit
            }
        }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
    }
}






sealed class InvokeOutput {
    object None : InvokeOutput()
    
    data class Cache(
        val `message`: Message?
        ) : InvokeOutput()
    data class Online(
        val `status`: Boolean
        ) : InvokeOutput()
    data class History(
        val `count`: Int
        ) : InvokeOutput()
    data class Grpc(
        val `port`: Int
        ) : InvokeOutput()
    

    
}

public object FfiConverterTypeInvokeOutput : FfiConverterRustBuffer<InvokeOutput>{
    override fun read(buf: ByteBuffer): InvokeOutput {
        return when(buf.getInt()) {
            1 -> InvokeOutput.None
            2 -> InvokeOutput.Cache(
                FfiConverterOptionalTypeMessage.read(buf),
                )
            3 -> InvokeOutput.Online(
                FfiConverterBoolean.read(buf),
                )
            4 -> InvokeOutput.History(
                FfiConverterInt.read(buf),
                )
            5 -> InvokeOutput.Grpc(
                FfiConverterInt.read(buf),
                )
            else -> throw RuntimeException("invalid enum value, something is very wrong!!")
        }
    }

    override fun allocationSize(value: InvokeOutput) = when(value) {
        is InvokeOutput.None -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
            )
        }
        is InvokeOutput.Cache -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterOptionalTypeMessage.allocationSize(value.`message`)
            )
        }
        is InvokeOutput.Online -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterBoolean.allocationSize(value.`status`)
            )
        }
        is InvokeOutput.History -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterInt.allocationSize(value.`count`)
            )
        }
        is InvokeOutput.Grpc -> {
            // Add the size for the Int that specifies the variant plus the size needed for all fields
            (
                4
                + FfiConverterInt.allocationSize(value.`port`)
            )
        }
    }

    override fun write(value: InvokeOutput, buf: ByteBuffer) {
        when(value) {
            is InvokeOutput.None -> {
                buf.putInt(1)
                Unit
            }
            is InvokeOutput.Cache -> {
                buf.putInt(2)
                FfiConverterOptionalTypeMessage.write(value.`message`, buf)
                Unit
            }
            is InvokeOutput.Online -> {
                buf.putInt(3)
                FfiConverterBoolean.write(value.`status`, buf)
                Unit
            }
            is InvokeOutput.History -> {
                buf.putInt(4)
                FfiConverterInt.write(value.`count`, buf)
                Unit
            }
            is InvokeOutput.Grpc -> {
                buf.putInt(5)
                FfiConverterInt.write(value.`port`, buf)
                Unit
            }
        }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
    }
}






enum class Qos {
    AT_MOST_ONCE,AT_LEAST_ONCE;
}

public object FfiConverterTypeQos: FfiConverterRustBuffer<Qos> {
    override fun read(buf: ByteBuffer) = try {
        Qos.values()[buf.getInt() - 1]
    } catch (e: IndexOutOfBoundsException) {
        throw RuntimeException("invalid enum value, something is very wrong!!", e)
    }

    override fun allocationSize(value: Qos) = 4

    override fun write(value: Qos, buf: ByteBuffer) {
        buf.putInt(value.ordinal + 1)
    }
}






public object FfiConverterOptionalTypeNativeSocket: FfiConverterRustBuffer<NativeSocket?> {
    override fun read(buf: ByteBuffer): NativeSocket? {
        if (buf.get().toInt() == 0) {
            return null
        }
        return FfiConverterTypeNativeSocket.read(buf)
    }

    override fun allocationSize(value: NativeSocket?): Int {
        if (value == null) {
            return 1
        } else {
            return 1 + FfiConverterTypeNativeSocket.allocationSize(value)
        }
    }

    override fun write(value: NativeSocket?, buf: ByteBuffer) {
        if (value == null) {
            buf.put(0)
        } else {
            buf.put(1)
            FfiConverterTypeNativeSocket.write(value, buf)
        }
    }
}




public object FfiConverterOptionalTypeMessage: FfiConverterRustBuffer<Message?> {
    override fun read(buf: ByteBuffer): Message? {
        if (buf.get().toInt() == 0) {
            return null
        }
        return FfiConverterTypeMessage.read(buf)
    }

    override fun allocationSize(value: Message?): Int {
        if (value == null) {
            return 1
        } else {
            return 1 + FfiConverterTypeMessage.allocationSize(value)
        }
    }

    override fun write(value: Message?, buf: ByteBuffer) {
        if (value == null) {
            buf.put(0)
        } else {
            buf.put(1)
            FfiConverterTypeMessage.write(value, buf)
        }
    }
}




public object FfiConverterOptionalSequenceUByte: FfiConverterRustBuffer<List<UByte>?> {
    override fun read(buf: ByteBuffer): List<UByte>? {
        if (buf.get().toInt() == 0) {
            return null
        }
        return FfiConverterSequenceUByte.read(buf)
    }

    override fun allocationSize(value: List<UByte>?): Int {
        if (value == null) {
            return 1
        } else {
            return 1 + FfiConverterSequenceUByte.allocationSize(value)
        }
    }

    override fun write(value: List<UByte>?, buf: ByteBuffer) {
        if (value == null) {
            buf.put(0)
        } else {
            buf.put(1)
            FfiConverterSequenceUByte.write(value, buf)
        }
    }
}




public object FfiConverterSequenceUByte: FfiConverterRustBuffer<List<UByte>> {
    override fun read(buf: ByteBuffer): List<UByte> {
        val len = buf.getInt()
        return List<UByte>(len) {
            FfiConverterUByte.read(buf)
        }
    }

    override fun allocationSize(value: List<UByte>): Int {
        val sizeForLength = 4
        val sizeForItems = value.map { FfiConverterUByte.allocationSize(it) }.sum()
        return sizeForLength + sizeForItems
    }

    override fun write(value: List<UByte>, buf: ByteBuffer) {
        buf.putInt(value.size)
        value.forEach {
            FfiConverterUByte.write(it, buf)
        }
    }
}


