Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3456,3 +3456,23 @@ pub struct Qualifiers {
pub api: f64,
pub kotlin: f64,
}

/// An object named as a class of Kotlin's runtime once was, which keeps its name now the
/// runtime's take a leading `__`.
pub struct Handle {
count: u32,
}

impl Handle {
pub fn new(count: u32) -> Self {
Handle { count }
}

pub fn count(&self) -> u32 {
self.count
}

pub async fn later(count: u32) -> Self {
Handle { count }
}
}
2 changes: 1 addition & 1 deletion ffi/runtime/jni.rs
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ fn caught(env: *mut JNIEnv, what: &str, cache: &OnceLock<usize>, name: &CStr) ->

static FAILED: OnceLock<usize> = OnceLock::new();

/// Raise the error a function returned, encoded in `w`, as the `_Native.Failed` Kotlin turns
/// Raise the error a function returned, encoded in `w`, as the `_Native.__Failed` Kotlin turns
/// into its exception: a call's success path then returns its value with no `byte[]`.
pub fn raise(env: *mut JNIEnv, w: Writer) {
let id = method(env, &FAILED, c"__failed", c"([B)Ljava/lang/Throwable;");
Expand Down
68 changes: 34 additions & 34 deletions ffi/runtime/rt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// objects own, what frees them once collected, and the waker futures park on.

/** Encodes values as the library's JNI glue decodes them: little-endian, field by field. */
class Writer {
class __Writer {
private var b: java.nio.ByteBuffer = java.nio.ByteBuffer.allocate(64).order(java.nio.ByteOrder.LITTLE_ENDIAN)

private fun room(n: Int) {
Expand Down Expand Up @@ -184,19 +184,19 @@ class Writer {
}
}

private var held: java.util.ArrayList<Handle>? = null
private var held: java.util.ArrayList<__Handle>? = null

// What holds Rust's bytes encoded in place, which the GC must not free before [release].
private var kept: java.util.ArrayList<Any?>? = null

/** An object's handle, held until [release], or 0 for none. */
fun handle(v: Handle?) {
fun handle(v: __Handle?) {
if (v == null) {
i64(0L)
return
}
i64(v.hold())
(held ?: java.util.ArrayList<Handle>().also { held = it }).add(v)
(held ?: java.util.ArrayList<__Handle>().also { held = it }).add(v)
}

fun finish(): ByteArray = b.array().copyOf(b.position())
Expand All @@ -208,7 +208,7 @@ class Writer {
}

/** Run [block] with this writer, releasing its handles once it returns. */
inline fun <R> use(block: (Writer) -> R): R {
inline fun <R> use(block: (__Writer) -> R): R {
try {
return block(this)
} finally {
Expand All @@ -218,7 +218,7 @@ class Writer {
}

/** Decodes what the library's JNI glue encodes. */
class Reader(private val b: java.nio.ByteBuffer) {
class __Reader(private val b: java.nio.ByteBuffer) {
constructor(bytes: ByteArray) : this(java.nio.ByteBuffer.wrap(bytes))

init { b.order(java.nio.ByteOrder.LITTLE_ENDIAN) }
Expand Down Expand Up @@ -282,7 +282,7 @@ class Reader(private val b: java.nio.ByteBuffer) {
/** Bytes Rust handed over, copied or lent by their owner, or null for none. */
fun owned(): Bytes? = when (val n = b.getInt()) {
-1 -> null
LENT -> Bytes(Lent(b.getLong()), b.getInt())
LENT -> Bytes(__Lent(b.getLong()), b.getInt())
else -> Bytes(ByteArray(n).also { b.get(it) })
}

Expand Down Expand Up @@ -336,12 +336,12 @@ class Reader(private val b: java.nio.ByteBuffer) {
* reference, which one daemon thread takes off one queue, as every JVM and Android level
* has. Freeing first is the fast path, and [untrack] makes it the only one.
*/
abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference<Any>(owner, QUEUE) {
abstract class __Cleanup(owner: Any?) : java.lang.ref.PhantomReference<Any>(owner, QUEUE) {
// The GC enqueues only a reference still reachable, so each is linked from its stripe's
// head until freed. The stripe is the making thread's, so threads making objects
// at once rarely share a lock, and a free from any thread finds it in [stripe].
private var prev: Cleanup? = null
private var next: Cleanup? = null
private var prev: __Cleanup? = null
private var next: __Cleanup? = null
// Final, so a thread the object reaches unsafely still sees it.
private val stripe = STRIPES[java.lang.Thread.currentThread().hashCode() and (STRIPES.size - 1)]

Expand Down Expand Up @@ -375,15 +375,15 @@ abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference<Any>(owner,
val QUEUE = java.lang.ref.ReferenceQueue<Any>()
/** One lock and list of the tracked. */
class Stripe {
@JvmField var head: Cleanup? = null
@JvmField var head: __Cleanup? = null
}

// A power of two, past the cores a phone or most servers have.
val STRIPES = Array(64) { Stripe() }

init {
val thread = java.lang.Thread({
while (true) (QUEUE.remove() as Cleanup).collected()
while (true) (QUEUE.remove() as __Cleanup).collected()
}, "rust2-ffi cleaner")
thread.isDaemon = true
thread.start()
Expand All @@ -396,8 +396,8 @@ abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference<Any>(owner,
* only once no call does, and a call after [close] throws. An owned one is closed once
* the GC collects [owner], if nothing closed it.
*/
class Handle(owner: Any, internal val raw: Long, private val free: Drop?, private val type: String) :
Cleanup(if (free == null) null else owner) {
class __Handle(owner: Any, internal val raw: Long, private val free: __Drop?, private val type: String) :
__Cleanup(if (free == null) null else owner) {
// The holds, one for the owner until closed and one per call, shifted past a bit set
// once closed: one word, so a handle allocates nothing beside itself.
@Volatile @JvmField internal var state = HELD
Expand Down Expand Up @@ -454,22 +454,22 @@ class Handle(owner: Any, internal val raw: Long, private val free: Drop?, privat
private companion object {
const val CLOSED = 1L
const val HELD = 2L
val STATE: java.util.concurrent.atomic.AtomicLongFieldUpdater<Handle> =
java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater(Handle::class.java, "state")
val STATE: java.util.concurrent.atomic.AtomicLongFieldUpdater<__Handle> =
java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater(__Handle::class.java, "state")
}
}

/** A waker Rust returned: [wake] wakes it through Rust until [close], or the GC, drops it. */
class Returned(raw: Long) : Waker, AutoCloseable {
private val handle = Handle(this, raw, Drop { __waker_drop(it) }, "Waker")
class __Returned(raw: Long) : Waker, AutoCloseable {
private val handle = __Handle(this, raw, __Drop { __waker_drop(it) }, "Waker")

override fun wake() = handle.hold { __waker_wake(it) }

override fun close() = handle.close()
}

/** Frees a raw handle: a `fun interface`, so the handle crosses unboxed. */
fun interface Drop {
fun interface __Drop {
fun drop(raw: Long)
}

Expand All @@ -479,13 +479,13 @@ fun interface Drop {
* returns: a fence on every JVM and Android level, where `Reference.reachabilityFence`
* needs API 28.
*/
class Lent(internal val owner: Long) {
class __Lent(internal val owner: Long) {
init {
Free(this, owner)
__Free(this, owner)
}
}

private class Free(lent: Lent, private val owner: Long) : Cleanup(lent) {
private class __Free(lent: __Lent, private val owner: Long) : __Cleanup(lent) {
init {
track()
}
Expand All @@ -509,18 +509,18 @@ const val TEXT = -4
fun owned(given: Any?): Bytes? = when (given) {
null -> null
is ByteArray -> Bytes(given)
else -> (given as kotlin.LongArray).let { Bytes(Lent(it[0]), it[1].toInt()) }
else -> (given as kotlin.LongArray).let { Bytes(__Lent(it[0]), it[1].toInt()) }
}

/** Run [block] with the raw handle of [handle], or 0 for none, held until it returns. */
inline fun <R> hold(handle: Handle?, block: (Long) -> R): R = when (handle) {
inline fun <R> hold(handle: __Handle?, block: (Long) -> R): R = when (handle) {
null -> block(0L)
else -> handle.hold(block)
}

/** A waker a future parks on, which latches a wake that lands before it parks. */
// The atomic itself, so a call allocates one object for it.
class Signal : java.util.concurrent.atomic.AtomicReference<Any?>(null), Waker {
class __Signal : java.util.concurrent.atomic.AtomicReference<Any?>(null), Waker {
override fun wake() {
val parked = getAndSet(WOKEN)
if (parked !is kotlinx.coroutines.CancellableContinuation<*>) return
Expand Down Expand Up @@ -561,7 +561,7 @@ class Signal : java.util.concurrent.atomic.AtomicReference<Any?>(null), Waker {
* or by Rust, it ends unfinished: Rust never sees it done, so a call the caller cancelled
* reports the caller's cancel.
*/
class Pollable(
class __Pollable(
private val body: suspend () -> Unit,
private val context: kotlin.coroutines.CoroutineContext,
) : AutoCloseable {
Expand Down Expand Up @@ -598,7 +598,7 @@ class Pollable(
return false
}

/** [context] without its job, on a dispatcher that defers, as [Signal] resumes on. */
/** [context] without its job, on a dispatcher that defers, as [__Signal] resumes on. */
private fun dispatched(): kotlin.coroutines.CoroutineContext {
val bare = context.minusKey(kotlinx.coroutines.Job)
val dispatcher = bare[kotlin.coroutines.ContinuationInterceptor] as? kotlinx.coroutines.CoroutineDispatcher
Expand Down Expand Up @@ -651,10 +651,10 @@ class Pollable(
}

/** A completed native future, including one whose value is null. */
class Ready(val value: Any?)
class __Ready(val value: Any?)

/** A native future still waiting on its waker node. */
class Pending(val raw: Long, val node: Long)
class __Pending(val raw: Long, val node: Long)

/**
* Await the future the call that returned [first] made and polled once with [signal]:
Expand All @@ -663,20 +663,20 @@ class Pending(val raw: Long, val node: Long)
*/
suspend fun await(
first: Any?,
signal: Signal,
signal: __Signal,
poll: (Long, Long) -> Any?,
free: (Long) -> Unit,
): Any? {
if (first is Ready) return first.value
val pending = first as Pending
if (first is __Ready) return first.value
val pending = first as __Pending
val raw = pending.raw
val node = pending.node
try {
while (true) {
signal.park()
signal.reset()
val done = poll(raw, node)
if (done != null) return (done as Ready).value
if (done != null) return (done as __Ready).value
}
} finally {
free(raw)
Expand All @@ -688,7 +688,7 @@ suspend fun await(
* Equality as Rust's `==` has it, apart from the exported functions, which a nested object's
* members never overload.
*/
object Eq {
object __Eq {
/**
* Whether [a] and [b] are equal as Rust's `==` compares them: primitive arrays, lists, and
* tuples by their contents, and floats by IEEE `==`, so NaN equals nothing and -0.0 equals
Expand Down
Loading