Advertisement
owi_acumalaka

Generated kotlin code from uniffi-rs

Dec 4th, 2024
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 36.41 KB | Software | 0 0
  1. // This file was autogenerated by some hot garbage in the `uniffi` crate.
  2. // Trust me, you don't want to mess with it!
  3.  
  4. @file:Suppress("NAME_SHADOWING")
  5.  
  6. package uniffi.sample;
  7.  
  8. // Common helper code.
  9. //
  10. // Ideally this would live in a separate .kt file where it can be unittested etc
  11. // in isolation, and perhaps even published as a re-useable package.
  12. //
  13. // However, it's important that the details of how this helper code works (e.g. the
  14. // way that different builtin types are passed across the FFI) exactly match what's
  15. // expected by the Rust code on the other side of the interface. In practice right
  16. // now that means coming from the exact some version of `uniffi` that was used to
  17. // compile the Rust component. The easiest way to ensure this is to bundle the Kotlin
  18. // helpers directly inline like we're doing here.
  19.  
  20. import com.sun.jna.Library
  21. import com.sun.jna.IntegerType
  22. import com.sun.jna.Native
  23. import com.sun.jna.Pointer
  24. import com.sun.jna.Structure
  25. import com.sun.jna.Callback
  26. import com.sun.jna.ptr.*
  27. import java.nio.ByteBuffer
  28. import java.nio.ByteOrder
  29. import java.nio.CharBuffer
  30. import java.nio.charset.CodingErrorAction
  31. import java.util.concurrent.atomic.AtomicLong
  32. import java.util.concurrent.ConcurrentHashMap
  33.  
  34. // This is a helper for safely working with byte buffers returned from the Rust code.
  35. // A rust-owned buffer is represented by its capacity, its current length, and a
  36. // pointer to the underlying data.
  37.  
  38. @Structure.FieldOrder("capacity", "len", "data")
  39. open class RustBuffer : Structure() {
  40.     // Note: `capacity` and `len` are actually `ULong` values, but JVM only supports signed values.
  41.     // When dealing with these fields, make sure to call `toULong()`.
  42.     @JvmField var capacity: Long = 0
  43.     @JvmField var len: Long = 0
  44.     @JvmField var data: Pointer? = null
  45.  
  46.     class ByValue: RustBuffer(), Structure.ByValue
  47.     class ByReference: RustBuffer(), Structure.ByReference
  48.  
  49.    internal fun setValue(other: RustBuffer) {
  50.         capacity = other.capacity
  51.         len = other.len
  52.         data = other.data
  53.     }
  54.  
  55.     companion object {
  56.         internal fun alloc(size: ULong = 0UL) = uniffiRustCall() { status ->
  57.             // Note: need to convert the size to a `Long` value to make this work with JVM.
  58.             UniffiLib.INSTANCE.ffi_sample_rustbuffer_alloc(size.toLong(), status)
  59.         }.also {
  60.             if(it.data == null) {
  61.                throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})")
  62.            }
  63.         }
  64.  
  65.         internal fun create(capacity: ULong, len: ULong, data: Pointer?): RustBuffer.ByValue {
  66.             var buf = RustBuffer.ByValue()
  67.             buf.capacity = capacity.toLong()
  68.             buf.len = len.toLong()
  69.             buf.data = data
  70.             return buf
  71.         }
  72.  
  73.         internal fun free(buf: RustBuffer.ByValue) = uniffiRustCall() { status ->
  74.             UniffiLib.INSTANCE.ffi_sample_rustbuffer_free(buf, status)
  75.         }
  76.     }
  77.  
  78.     @Suppress("TooGenericExceptionThrown")
  79.     fun asByteBuffer() =
  80.         this.data?.getByteBuffer(0, this.len.toLong())?.also {
  81.             it.order(ByteOrder.BIG_ENDIAN)
  82.         }
  83. }
  84.  
  85. /**
  86.  * The equivalent of the `*mut RustBuffer` type.
  87.  * Required for callbacks taking in an out pointer.
  88.  *
  89.  * Size is the sum of all values in the struct.
  90.  */
  91. class RustBufferByReference : ByReference(16) {
  92.     /**
  93.      * Set the pointed-to `RustBuffer` to the given value.
  94.      */
  95.     fun setValue(value: RustBuffer.ByValue) {
  96.         // NOTE: The offsets are as they are in the C-like struct.
  97.         val pointer = getPointer()
  98.         pointer.setLong(0, value.capacity)
  99.         pointer.setLong(8, value.len)
  100.         pointer.setPointer(16, value.data)
  101.     }
  102.  
  103.     /**
  104.      * Get a `RustBuffer.ByValue` from this reference.
  105.      */
  106.     fun getValue(): RustBuffer.ByValue {
  107.         val pointer = getPointer()
  108.         val value = RustBuffer.ByValue()
  109.         value.writeField("capacity", pointer.getLong(0))
  110.         value.writeField("len", pointer.getLong(8))
  111.         value.writeField("data", pointer.getLong(16))
  112.  
  113.         return value
  114.     }
  115. }
  116.  
  117. // This is a helper for safely passing byte references into the rust code.
  118. // It's not actually used at the moment, because there aren't many things that you
  119. // can take a direct pointer to in the JVM, and if we're going to copy something
  120. // then we might as well copy it into a `RustBuffer`. But it's here for API
  121. // completeness.
  122.  
  123. @Structure.FieldOrder("len", "data")
  124. open class ForeignBytes : Structure() {
  125.     @JvmField var len: Int = 0
  126.     @JvmField var data: Pointer? = null
  127.  
  128.     class ByValue : ForeignBytes(), Structure.ByValue
  129. }
  130. // The FfiConverter interface handles converter types to and from the FFI
  131. //
  132. // All implementing objects should be public to support external types.  When a
  133. // type is external we need to import it's FfiConverter.
  134. public interface FfiConverter<KotlinType, FfiType> {
  135.     // Convert an FFI type to a Kotlin type
  136.     fun lift(value: FfiType): KotlinType
  137.  
  138.     // Convert an Kotlin type to an FFI type
  139.     fun lower(value: KotlinType): FfiType
  140.  
  141.     // Read a Kotlin type from a `ByteBuffer`
  142.     fun read(buf: ByteBuffer): KotlinType
  143.  
  144.     // Calculate bytes to allocate when creating a `RustBuffer`
  145.     //
  146.     // This must return at least as many bytes as the write() function will
  147.     // write. It can return more bytes than needed, for example when writing
  148.     // Strings we can't know the exact bytes needed until we the UTF-8
  149.     // encoding, so we pessimistically allocate the largest size possible (3
  150.     // bytes per codepoint).  Allocating extra bytes is not really a big deal
  151.     // because the `RustBuffer` is short-lived.
  152.     fun allocationSize(value: KotlinType): ULong
  153.  
  154.     // Write a Kotlin type to a `ByteBuffer`
  155.     fun write(value: KotlinType, buf: ByteBuffer)
  156.  
  157.     // Lower a value into a `RustBuffer`
  158.     //
  159.     // This method lowers a value into a `RustBuffer` rather than the normal
  160.     // FfiType.  It's used by the callback interface code.  Callback interface
  161.     // returns are always serialized into a `RustBuffer` regardless of their
  162.     // normal FFI type.
  163.     fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue {
  164.         val rbuf = RustBuffer.alloc(allocationSize(value))
  165.         try {
  166.             val bbuf = rbuf.data!!.getByteBuffer(0, rbuf.capacity).also {
  167.                 it.order(ByteOrder.BIG_ENDIAN)
  168.             }
  169.             write(value, bbuf)
  170.             rbuf.writeField("len", bbuf.position().toLong())
  171.             return rbuf
  172.         } catch (e: Throwable) {
  173.             RustBuffer.free(rbuf)
  174.             throw e
  175.         }
  176.     }
  177.  
  178.     // Lift a value from a `RustBuffer`.
  179.     //
  180.     // This here mostly because of the symmetry with `lowerIntoRustBuffer()`.
  181.     // It's currently only used by the `FfiConverterRustBuffer` class below.
  182.     fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType {
  183.         val byteBuf = rbuf.asByteBuffer()!!
  184.         try {
  185.            val item = read(byteBuf)
  186.            if (byteBuf.hasRemaining()) {
  187.                throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!")
  188.            }
  189.            return item
  190.         } finally {
  191.             RustBuffer.free(rbuf)
  192.         }
  193.     }
  194. }
  195.  
  196. // FfiConverter that uses `RustBuffer` as the FfiType
  197. public interface FfiConverterRustBuffer<KotlinType>: FfiConverter<KotlinType, RustBuffer.ByValue> {
  198.     override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value)
  199.     override fun lower(value: KotlinType) = lowerIntoRustBuffer(value)
  200. }
  201. // A handful of classes and functions to support the generated data structures.
  202. // This would be a good candidate for isolating in its own ffi-support lib.
  203.  
  204. internal const val UNIFFI_CALL_SUCCESS = 0.toByte()
  205. internal const val UNIFFI_CALL_ERROR = 1.toByte()
  206. internal const val UNIFFI_CALL_UNEXPECTED_ERROR = 2.toByte()
  207.  
  208. @Structure.FieldOrder("code", "error_buf")
  209. internal open class UniffiRustCallStatus : Structure() {
  210.     @JvmField var code: Byte = 0
  211.     @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue()
  212.  
  213.     class ByValue: UniffiRustCallStatus(), Structure.ByValue
  214.  
  215.     fun isSuccess(): Boolean {
  216.         return code == UNIFFI_CALL_SUCCESS
  217.     }
  218.  
  219.     fun isError(): Boolean {
  220.         return code == UNIFFI_CALL_ERROR
  221.     }
  222.  
  223.     fun isPanic(): Boolean {
  224.         return code == UNIFFI_CALL_UNEXPECTED_ERROR
  225.     }
  226.  
  227.     companion object {
  228.         fun create(code: Byte, errorBuf: RustBuffer.ByValue): UniffiRustCallStatus.ByValue {
  229.             val callStatus = UniffiRustCallStatus.ByValue()
  230.             callStatus.code = code
  231.             callStatus.error_buf = errorBuf
  232.             return callStatus
  233.         }
  234.     }
  235. }
  236.  
  237. class InternalException(message: String) : Exception(message)
  238.  
  239. // Each top-level error class has a companion object that can lift the error from the call status's rust buffer
  240. interface UniffiRustCallStatusErrorHandler<E> {
  241.     fun lift(error_buf: RustBuffer.ByValue): E;
  242. }
  243.  
  244. // Helpers for calling Rust
  245. // In practice we usually need to be synchronized to call this safely, so it doesn't
  246. // synchronize itself
  247.  
  248. // Call a rust function that returns a Result<>.  Pass in the Error class companion that corresponds to the Err
  249. private inline fun <U, E: Exception> uniffiRustCallWithError(errorHandler: UniffiRustCallStatusErrorHandler<E>, callback: (UniffiRustCallStatus) -> U): U {
  250.     var status = UniffiRustCallStatus();
  251.     val return_value = callback(status)
  252.     uniffiCheckCallStatus(errorHandler, status)
  253.     return return_value
  254. }
  255.  
  256. // Check UniffiRustCallStatus and throw an error if the call wasn't successful
  257. private fun<E: Exception> uniffiCheckCallStatus(errorHandler: UniffiRustCallStatusErrorHandler<E>, status: UniffiRustCallStatus) {
  258.     if (status.isSuccess()) {
  259.         return
  260.     } else if (status.isError()) {
  261.         throw errorHandler.lift(status.error_buf)
  262.     } else if (status.isPanic()) {
  263.         // when the rust code sees a panic, it tries to construct a rustbuffer
  264.         // with the message.  but if that code panics, then it just sends back
  265.         // an empty buffer.
  266.         if (status.error_buf.len > 0) {
  267.             throw InternalException(FfiConverterString.lift(status.error_buf))
  268.         } else {
  269.             throw InternalException("Rust panic")
  270.         }
  271.     } else {
  272.         throw InternalException("Unknown rust call status: $status.code")
  273.     }
  274. }
  275.  
  276. // UniffiRustCallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR
  277. object UniffiNullRustCallStatusErrorHandler: UniffiRustCallStatusErrorHandler<InternalException> {
  278.     override fun lift(error_buf: RustBuffer.ByValue): InternalException {
  279.         RustBuffer.free(error_buf)
  280.         return InternalException("Unexpected CALL_ERROR")
  281.     }
  282. }
  283.  
  284. // Call a rust function that returns a plain value
  285. private inline fun <U> uniffiRustCall(callback: (UniffiRustCallStatus) -> U): U {
  286.     return uniffiRustCallWithError(UniffiNullRustCallStatusErrorHandler, callback);
  287. }
  288.  
  289. internal inline fun<T> uniffiTraitInterfaceCall(
  290.     callStatus: UniffiRustCallStatus,
  291.     makeCall: () -> T,
  292.     writeReturn: (T) -> Unit,
  293. ) {
  294.     try {
  295.         writeReturn(makeCall())
  296.     } catch(e: Exception) {
  297.         callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
  298.         callStatus.error_buf = FfiConverterString.lower(e.toString())
  299.     }
  300. }
  301.  
  302. internal inline fun<T, reified E: Throwable> uniffiTraitInterfaceCallWithError(
  303.     callStatus: UniffiRustCallStatus,
  304.     makeCall: () -> T,
  305.     writeReturn: (T) -> Unit,
  306.     lowerError: (E) -> RustBuffer.ByValue
  307. ) {
  308.     try {
  309.         writeReturn(makeCall())
  310.     } catch(e: Exception) {
  311.         if (e is E) {
  312.             callStatus.code = UNIFFI_CALL_ERROR
  313.             callStatus.error_buf = lowerError(e)
  314.         } else {
  315.             callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR
  316.             callStatus.error_buf = FfiConverterString.lower(e.toString())
  317.         }
  318.     }
  319. }
  320. // Map handles to objects
  321. //
  322. // This is used pass an opaque 64-bit handle representing a foreign object to the Rust code.
  323. internal class UniffiHandleMap<T: Any> {
  324.     private val map = ConcurrentHashMap<Long, T>()
  325.     private val counter = java.util.concurrent.atomic.AtomicLong(0)
  326.  
  327.     val size: Int
  328.         get() = map.size
  329.  
  330.     // Insert a new object into the handle map and get a handle for it
  331.     fun insert(obj: T): Long {
  332.         val handle = counter.getAndAdd(1)
  333.         map.put(handle, obj)
  334.         return handle
  335.     }
  336.  
  337.     // Get an object from the handle map
  338.     fun get(handle: Long): T {
  339.         return map.get(handle) ?: throw InternalException("UniffiHandleMap.get: Invalid handle")
  340.     }
  341.  
  342.     // Remove an entry from the handlemap and get the Kotlin object back
  343.     fun remove(handle: Long): T {
  344.         return map.remove(handle) ?: throw InternalException("UniffiHandleMap: Invalid handle")
  345.     }
  346. }
  347.  
  348. // Contains loading, initialization code,
  349. // and the FFI Function declarations in a com.sun.jna.Library.
  350. @Synchronized
  351. private fun findLibraryName(componentName: String): String {
  352.     val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride")
  353.     if (libOverride != null) {
  354.         return libOverride
  355.     }
  356.     return "sample"
  357. }
  358.  
  359. private inline fun <reified Lib : Library> loadIndirect(
  360.     componentName: String
  361. ): Lib {
  362.     return Native.load<Lib>(findLibraryName(componentName), Lib::class.java)
  363. }
  364.  
  365. // Define FFI callback types
  366. internal interface UniffiRustFutureContinuationCallback : com.sun.jna.Callback {
  367.     fun callback(`data`: Long,`pollResult`: Byte,)
  368. }
  369. internal interface UniffiForeignFutureFree : com.sun.jna.Callback {
  370.     fun callback(`handle`: Long,)
  371. }
  372. internal interface UniffiCallbackInterfaceFree : com.sun.jna.Callback {
  373.     fun callback(`handle`: Long,)
  374. }
  375. @Structure.FieldOrder("handle", "free")
  376. internal open class UniffiForeignFuture(
  377.     @JvmField internal var `handle`: Long = 0.toLong(),
  378.     @JvmField internal var `free`: UniffiForeignFutureFree? = null,
  379. ) : Structure() {
  380.     class UniffiByValue(
  381.         `handle`: Long = 0.toLong(),
  382.         `free`: UniffiForeignFutureFree? = null,
  383.     ): UniffiForeignFuture(`handle`,`free`,), Structure.ByValue
  384.  
  385.    internal fun uniffiSetValue(other: UniffiForeignFuture) {
  386.         `handle` = other.`handle`
  387.         `free` = other.`free`
  388.     }
  389.  
  390. }
  391. @Structure.FieldOrder("returnValue", "callStatus")
  392. internal open class UniffiForeignFutureStructU8(
  393.     @JvmField internal var `returnValue`: Byte = 0.toByte(),
  394.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  395. ) : Structure() {
  396.     class UniffiByValue(
  397.         `returnValue`: Byte = 0.toByte(),
  398.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  399.     ): UniffiForeignFutureStructU8(`returnValue`,`callStatus`,), Structure.ByValue
  400.  
  401.    internal fun uniffiSetValue(other: UniffiForeignFutureStructU8) {
  402.         `returnValue` = other.`returnValue`
  403.         `callStatus` = other.`callStatus`
  404.     }
  405.  
  406. }
  407. internal interface UniffiForeignFutureCompleteU8 : com.sun.jna.Callback {
  408.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU8.UniffiByValue,)
  409. }
  410. @Structure.FieldOrder("returnValue", "callStatus")
  411. internal open class UniffiForeignFutureStructI8(
  412.     @JvmField internal var `returnValue`: Byte = 0.toByte(),
  413.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  414. ) : Structure() {
  415.     class UniffiByValue(
  416.         `returnValue`: Byte = 0.toByte(),
  417.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  418.     ): UniffiForeignFutureStructI8(`returnValue`,`callStatus`,), Structure.ByValue
  419.  
  420.    internal fun uniffiSetValue(other: UniffiForeignFutureStructI8) {
  421.         `returnValue` = other.`returnValue`
  422.         `callStatus` = other.`callStatus`
  423.     }
  424.  
  425. }
  426. internal interface UniffiForeignFutureCompleteI8 : com.sun.jna.Callback {
  427.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI8.UniffiByValue,)
  428. }
  429. @Structure.FieldOrder("returnValue", "callStatus")
  430. internal open class UniffiForeignFutureStructU16(
  431.     @JvmField internal var `returnValue`: Short = 0.toShort(),
  432.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  433. ) : Structure() {
  434.     class UniffiByValue(
  435.         `returnValue`: Short = 0.toShort(),
  436.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  437.     ): UniffiForeignFutureStructU16(`returnValue`,`callStatus`,), Structure.ByValue
  438.  
  439.    internal fun uniffiSetValue(other: UniffiForeignFutureStructU16) {
  440.         `returnValue` = other.`returnValue`
  441.         `callStatus` = other.`callStatus`
  442.     }
  443.  
  444. }
  445. internal interface UniffiForeignFutureCompleteU16 : com.sun.jna.Callback {
  446.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU16.UniffiByValue,)
  447. }
  448. @Structure.FieldOrder("returnValue", "callStatus")
  449. internal open class UniffiForeignFutureStructI16(
  450.     @JvmField internal var `returnValue`: Short = 0.toShort(),
  451.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  452. ) : Structure() {
  453.     class UniffiByValue(
  454.         `returnValue`: Short = 0.toShort(),
  455.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  456.     ): UniffiForeignFutureStructI16(`returnValue`,`callStatus`,), Structure.ByValue
  457.  
  458.    internal fun uniffiSetValue(other: UniffiForeignFutureStructI16) {
  459.         `returnValue` = other.`returnValue`
  460.         `callStatus` = other.`callStatus`
  461.     }
  462.  
  463. }
  464. internal interface UniffiForeignFutureCompleteI16 : com.sun.jna.Callback {
  465.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI16.UniffiByValue,)
  466. }
  467. @Structure.FieldOrder("returnValue", "callStatus")
  468. internal open class UniffiForeignFutureStructU32(
  469.     @JvmField internal var `returnValue`: Int = 0,
  470.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  471. ) : Structure() {
  472.     class UniffiByValue(
  473.         `returnValue`: Int = 0,
  474.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  475.     ): UniffiForeignFutureStructU32(`returnValue`,`callStatus`,), Structure.ByValue
  476.  
  477.    internal fun uniffiSetValue(other: UniffiForeignFutureStructU32) {
  478.         `returnValue` = other.`returnValue`
  479.         `callStatus` = other.`callStatus`
  480.     }
  481.  
  482. }
  483. internal interface UniffiForeignFutureCompleteU32 : com.sun.jna.Callback {
  484.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU32.UniffiByValue,)
  485. }
  486. @Structure.FieldOrder("returnValue", "callStatus")
  487. internal open class UniffiForeignFutureStructI32(
  488.     @JvmField internal var `returnValue`: Int = 0,
  489.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  490. ) : Structure() {
  491.     class UniffiByValue(
  492.         `returnValue`: Int = 0,
  493.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  494.     ): UniffiForeignFutureStructI32(`returnValue`,`callStatus`,), Structure.ByValue
  495.  
  496.    internal fun uniffiSetValue(other: UniffiForeignFutureStructI32) {
  497.         `returnValue` = other.`returnValue`
  498.         `callStatus` = other.`callStatus`
  499.     }
  500.  
  501. }
  502. internal interface UniffiForeignFutureCompleteI32 : com.sun.jna.Callback {
  503.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI32.UniffiByValue,)
  504. }
  505. @Structure.FieldOrder("returnValue", "callStatus")
  506. internal open class UniffiForeignFutureStructU64(
  507.     @JvmField internal var `returnValue`: Long = 0.toLong(),
  508.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  509. ) : Structure() {
  510.     class UniffiByValue(
  511.         `returnValue`: Long = 0.toLong(),
  512.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  513.     ): UniffiForeignFutureStructU64(`returnValue`,`callStatus`,), Structure.ByValue
  514.  
  515.    internal fun uniffiSetValue(other: UniffiForeignFutureStructU64) {
  516.         `returnValue` = other.`returnValue`
  517.         `callStatus` = other.`callStatus`
  518.     }
  519.  
  520. }
  521. internal interface UniffiForeignFutureCompleteU64 : com.sun.jna.Callback {
  522.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU64.UniffiByValue,)
  523. }
  524. @Structure.FieldOrder("returnValue", "callStatus")
  525. internal open class UniffiForeignFutureStructI64(
  526.     @JvmField internal var `returnValue`: Long = 0.toLong(),
  527.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  528. ) : Structure() {
  529.     class UniffiByValue(
  530.         `returnValue`: Long = 0.toLong(),
  531.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  532.     ): UniffiForeignFutureStructI64(`returnValue`,`callStatus`,), Structure.ByValue
  533.  
  534.    internal fun uniffiSetValue(other: UniffiForeignFutureStructI64) {
  535.         `returnValue` = other.`returnValue`
  536.         `callStatus` = other.`callStatus`
  537.     }
  538.  
  539. }
  540. internal interface UniffiForeignFutureCompleteI64 : com.sun.jna.Callback {
  541.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI64.UniffiByValue,)
  542. }
  543. @Structure.FieldOrder("returnValue", "callStatus")
  544. internal open class UniffiForeignFutureStructF32(
  545.     @JvmField internal var `returnValue`: Float = 0.0f,
  546.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  547. ) : Structure() {
  548.     class UniffiByValue(
  549.         `returnValue`: Float = 0.0f,
  550.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  551.     ): UniffiForeignFutureStructF32(`returnValue`,`callStatus`,), Structure.ByValue
  552.  
  553.    internal fun uniffiSetValue(other: UniffiForeignFutureStructF32) {
  554.         `returnValue` = other.`returnValue`
  555.         `callStatus` = other.`callStatus`
  556.     }
  557.  
  558. }
  559. internal interface UniffiForeignFutureCompleteF32 : com.sun.jna.Callback {
  560.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructF32.UniffiByValue,)
  561. }
  562. @Structure.FieldOrder("returnValue", "callStatus")
  563. internal open class UniffiForeignFutureStructF64(
  564.     @JvmField internal var `returnValue`: Double = 0.0,
  565.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  566. ) : Structure() {
  567.     class UniffiByValue(
  568.         `returnValue`: Double = 0.0,
  569.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  570.     ): UniffiForeignFutureStructF64(`returnValue`,`callStatus`,), Structure.ByValue
  571.  
  572.    internal fun uniffiSetValue(other: UniffiForeignFutureStructF64) {
  573.         `returnValue` = other.`returnValue`
  574.         `callStatus` = other.`callStatus`
  575.     }
  576.  
  577. }
  578. internal interface UniffiForeignFutureCompleteF64 : com.sun.jna.Callback {
  579.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructF64.UniffiByValue,)
  580. }
  581. @Structure.FieldOrder("returnValue", "callStatus")
  582. internal open class UniffiForeignFutureStructPointer(
  583.     @JvmField internal var `returnValue`: Pointer = Pointer.NULL,
  584.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  585. ) : Structure() {
  586.     class UniffiByValue(
  587.         `returnValue`: Pointer = Pointer.NULL,
  588.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  589.     ): UniffiForeignFutureStructPointer(`returnValue`,`callStatus`,), Structure.ByValue
  590.  
  591.    internal fun uniffiSetValue(other: UniffiForeignFutureStructPointer) {
  592.         `returnValue` = other.`returnValue`
  593.         `callStatus` = other.`callStatus`
  594.     }
  595.  
  596. }
  597. internal interface UniffiForeignFutureCompletePointer : com.sun.jna.Callback {
  598.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructPointer.UniffiByValue,)
  599. }
  600. @Structure.FieldOrder("returnValue", "callStatus")
  601. internal open class UniffiForeignFutureStructRustBuffer(
  602.     @JvmField internal var `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
  603.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  604. ) : Structure() {
  605.     class UniffiByValue(
  606.         `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(),
  607.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  608.     ): UniffiForeignFutureStructRustBuffer(`returnValue`,`callStatus`,), Structure.ByValue
  609.  
  610.    internal fun uniffiSetValue(other: UniffiForeignFutureStructRustBuffer) {
  611.         `returnValue` = other.`returnValue`
  612.         `callStatus` = other.`callStatus`
  613.     }
  614.  
  615. }
  616. internal interface UniffiForeignFutureCompleteRustBuffer : com.sun.jna.Callback {
  617.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructRustBuffer.UniffiByValue,)
  618. }
  619. @Structure.FieldOrder("callStatus")
  620. internal open class UniffiForeignFutureStructVoid(
  621.     @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  622. ) : Structure() {
  623.     class UniffiByValue(
  624.         `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(),
  625.     ): UniffiForeignFutureStructVoid(`callStatus`,), Structure.ByValue
  626.  
  627.    internal fun uniffiSetValue(other: UniffiForeignFutureStructVoid) {
  628.         `callStatus` = other.`callStatus`
  629.     }
  630.  
  631. }
  632. internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback {
  633.     fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructVoid.UniffiByValue,)
  634. }
  635.  
  636.  
  637.  
  638.  
  639.  
  640.  
  641.  
  642.  
  643.  
  644.  
  645.  
  646.  
  647.  
  648.  
  649.  
  650.  
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.  
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.  
  665.  
  666.  
  667.  
  668.  
  669.  
  670.  
  671.  
  672.  
  673.  
  674.  
  675.  
  676.  
  677.  
  678.  
  679.  
  680.  
  681.  
  682.  
  683.  
  684.  
  685.  
  686.  
  687.  
  688.  
  689.  
  690.  
  691.  
  692.  
  693.  
  694.  
  695. // A JNA Library to expose the extern-C FFI definitions.
  696. // This is an implementation detail which will be called internally by the public API.
  697.  
  698. internal interface UniffiLib : Library {
  699.     companion object {
  700.         internal val INSTANCE: UniffiLib by lazy {
  701.             loadIndirect<UniffiLib>(componentName = "sample")
  702.             .also { lib: UniffiLib ->
  703.                 uniffiCheckContractApiVersion(lib)
  704.                 uniffiCheckApiChecksums(lib)
  705.                 }
  706.         }
  707.        
  708.     }
  709.  
  710.     fun uniffi_sample_fn_func_expensive_calculation(`intensity`: Long,uniffi_out_err: UniffiRustCallStatus,
  711.     ): Long
  712.     fun ffi_sample_rustbuffer_alloc(`size`: Long,uniffi_out_err: UniffiRustCallStatus,
  713.     ): RustBuffer.ByValue
  714.     fun ffi_sample_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,uniffi_out_err: UniffiRustCallStatus,
  715.     ): RustBuffer.ByValue
  716.     fun ffi_sample_rustbuffer_free(`buf`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
  717.     ): Unit
  718.     fun ffi_sample_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Long,uniffi_out_err: UniffiRustCallStatus,
  719.     ): RustBuffer.ByValue
  720.     fun ffi_sample_rust_future_poll_u8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  721.     ): Unit
  722.     fun ffi_sample_rust_future_cancel_u8(`handle`: Long,
  723.     ): Unit
  724.     fun ffi_sample_rust_future_free_u8(`handle`: Long,
  725.     ): Unit
  726.     fun ffi_sample_rust_future_complete_u8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  727.     ): Byte
  728.     fun ffi_sample_rust_future_poll_i8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  729.     ): Unit
  730.     fun ffi_sample_rust_future_cancel_i8(`handle`: Long,
  731.     ): Unit
  732.     fun ffi_sample_rust_future_free_i8(`handle`: Long,
  733.     ): Unit
  734.     fun ffi_sample_rust_future_complete_i8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  735.     ): Byte
  736.     fun ffi_sample_rust_future_poll_u16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  737.     ): Unit
  738.     fun ffi_sample_rust_future_cancel_u16(`handle`: Long,
  739.     ): Unit
  740.     fun ffi_sample_rust_future_free_u16(`handle`: Long,
  741.     ): Unit
  742.     fun ffi_sample_rust_future_complete_u16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  743.     ): Short
  744.     fun ffi_sample_rust_future_poll_i16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  745.     ): Unit
  746.     fun ffi_sample_rust_future_cancel_i16(`handle`: Long,
  747.     ): Unit
  748.     fun ffi_sample_rust_future_free_i16(`handle`: Long,
  749.     ): Unit
  750.     fun ffi_sample_rust_future_complete_i16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  751.     ): Short
  752.     fun ffi_sample_rust_future_poll_u32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  753.     ): Unit
  754.     fun ffi_sample_rust_future_cancel_u32(`handle`: Long,
  755.     ): Unit
  756.     fun ffi_sample_rust_future_free_u32(`handle`: Long,
  757.     ): Unit
  758.     fun ffi_sample_rust_future_complete_u32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  759.     ): Int
  760.     fun ffi_sample_rust_future_poll_i32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  761.     ): Unit
  762.     fun ffi_sample_rust_future_cancel_i32(`handle`: Long,
  763.     ): Unit
  764.     fun ffi_sample_rust_future_free_i32(`handle`: Long,
  765.     ): Unit
  766.     fun ffi_sample_rust_future_complete_i32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  767.     ): Int
  768.     fun ffi_sample_rust_future_poll_u64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  769.     ): Unit
  770.     fun ffi_sample_rust_future_cancel_u64(`handle`: Long,
  771.     ): Unit
  772.     fun ffi_sample_rust_future_free_u64(`handle`: Long,
  773.     ): Unit
  774.     fun ffi_sample_rust_future_complete_u64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  775.     ): Long
  776.     fun ffi_sample_rust_future_poll_i64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  777.     ): Unit
  778.     fun ffi_sample_rust_future_cancel_i64(`handle`: Long,
  779.     ): Unit
  780.     fun ffi_sample_rust_future_free_i64(`handle`: Long,
  781.     ): Unit
  782.     fun ffi_sample_rust_future_complete_i64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  783.     ): Long
  784.     fun ffi_sample_rust_future_poll_f32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  785.     ): Unit
  786.     fun ffi_sample_rust_future_cancel_f32(`handle`: Long,
  787.     ): Unit
  788.     fun ffi_sample_rust_future_free_f32(`handle`: Long,
  789.     ): Unit
  790.     fun ffi_sample_rust_future_complete_f32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  791.     ): Float
  792.     fun ffi_sample_rust_future_poll_f64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  793.     ): Unit
  794.     fun ffi_sample_rust_future_cancel_f64(`handle`: Long,
  795.     ): Unit
  796.     fun ffi_sample_rust_future_free_f64(`handle`: Long,
  797.     ): Unit
  798.     fun ffi_sample_rust_future_complete_f64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  799.     ): Double
  800.     fun ffi_sample_rust_future_poll_pointer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  801.     ): Unit
  802.     fun ffi_sample_rust_future_cancel_pointer(`handle`: Long,
  803.     ): Unit
  804.     fun ffi_sample_rust_future_free_pointer(`handle`: Long,
  805.     ): Unit
  806.     fun ffi_sample_rust_future_complete_pointer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  807.     ): Pointer
  808.     fun ffi_sample_rust_future_poll_rust_buffer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  809.     ): Unit
  810.     fun ffi_sample_rust_future_cancel_rust_buffer(`handle`: Long,
  811.     ): Unit
  812.     fun ffi_sample_rust_future_free_rust_buffer(`handle`: Long,
  813.     ): Unit
  814.     fun ffi_sample_rust_future_complete_rust_buffer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  815.     ): RustBuffer.ByValue
  816.     fun ffi_sample_rust_future_poll_void(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long,
  817.     ): Unit
  818.     fun ffi_sample_rust_future_cancel_void(`handle`: Long,
  819.     ): Unit
  820.     fun ffi_sample_rust_future_free_void(`handle`: Long,
  821.     ): Unit
  822.     fun ffi_sample_rust_future_complete_void(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
  823.     ): Unit
  824.     fun uniffi_sample_checksum_func_expensive_calculation(
  825.     ): Short
  826.     fun ffi_sample_uniffi_contract_version(
  827.     ): Int
  828.    
  829. }
  830.  
  831. private fun uniffiCheckContractApiVersion(lib: UniffiLib) {
  832.     // Get the bindings contract version from our ComponentInterface
  833.     val bindings_contract_version = 26
  834.     // Get the scaffolding contract version by calling the into the dylib
  835.     val scaffolding_contract_version = lib.ffi_sample_uniffi_contract_version()
  836.     if (bindings_contract_version != scaffolding_contract_version) {
  837.         throw RuntimeException("UniFFI contract version mismatch: try cleaning and rebuilding your project")
  838.     }
  839. }
  840.  
  841. @Suppress("UNUSED_PARAMETER")
  842. private fun uniffiCheckApiChecksums(lib: UniffiLib) {
  843.     if (lib.uniffi_sample_checksum_func_expensive_calculation() != 18134.toShort()) {
  844.         throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
  845.     }
  846. }
  847.  
  848. // Async support
  849.  
  850. // Public interface members begin here.
  851.  
  852.  
  853. // Interface implemented by anything that can contain an object reference.
  854. //
  855. // Such types expose a `destroy()` method that must be called to cleanly
  856. // dispose of the contained objects. Failure to call this method may result
  857. // in memory leaks.
  858. //
  859. // The easiest way to ensure this method is called is to use the `.use`
  860. // helper method to execute a block and destroy the object at the end.
  861. interface Disposable {
  862.     fun destroy()
  863.     companion object {
  864.         fun destroy(vararg args: Any?) {
  865.             args.filterIsInstance<Disposable>()
  866.                 .forEach(Disposable::destroy)
  867.         }
  868.     }
  869. }
  870.  
  871. inline fun <T : Disposable?, R> T.use(block: (T) -> R) =
  872.     try {
  873.         block(this)
  874.     } finally {
  875.         try {
  876.             // N.B. our implementation is on the nullable type `Disposable?`.
  877.             this?.destroy()
  878.         } catch (e: Throwable) {
  879.             // swallow
  880.         }
  881.     }
  882.  
  883. /** Used to instantiate an interface without an actual pointer, for fakes in tests, mostly. */
  884. object NoPointer
  885.  
  886. public object FfiConverterULong: FfiConverter<ULong, Long> {
  887.     override fun lift(value: Long): ULong {
  888.         return value.toULong()
  889.     }
  890.  
  891.     override fun read(buf: ByteBuffer): ULong {
  892.         return lift(buf.getLong())
  893.     }
  894.  
  895.     override fun lower(value: ULong): Long {
  896.         return value.toLong()
  897.     }
  898.  
  899.     override fun allocationSize(value: ULong) = 8UL
  900.  
  901.     override fun write(value: ULong, buf: ByteBuffer) {
  902.         buf.putLong(value.toLong())
  903.     }
  904. }
  905.  
  906. public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> {
  907.     // Note: we don't inherit from FfiConverterRustBuffer, because we use a
  908.     // special encoding when lowering/lifting.  We can use `RustBuffer.len` to
  909.     // store our length and avoid writing it out to the buffer.
  910.     override fun lift(value: RustBuffer.ByValue): String {
  911.         try {
  912.             val byteArr = ByteArray(value.len.toInt())
  913.             value.asByteBuffer()!!.get(byteArr)
  914.             return byteArr.toString(Charsets.UTF_8)
  915.         } finally {
  916.             RustBuffer.free(value)
  917.         }
  918.     }
  919.  
  920.     override fun read(buf: ByteBuffer): String {
  921.         val len = buf.getInt()
  922.         val byteArr = ByteArray(len)
  923.         buf.get(byteArr)
  924.         return byteArr.toString(Charsets.UTF_8)
  925.     }
  926.  
  927.     fun toUtf8(value: String): ByteBuffer {
  928.         // Make sure we don't have invalid UTF-16, check for lone surrogates.
  929.         return Charsets.UTF_8.newEncoder().run {
  930.             onMalformedInput(CodingErrorAction.REPORT)
  931.             encode(CharBuffer.wrap(value))
  932.         }
  933.     }
  934.  
  935.     override fun lower(value: String): RustBuffer.ByValue {
  936.         val byteBuf = toUtf8(value)
  937.         // Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us
  938.         // to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`.
  939.         val rbuf = RustBuffer.alloc(byteBuf.limit().toULong())
  940.         rbuf.asByteBuffer()!!.put(byteBuf)
  941.         return rbuf
  942.     }
  943.  
  944.     // We aren't sure exactly how many bytes our string will be once it's UTF-8
  945.     // encoded.  Allocate 3 bytes per UTF-16 code unit which will always be
  946.     // enough.
  947.     override fun allocationSize(value: String): ULong {
  948.         val sizeForLength = 4UL
  949.         val sizeForString = value.length.toULong() * 3UL
  950.         return sizeForLength + sizeForString
  951.     }
  952.  
  953.     override fun write(value: String, buf: ByteBuffer) {
  954.         val byteBuf = toUtf8(value)
  955.         buf.putInt(byteBuf.limit())
  956.         buf.put(byteBuf)
  957.     }
  958. } fun `expensiveCalculation`(`intensity`: kotlin.ULong): kotlin.ULong {
  959.             return FfiConverterULong.lift(
  960.     uniffiRustCall() { _status ->
  961.     UniffiLib.INSTANCE.uniffi_sample_fn_func_expensive_calculation(
  962.         FfiConverterULong.lower(`intensity`),_status)
  963. }
  964.     )
  965.     }
  966.    
  967.  
  968.  
  969.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement