1 // This is a helper for safely working with byte buffers returned from the Rust code.
2 // A rust-owned buffer is represented by its capacity, its current length, and a
3 // pointer to the underlying data.
5 @Structure.FieldOrder("capacity", "len", "data")
6 open class RustBuffer : Structure() {
7 @JvmField var capacity: Int = 0
8 @JvmField var len: Int = 0
9 @JvmField var data: Pointer? = null
11 class ByValue: RustBuffer(), Structure.ByValue
12 class ByReference: RustBuffer(), Structure.ByReference
15 internal fun alloc(size: Int = 0) = rustCall() { status ->
16 _UniFFILib.INSTANCE.{{ ci.ffi_rustbuffer_alloc().name() }}(size, status)
19 throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})")
23 internal fun create(capacity: Int, len: Int, data: Pointer?): RustBuffer.ByValue {
24 var buf = RustBuffer.ByValue()
25 buf.capacity = capacity
31 internal fun free(buf: RustBuffer.ByValue) = rustCall() { status ->
32 _UniFFILib.INSTANCE.{{ ci.ffi_rustbuffer_free().name() }}(buf, status)
36 @Suppress("TooGenericExceptionThrown")
38 this.data?.getByteBuffer(0, this.len.toLong())?.also {
39 it.order(ByteOrder.BIG_ENDIAN)
44 * The equivalent of the `*mut RustBuffer` type.
45 * Required for callbacks taking in an out pointer.
47 * Size is the sum of all values in the struct.
49 class RustBufferByReference : ByReference(16) {
51 * Set the pointed-to `RustBuffer` to the given value.
53 fun setValue(value: RustBuffer.ByValue) {
54 // NOTE: The offsets are as they are in the C-like struct.
55 val pointer = getPointer()
56 pointer.setInt(0, value.capacity)
57 pointer.setInt(4, value.len)
58 pointer.setPointer(8, value.data)
62 * Get a `RustBuffer.ByValue` from this reference.
64 fun getValue(): RustBuffer.ByValue {
65 val pointer = getPointer()
66 val value = RustBuffer.ByValue()
67 value.writeField("capacity", pointer.getInt(0))
68 value.writeField("len", pointer.getInt(4))
69 value.writeField("data", pointer.getPointer(8))
75 // This is a helper for safely passing byte references into the rust code.
76 // It's not actually used at the moment, because there aren't many things that you
77 // can take a direct pointer to in the JVM, and if we're going to copy something
78 // then we might as well copy it into a `RustBuffer`. But it's here for API
81 @Structure.FieldOrder("len", "data")
82 open class ForeignBytes : Structure() {
83 @JvmField var len: Int = 0
84 @JvmField var data: Pointer? = null
86 class ByValue : ForeignBytes(), Structure.ByValue