diff --git a/bench/ffi/README.md b/bench/ffi/README.md index f450b15c0..198622533 100644 --- a/bench/ffi/README.md +++ b/bench/ffi/README.md @@ -454,7 +454,7 @@ measure them at the load beside them. ### Copy values A `Copy` type with private fields, such as `Timestamp`, crosses by value: a struct of its -bytes in C, C++, Swift, Go, and Dart, a class over a `LongArray` in Kotlin (a word value +bytes in C, C++, Swift, Go, and Dart, a class of a `Long` per word in Kotlin (a word value class when it fits one), and a class of the runtime's `Value` holding its bytes in Python. Measured 2026-11-13 at rust2 `7766768f`, moq `ffcb7cd9`, on an AMD Ryzen 9 9950X (32 threads), Linux, at a load average of 13 to 15, the median of 3 rounds, in CPU time: @@ -466,8 +466,15 @@ Linux, at a load average of 13 to 15, the median of 3 rounds, in CPU time: | stamped minus write | 0 | 3 | 1 | 33 | 45 | 150 (35 wall) | 160 | C, C++, and Swift pay nothing for the timestamp; Go and Dart pay about their getter's call, -the `from_micros` itself. Kotlin's 35 ns wall is its call, and its CPU column adds the -collector's work on each `LongArray`. Python's is a call and a new object. The handle's cost +the `from_micros` itself. Kotlin's 35 ns wall was its call, and its CPU column adds the +collector's work on each `LongArray`. Since its value is a class of a `Long` per word, and a +`Result` of one returns its words through the thread's slots rather than encoded, the +stamped write costs Kotlin 30 ns of wall time over the write, against 270 on main's build: +measured 2026-11-14 at rust2 `2ec35316`, moq `ffcb7cd9`, on the same host, interleaved over 7 +rounds at a load average of 6 to 17, the medians of each round's difference. Its CPU time, +which counts the JIT's and collector's threads, ranged from 30 to 300 ns at that load. +The thread allocates 32 B a stamped frame over the write, the `Timestamp` itself, which +`write_frame` keeps from the JIT's escape analysis, against 112 on main's. Python's is a call and a new object. The handle's cost in the tables above came from another load, so Python's was also measured against main's build on the same host, interleaved over 5 rounds at a load of 10 to 12: stamped minus write fell from 205 ns to 166, and the stamped write from 441 to 391. diff --git a/ffi/README.md b/ffi/README.md index bbb9a0fb2..cd92ceee2 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -522,8 +522,10 @@ kotlinx-coroutines. Each value crosses JNI as a scalar, a handle as a `Long`, by in as a `ByteArray`, bytes returned as their owner, a block of numbers as its primitive array, and anything else encoded into a `ByteArray` as its C struct holds it. A record a call takes or returns directly, or in an `Option` returned, crosses as its scalars, a -nested record's included, as JNI parameters in and through a `LongArray` each thread keeps -out, with only its other fields encoded. +nested record's included, and an opaque value as its 64-bit words, as JNI parameters in +and through a `LongArray` each thread keeps out, with only a record's other fields encoded; +an opaque value of one word returns as that `Long`. Past the 255 slots a JVM method takes, +the rest cross encoded. - **Names** are in a package of the prefix: types in PascalCase without it, members in camelCase without their type's name (`moq.TrackProducer.appendGroup`). Pascal case @@ -556,8 +558,8 @@ out, with only its other fields encoded. value** is a class with an internal constructor, so only Rust makes one: of no more than 8 bytes on every target, with no padding, fields of integers, `bool`s, and `char`s alone, nested or not, and a derived or std `PartialEq`, a value class over a `Long`, compared by its bits, which - allocates nothing unless Kotlin boxes it, as in a `List` or a nullable; otherwise one over - a `LongArray`, whose `==` is Rust's, and whose `hashCode` is 0, since none Kotlin + allocates nothing unless Kotlin boxes it, as in a `List` or a nullable; otherwise a class of a `Long` for each 64-bit word of its bytes, which allocates + nothing where the JIT sees it does not escape, whose `==` is Rust's, and whose `hashCode` is 0, since none Kotlin computes agrees with it. Either is shared by reference, so it never changes: a `&mut self` method, a field's setter included, returns the value as the call left it, `x = x.add(o)`, and beside Rust's own return, a `Pair`, or each element of its tuple, diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index e4d56cc8d..cfa89d32e 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1302,6 +1302,19 @@ impl Moment { } } +/// `ticks` of `rate` a second, failing at a rate of zero: a value past a word in a `Result`. +pub fn moment_at(ticks: u64, rate: u64) -> Result { + Moment::new(ticks, rate).ok_or_else(|| "a rate of zero".to_string()) +} + +/// The stamp `millis` from zero, failing at zero: a value of a word in a `Result`. +pub fn stamp_at(millis: u64) -> Result { + match millis { + 0 => Err("zero".to_string()), + millis => Ok(Stamp::from_millis(millis)), + } +} + /// The moment `shift` returns for `moment`, which C copies in and out. pub fn shifted(moment: Moment, shift: impl Fn(Moment) -> Moment) -> Moment { shift(moment) @@ -1325,8 +1338,9 @@ impl Gap { } } -/// A value named as Kotlin's `LongArray`, which holds a value's words, with a method named -/// as C++'s member holding its bytes: each generator keeps its own apart. +/// A value named as Kotlin's `LongArray`, which holds a returned value's words, with methods named +/// as C++'s member holding its bytes and Kotlin's `also`, which makes a value past a word: each +/// generator keeps its own apart. #[derive(Clone, Copy, Debug, PartialEq)] pub struct LongArray { words: [u64; 2], @@ -1340,8 +1354,84 @@ impl LongArray { pub fn c_(&self) -> u64 { self.words[0].wrapping_add(self.words[1]) } + + /// Calls `f` with its low word. + pub fn also(&self, f: impl Fn(u64)) { + f(self.words[0]) + } +} + +/// A type named as the annotation Kotlin's fields take, which the binding qualifies. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct JvmField { + pub n: u32, +} + +/// A type named as the annotation Kotlin's static methods take, which the binding qualifies. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct JvmStatic { + pub n: u32, +} + +/// A type named as the annotation Kotlin opts in to an API with, which the binding qualifies. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OptIn { + pub n: u32, +} + +/// The sum of a `JvmField`, a `JvmStatic`, and an `OptIn`. +pub fn jvm_sum(field: JvmField, method: JvmStatic, opt: OptIn) -> u32 { + field.n.wrapping_add(method.n).wrapping_add(opt.n) +} + +/// A value of 128 words, past what a JVM method's 255 slots hold as `long`s: Kotlin makes +/// one with no constructor of a parameter each, and passes one encoded. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Wide { + words: [u64; 128], +} + +impl Wide { + /// Words `seed`, `seed + 1`, and on, wrapping. + pub fn new(seed: u64) -> Self { + Self { + words: std::array::from_fn(|k| seed.wrapping_add(k as u64)), + } + } + + pub fn sum(&self) -> u64 { + self.words.iter().fold(0, |a, w| a.wrapping_add(*w)) + } } +/// A moment and a count: a record holding a value past a word, flattened as its words. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clocked { + pub at: Moment, + pub count: u32, +} + +/// `clocked`, its moment `ticks` later and its count one more. +pub fn clocked_after(clocked: Clocked, ticks: u64) -> Clocked { + Clocked { + at: clocked.at.after(ticks), + count: clocked.count + 1, + } +} + +/// Declares `crammed`, whose numbers take 248 of a JVM method's 255 slots, so its first +/// moment crosses as its words and its second, past the limit, encoded. +macro_rules! crammed { + ($($n:ident)*) => { + /// Both moments' millis and every number, summed. + pub fn crammed(a: Moment, b: Moment, $($n: u64),*) -> u64 { + a.millis().wrapping_add(b.millis())$(.wrapping_add($n))* + } + }; +} + +crammed!(n0 n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 n16 n17 n18 n19 n20 n21 n22 n23 n24 n25 n26 n27 n28 n29 n30 n31 n32 n33 n34 n35 n36 n37 n38 n39 n40 n41 n42 n43 n44 n45 n46 n47 n48 n49 n50 n51 n52 n53 n54 n55 n56 n57 n58 n59 n60 n61 n62 n63 n64 n65 n66 n67 n68 n69 n70 n71 n72 n73 n74 n75 n76 n77 n78 n79 n80 n81 n82 n83 n84 n85 n86 n87 n88 n89 n90 n91 n92 n93 n94 n95 n96 n97 n98 n99 n100 n101 n102 n103 n104 n105 n106 n107 n108 n109 n110 n111 n112 n113 n114 n115 n116 n117 n118 n119 n120 n121 n122 n123); + /// A `Copy` type whose `None` leaves its payload's bytes uninitialized, so no padding table /// covers it: a handle, rather than a value. #[derive(Clone, Copy, Debug)] diff --git a/ffi/runtime/jni.rs b/ffi/runtime/jni.rs index 963c925e3..f94c172c7 100644 --- a/ffi/runtime/jni.rs +++ b/ffi/runtime/jni.rs @@ -1014,62 +1014,26 @@ impl Writer { } } -/// An opaque value's C struct from the `long` Kotlin holds it in: its bytes, at the word's -/// lowest addresses, as [`to_word`] put them. -pub fn from_word(word: jlong) -> T { - const { assert!(size_of::() <= size_of::()) }; +/// An opaque value's C struct from the `W` `long`s Kotlin holds it in: its bytes, in the +/// words' order, as [`to_words`] put them. +pub fn from_words(words: [jlong; W]) -> T { + const { assert!(size_of::() <= W * size_of::()) }; let mut value = std::mem::MaybeUninit::::zeroed(); // SAFETY: `T` is a struct of `MaybeUninit` units, any bytes of which are one. unsafe { - std::ptr::copy_nonoverlapping((&raw const word).cast::(), value.as_mut_ptr().cast::(), size_of::()); - value.assume_init() - } -} - -/// The `long` Kotlin holds an opaque value's C struct in, which has no padding: Kotlin -/// compares two by it. -pub fn to_word(value: T) -> jlong { - const { assert!(size_of::() <= size_of::()) }; - let mut word: jlong = 0; - // SAFETY: every byte of a value with no padding is initialized, and the rest are zero. - unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::(), (&raw mut word).cast::(), size_of::()) }; - word -} - -/// An opaque value's C struct from the `W` words of the `long[]` Kotlin holds it in. -/// -/// # Safety -/// `array` is a live `long[]`. -pub unsafe fn from_words(env: *mut JNIEnv, array: jlongArray) -> T { - const { assert!(size_of::() <= W * size_of::()) }; - let mut words = [std::mem::MaybeUninit::::zeroed(); W]; - // SAFETY: `array` is live, and `T` is a struct of `MaybeUninit` units. - unsafe { - if array.is_null() || ((**env).v1_2.GetArrayLength)(env, array) != W as jsize { - fail(env, "jni", "an opaque value's words are not its own"); - } - ((**env).v1_2.GetLongArrayRegion)(env, array, 0, W as jsize, words.as_mut_ptr().cast()); - let mut value = std::mem::MaybeUninit::::zeroed(); std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), value.as_mut_ptr().cast::(), size_of::()); value.assume_init() } } -/// A new `long[]` of the `W` words an opaque value's C struct is held in: its bytes, then -/// zeros. -pub fn to_words(env: *mut JNIEnv, value: T) -> jlongArray { +/// The `W` `long`s Kotlin holds an opaque value's C struct in: its bytes, then zeros. +/// Kotlin compares a value class of one by it. +pub fn to_words(value: T) -> [jlong; W] { const { assert!(size_of::() <= W * size_of::()) }; - let mut words = [std::mem::MaybeUninit::::zeroed(); W]; - // SAFETY: `env` is this thread's; JNI copies the words as bytes. - unsafe { - std::ptr::copy_nonoverlapping((&raw const value).cast::(), words.as_mut_ptr().cast::(), size_of::()); - let array = ((**env).v1_2.NewLongArray)(env, W as jsize); - if array.is_null() { - fail(env, "jni", "a long[] is out of memory"); - } - ((**env).v1_2.SetLongArrayRegion)(env, array, 0, W as jsize, words.as_ptr().cast()); - array - } + let mut words = [0; W]; + // SAFETY: an opaque value's C struct initializes every byte, as the glue makes it. + unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::(), words.as_mut_ptr().cast::(), size_of::()) }; + words } /// An opaque value's C struct as it crosses encoded: the `W` words Kotlin holds it in, diff --git a/ffi/runtime/rt.kt b/ffi/runtime/rt.kt index 872724bda..3e7705be9 100644 --- a/ffi/runtime/rt.kt +++ b/ffi/runtime/rt.kt @@ -375,7 +375,7 @@ abstract class __Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owne val QUEUE = java.lang.ref.ReferenceQueue() /** One lock and list of the tracked. */ class Stripe { - @JvmField var head: __Cleanup? = null + @kotlin.jvm.JvmField var head: __Cleanup? = null } // A power of two, past the cores a phone or most servers have. @@ -407,7 +407,7 @@ class __Handle( ) : __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 + @kotlin.concurrent.Volatile @kotlin.jvm.JvmField internal var state = HELD init { if (free != null) track() @@ -563,7 +563,7 @@ class __Signal : java.util.concurrent.atomic.AtomicReference(null), Waker override fun wake() { val parked = getAndSet(WOKEN) if (parked !is kotlinx.coroutines.CancellableContinuation<*>) return - @Suppress("UNCHECKED_CAST") + @kotlin.Suppress("UNCHECKED_CAST") val c = parked as kotlinx.coroutines.CancellableContinuation // Never resumed in place, since the next poll would run inside Rust's wake, which may // hold a lock that poll takes: a dispatcher that would resume here is made to defer, @@ -614,7 +614,7 @@ class __Pollable( // The caller's job reaches it as it starts cancelling, not once its children finish, // which only the internal overload of invokeOnCompletion tells. - @OptIn(kotlinx.coroutines.InternalCoroutinesApi::class) + @kotlin.OptIn(kotlinx.coroutines.InternalCoroutinesApi::class) fun poll(given: Long): Boolean { val old: Long synchronized(this) { diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 3596102e3..1018ca389 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -17,8 +17,9 @@ //! bytes returned as their owner, which a `Bytes` reads through a call each, or encoded //! into native scratch memory consumed synchronously by a kept Kotlin factory. Composite //! results cross JNI as their constructed Kotlin value, without a transport `byte[]`. -//! A record passed or returned directly crosses as its scalars instead, parameters in and -//! a thread's `long[]` slots out, with only its other fields encoded. +//! A record passed or returned directly crosses as its scalars instead, and an opaque +//! value as its words, parameters in and a thread's `long[]` slots out, with only a +//! record's other fields encoded; an opaque value of one word returns as that `long`. //! An object never closed, and Rust's bytes, are freed once the GC collects them. use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -87,8 +88,8 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result, packages: &str, contract: u64) -> Result 0 { let _ = write!( helpers, - "\t/** This thread's slots a returned record's scalars cross in, read before its next call. */\n\t// A field, not a function, so no exported function's name can clash with it.\n\t@JvmField val __slots = object : java.lang.ThreadLocal() {{\n\t\t// Not `withInitial`, which Android lacks before API 26.\n\t\toverride fun initialValue() = kotlin.LongArray({n})\n\t}}\n\n", + "\t/** This thread's slots a returned record's scalars cross in, read before its next call. */\n\t// A field, not a function, so no exported function's name can clash with it.\n\t@kotlin.jvm.JvmField val __slots = object : java.lang.ThreadLocal() {{\n\t\t// Not `withInitial`, which Android lacks before API 26.\n\t\toverride fun initialValue() = kotlin.LongArray({n})\n\t}}\n\n", n = g.slots ); } @@ -130,13 +131,13 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result Gen<'a> { _ => wrap(e), } } - Ty::Struct(name) if opaque_of(self.abi, c).is_some() => format!("{}({e})", self.qualified(name)), + Ty::Struct(name) + if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => + { + let class = self.qualified(name); + self.made(&class, &opaque, &[e.to_string()]) + } Ty::Buf => match (decode(ty), matches!(ty.base(), Type::Option(_)), lent) { (Some(decode), true, _) => format!("{e}?.{decode}"), (Some(decode), false, _) => format!("{e}!!.{decode}"), @@ -899,7 +909,12 @@ impl<'a> Gen<'a> { match c { Ty::Int(int) => to_signed(*int, e), Ty::Buf => format!("{e}.encodeToByteArray()"), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) => format!("{e}.{}", holder(&opaque)), + Ty::Struct(_) + if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => + { + format!("{e}.{}", holders(&opaque)[0]) + } Ty::Struct(_) => { let w = self.fresh("w"); let write = self.write_value(ty, &w, e); @@ -1012,20 +1027,12 @@ impl<'a> Gen<'a> { "crate::{name} {{ vtable: &VTABLE_{name}, data: rt::global(env, {p}) }}" )); } - // An opaque value crosses as the word or words Kotlin holds it in. - Ty::Struct(_) | Ty::In(_) if let Some(opaque) = opaque_of(abi, c) => { - arg.exprs.push(format!("{e}.{}", holder(&opaque))); - arg.rust_pre.push(format!("let a{p} = {};", from_kotlin(&opaque, &p))); - arg.rust_args.push(match c { - Ty::In(_) => format!("&a{p}"), - _ => format!("a{p}"), - }); - } - // A record crosses as its scalars, and its other fields encoded into one `byte[]`. - // Only while the call's JVM parameters stay within the 255 slots a method takes. + // A record crosses as its scalars, and its other fields encoded into one `byte[]`; + // an opaque value as the words Kotlin holds it in. Only while the call's JVM + // parameters stay within the 255 slots a method takes, which a word always does. Ty::Struct(_) | Ty::In(_) if let Type::Record(i) = ty.base() - && let Some(left) = self.room.checked_sub(weight(abi, *i).saturating_sub(c_slots(abi, c))) => + && let Some(left) = self.room.checked_sub(weight(abi, *i).saturating_sub(c_slots(c))) => { self.room = left; arg.jni.clear(); @@ -1297,8 +1304,11 @@ impl<'a> Gen<'a> { Type::Record(i) => self.abi.api.records[*i].opaque, _ => None, }; + // Whether `n` opaque values cross as their words within the 255 JVM slots a method + // takes, or else encoded. + let fits = |n: u64| opaque.is_some_and(|o| 2 * n * o.words() <= 255); // The receiver as the glue takes it: a handle, held for the call, an opaque value's - // word or words, or encoded. + // words, or encoded. let (params, open, arg, rust_self): (Vec<(&str, &str)>, _, _, _) = match (object, opaque) { (true, _) => ( vec![("jlong", "Long")], @@ -1306,16 +1316,16 @@ impl<'a> Gen<'a> { "h".to_string(), "p0 as usize as _".to_string(), ), - (false, Some(opaque)) => { - let (jni, native) = jni_type(self.abi, &Ty::Struct(c.to_string()), ty); + (false, Some(opaque)) if fits(1) => { + let words: Vec = (0..opaque.words()).map(|k| format!("p{k}")).collect(); ( - vec![(jni, native)], + vec![("jlong", "Long"); words.len()], "run {".to_string(), - holder(&opaque).to_string(), - format!("&{}", from_kotlin(&opaque, "p0")), + holders(&opaque).join(", "), + format!("&{}", from_kotlin(&opaque, &words)), ) } - (false, None) => { + (false, _) => { let write = self.write_value(ty, "w", "this"); ( vec![("jbyteArray", "ByteArray"), ("jobjectArray", "kotlin.Array?")], @@ -1374,20 +1384,37 @@ impl<'a> Gen<'a> { "\t/** A new handle to a clone. */\n\tfun clone(): {class} = handle.hold {{ h -> {class}(_Native.{bare}_clone(h)) }}\n" )); } - // An opaque value Kotlin holds in a word compares by it, as a value class does. + // An opaque value Kotlin holds in a word compares by it, as a value class does; any + // other through Rust, passing both values' words, or both encoded. if let Some(opaque) = opaque.filter(|opaque| t.eq && !word(opaque)) { - self.native( - &format!("{bare}_eq"), - &[("jlongArray", "LongArray"), ("jlongArray", "LongArray")], - ("jboolean", "Boolean"), - &format!( - "crate::{c}_eq(&{}, &{})", - from_kotlin(&opaque, "p0"), - from_kotlin(&opaque, "p1") - ), - ); + let holders = holders(&opaque); + let (params, rust, kt) = match fits(2) { + true => { + let words: Vec = (0..2 * holders.len()).map(|k| format!("p{k}")).collect(); + let (a, b) = words.split_at(holders.len()); + let others: Vec = holders.iter().map(|h| format!("other.{h}")).collect(); + ( + vec![("jlong", "Long"); words.len()], + format!( + "crate::{c}_eq(&{}, &{})", + from_kotlin(&opaque, a), + from_kotlin(&opaque, b) + ), + format!("_Native.{bare}_eq({}, {})", holders.join(", "), others.join(", ")), + ) + } + false => { + let (this, other) = (self.write_value(ty, "w", "this"), self.write_value(ty, "w", "other")); + ( + vec![("jbyteArray", "ByteArray"), ("jobjectArray", "kotlin.Array?")], + "{ let b = rt::bytes(env, p0).unwrap_or_default(); let mut r = rt::Reader::new(env, &b, p1); crate::{c}_eq(&r.get(), &r.get()) }".replace("{c}", c), + format!("_Native.__Writer().use {{ w -> {this}; {other}; _Native.{bare}_eq(w.finish(), w.refs()) }}"), + ) + } + }; + self.native(&format!("{bare}_eq"), ¶ms, ("jboolean", "Boolean"), &rust); body.push(format!( - "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {class} && _Native.{bare}_eq(words, other.words)\n\n\t/** One for every value: Rust's `PartialEq` comes with no `Hash`. */\n\toverride fun hashCode(): kotlin.Int = 0\n" + "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {class} && {kt}\n\n\t/** One for every value: Rust's `PartialEq` comes with no `Hash`. */\n\toverride fun hashCode(): kotlin.Int = 0\n" )); } if object && t.eq { @@ -1451,7 +1478,7 @@ impl<'a> Gen<'a> { self.traits(&ty, &c, record.traits, &mut body, &mut statics); let mut members: Vec = fields.iter().map(|(f, _)| format!("val {f}")).collect(); if let Some(opaque) = record.opaque { - members.push(format!("val {}", holder(&opaque))); + members.extend(holders(&opaque).iter().map(|h| format!("val {h}"))); } let owner = Ty::Struct(c.clone()); for method in &record.methods { @@ -1555,22 +1582,33 @@ impl<'a> Gen<'a> { } /// An opaque value's class, `name` in Kotlin and `c` in C, and its codec: a value class - /// over the `Long` it fits in with no padding, or else a class over its words, which - /// compares through Rust's `PartialEq`. Only Rust makes one. + /// over the `Long` it fits in with no padding, or else a class of a `Long` for each of + /// its words, which compares through Rust's `PartialEq`, so one that does not escape + /// allocates nothing. Only Rust makes one. fn opaque(&mut self, c: &str, name: &str, opaque: &Opaque, docs: &str, body: &str) { let words = opaque.words(); - let (head, write, read) = match word(opaque) { + let holders = holders(opaque); + // Set after a constructor of none, as a constructor of a parameter each would pass + // the 255 JVM slots a method takes past 127 words. + let fields: String = holders + .iter() + .map(|h| format!("\t@kotlin.jvm.JvmField internal var {h}: Long = 0L\n")) + .collect(); + let (head, body) = match word(opaque) { true => ( format!("@kotlin.jvm.JvmInline\nvalue class {name} internal constructor(internal val bits: Long)"), - "\tw.i64(v.bits)\n".to_string(), - format!("{name}(r.i64())"), + body.to_string(), ), false => ( - format!("class {name} internal constructor(internal val words: LongArray)"), - "\tfor (word in v.words) w.i64(word)\n".to_string(), - format!("{name}(LongArray({words}) {{ r.i64() }})"), + format!("class {name} internal constructor()"), + match body.is_empty() { + true => format!(" {{\n{fields}}}"), + false => body.replacen(" {\n", &format!(" {{\n{fields}\n"), 1), + }, ), }; + let write: String = holders.iter().map(|h| format!("\tw.i64(v.{h})\n")).collect(); + let read = self.made(name, opaque, &vec!["r.i64()".to_string(); holders.len()]); let _ = write!(self.types, "{docs}{head}{body}\n\n"); let _ = write!( self.top, @@ -1582,6 +1620,23 @@ impl<'a> Gen<'a> { ); } + /// The Kotlin expression making the opaque value of class `class` from the `Long` + /// expressions `words`, evaluated in order. + fn made(&mut self, class: &str, opaque: &Opaque, words: &[String]) -> String { + if word(opaque) { + return format!("{class}({})", words[0]); + } + let v = self.fresh("v"); + let sets: Vec = holders(opaque) + .iter() + .zip(words) + .map(|(h, w)| format!("{v}.{h} = {w}")) + .collect(); + // Through the alias, which no exported member's name takes, as a member `also` would + // win over the extension. + format!("{class}()._also {{ {v} -> {} }}", sets.join("; ")) + } + fn enumeration(&mut self, i: usize) { let abi = self.abi; let e = &abi.api.enums[i]; @@ -1920,10 +1975,12 @@ impl<'a> Gen<'a> { Ty::Enum(_) => ("i", format!("p{k}")), Ty::Handle { .. } => ("j", format!("p{k} as usize as jlong")), Ty::Buf => ("l", format!("unsafe {{ rt::lent(env, p{k}) }}")), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) => match word(&opaque) { - true => ("j", to_kotlin(&opaque, &format!("p{k}"))), - false => ("l", to_kotlin(&opaque, &format!("p{k}"))), - }, + Ty::Struct(_) + if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => + { + ("j", to_kotlin(&opaque, &format!("p{k}"), 0)) + } _ => ( "l", format!("{{ let mut w = rt::Writer::default(); w.put(p{k}); w.array(env) }}"), @@ -1965,8 +2022,14 @@ impl<'a> Gen<'a> { Ty::Char => "ret as u32".to_string(), // A buffer Rust frees, as `buf_copy` makes one. Ty::Buf => "crate::rt::Buf::vec(rt::bytes(env, ret).unwrap_or_default())".to_string(), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, &c_ok) => from_kotlin(&opaque, "ret"), - // Encoded, as an option of an opaque value, which names no array or text to refer to. + Ty::Struct(_) + if let Some(opaque) = opaque_of(self.abi, &c_ok) + && one_word(&opaque) => + { + from_kotlin(&opaque, &["ret".to_string()]) + } + // Encoded, as an option of an opaque value or one past a word, which names no + // array or text to refer to. Ty::Struct(_) => { "rt::Reader::new(env, &rt::bytes(env, ret).unwrap_or_default(), ::std::ptr::null_mut()).get()" .to_string() @@ -2011,7 +2074,7 @@ impl<'a> Gen<'a> { // A closure's function type is erased, so the cast cannot check it. let cast_line = match method { Some(_) => format!("\t\tval o = o as {cast}\n"), - None => format!("\t\t@Suppress(\"UNCHECKED_CAST\")\n\t\tval o = o as {cast}\n"), + None => format!("\t\t@kotlin.Suppress(\"UNCHECKED_CAST\")\n\t\tval o = o as {cast}\n"), }; let body = match finally.is_empty() { true => format!("{cast_line}\t\treturn {lowered}"), @@ -2027,7 +2090,7 @@ impl<'a> Gen<'a> { }; let _ = write!( self.natives, - "\t@JvmStatic private fun {dispatcher}({}){ret_decl} {{\n{body}\n\t}}\n\n", + "\t@kotlin.jvm.JvmStatic private fun {dispatcher}({}){ret_decl} {{\n{body}\n\t}}\n\n", kt_params.join(", ") ); } @@ -2064,7 +2127,7 @@ impl<'a> Gen<'a> { let args: Vec = (0..params.len()).map(|n| format!("p{n}")).collect(); let _ = write!( self.natives, - "\t@JvmStatic fun {bare}({}): {} {{\n\t\tcheck({}uL, \"{}_{bare}\")\n\t\treturn {external}({})\n\t}}\n\n", + "\t@kotlin.jvm.JvmStatic fun {bare}({}): {} {{\n\t\tcheck({}uL, \"{}_{bare}\")\n\t\treturn {external}({})\n\t}}\n\n", kt.join(", "), ret.1, self.on.0 & api.all().0, @@ -2077,7 +2140,7 @@ impl<'a> Gen<'a> { let bare = external.as_str(); let _ = write!( self.natives, - "\t@JvmStatic external fun {bare}({}): {}\n\n", + "\t@kotlin.jvm.JvmStatic external fun {bare}({}): {}\n\n", kt.join(", "), ret.1 ); @@ -2167,7 +2230,7 @@ impl<'a> Gen<'a> { .iter() .any(|p| matches!(&p.ty, Type::Ref(..)) && p.ty.written()); self.room = room( - export.call.params.iter().map(|(_, c)| c_slots(abi, c)).sum(), + export.call.params.iter().map(|(_, c)| c_slots(c)).sum(), export.future.is_some(), written, ); @@ -2319,9 +2382,11 @@ impl<'a> Gen<'a> { let err = function.err.as_ref().map(strip_refs); let exception = err.as_ref().map(|e| self.exception(e)); // A record returned directly crosses as its scalars, set into slots the call takes, - // and its other fields encoded into the `byte[]` it returns. + // and its other fields encoded into the `byte[]` it returns; an opaque value as its + // words, unless it returns its one word itself. let flat = match (&export.future, outs.is_empty()) { - (None, true) if self.room > 0 => returned_record(&ok).filter(|(i, _)| abi.api.records[*i].opaque.is_none()), + (None, true) if self.room > 0 => returned_record(&ok) + .filter(|(i, option)| *option || !abi.api.records[*i].opaque.is_some_and(|o| one_word(&o))), _ => None, }; let flat = flat.map(|(i, option)| { @@ -2400,7 +2465,7 @@ impl<'a> Gen<'a> { }; let _ = write!( self.natives, - "\t@Suppress(\"UNUSED_PARAMETER\")\n\t@JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\t{pending}\n{}\t\treturn __Ready({last})\n\t}}\n\n", + "\t@kotlin.Suppress(\"UNUSED_PARAMETER\")\n\t@kotlin.jvm.JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\t{pending}\n{}\t\treturn __Ready({last})\n\t}}\n\n", lines.iter().map(|l| format!("\t\t{l}\n")).collect::() ); } @@ -2489,7 +2554,7 @@ impl<'a> Gen<'a> { let make = self.tuple_class(elements); let _ = write!( self.natives, - "\t@JvmStatic private fun {factory}({}): Any {{\n\t\t{failure}\n\t\treturn {make}({})\n\t}}\n\n", + "\t@kotlin.jvm.JvmStatic private fun {factory}({}): Any {{\n\t\t{failure}\n\t\treturn {make}({})\n\t}}\n\n", fields.join(", "), lifted.join(", ") ); @@ -2520,12 +2585,25 @@ impl<'a> Gen<'a> { } }; value = format!("({raw}) as {ok_kt}"); - } else if let Some(c_ok) = direct(&outs, &written, &function.ok, function.err.as_ref()) { - // A result of a scalar, a handle, or nothing returns its value directly, raising - // its error as a `_Native.__Failed` Kotlin catches. + } else if let Some(c_ok) = direct(abi, &outs, &written, &function.ok, function.err.as_ref()) + .filter(|c| self.room > 0 || opaque_of(abi, c).is_none_or(|o| one_word(&o))) + { + // A result of a scalar, a handle, an opaque value, or nothing returns its value + // directly, raising its error as a `_Native.__Failed` Kotlin catches; an opaque + // value past a word sets its words into this thread's slots. let err_ty = function.err.as_ref().expect("a direct return is a result's"); - let (jni, native) = jni_type(abi, &c_ok, &ok); - let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); + let words = opaque_of(abi, &c_ok).filter(|o| !one_word(o)); + let (jni, native) = match words { + Some(_) => ("()", "Unit"), + None => jni_type(abi, &c_ok, &ok), + }; + let mut params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); + let a = self.fresh("a"); + if let Some(opaque) = &words { + params.push(("jlongArray", "kotlin.LongArray")); + exprs.push(a.clone()); + self.slots = self.slots.max(opaque.words() as usize); + } let mut ptrs = Vec::new(); let mut decl = Vec::new(); for (name, _) in &outs { @@ -2533,8 +2611,13 @@ impl<'a> Gen<'a> { ptrs.push(format!("o_{name}.as_mut_ptr()")); } let ok_name = &outs[0].0; - let ret = match c_ok { - Ty::Void => String::new(), + let ret = match (&c_ok, &words) { + (Ty::Void, _) => String::new(), + (_, Some(opaque)) => format!( + "let ret = o_{ok_name}.assume_init();\n\t\trt::slots(env, p{}, &rt::to_words::<_, {}>(ret));", + params.len() - 1, + opaque.words() + ), _ => format!( "let ret = o_{ok_name}.assume_init();\n\t\t{}", ret_expr(abi, &c_ok, &ok) @@ -2567,8 +2650,20 @@ impl<'a> Gen<'a> { self.refused_first(&bare, moving) } }; - value = match ok { - Type::Unit => caught, + value = match (&ok, &words) { + (Type::Unit, _) => caught, + (_, Some(opaque)) => { + let words: Vec = (0..opaque.words()).map(|k| format!("{a}[{k}]")).collect(); + let class = match &c_ok { + Ty::Struct(name) => self.qualified(name), + _ => unreachable!("an opaque value is a struct"), + }; + let made = self.made(&class, opaque, &words); + format!( + "_Native.__slots.get()!!.let {{ {a} ->\n{}\n\t{made}\n}}", + indent_by(&caught, 1) + ) + } _ => self.lift(&ok, &c_ok, &format!("({caught})"), false), }; } else if !outs.is_empty() { @@ -2600,7 +2695,7 @@ impl<'a> Gen<'a> { } let _ = write!( self.natives, - "\t@Suppress(\"UNCHECKED_CAST\", \"UNUSED_PARAMETER\")\n\t@JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n{}\t}}\n\n", + "\t@kotlin.Suppress(\"UNCHECKED_CAST\", \"UNUSED_PARAMETER\")\n\t@kotlin.jvm.JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n{}\t}}\n\n", lines.iter().map(|l| format!("\t\t{l}\n")).collect::() ); let mut params = params; @@ -2703,7 +2798,7 @@ impl<'a> Gen<'a> { let read = self.read_value(&ok, "r"); let _ = write!( self.natives, - "\t@Suppress(\"UNUSED_PARAMETER\")\n\t@JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\treturn {read}\n\t}}\n\n" + "\t@kotlin.Suppress(\"UNUSED_PARAMETER\")\n\t@kotlin.jvm.JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\treturn {read}\n\t}}\n\n" ); let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); self.native(&bare, ¶ms, ("jobject", "Any?"), &format!( @@ -2936,8 +3031,9 @@ impl<'a> Gen<'a> { } /// The glue's C value of the record `i` Kotlin passes as `e`: each scalar, nested - /// records' too, a JNI parameter `arg` gains, numbered from `n`, and each other field - /// read from `r`, which Kotlin writes into `w` with `writes`, in field order. + /// records' too, and each word of an opaque value, a JNI parameter `arg` gains, numbered + /// from `n`, and each other field read from `r`, which Kotlin writes into `w` with + /// `writes`, in field order. fn flat_in( &mut self, i: usize, @@ -2947,13 +3043,22 @@ impl<'a> Gen<'a> { r: &str, ) -> String { let abi = self.abi; + if let Some(opaque) = abi.api.records[i].opaque { + let mut words = Vec::new(); + for h in holders(&opaque) { + words.push(format!("p{n}")); + *n += 1; + arg.jni.push("jlong"); + arg.native.push("Long".to_string()); + arg.exprs.push(format!("{e}.{h}")); + } + return from_kotlin(&opaque, &words); + } let mut fields = Vec::new(); for (k, field) in abi.api.records[i].fields.iter().enumerate() { let e = format!("{e}.{}", field_name(&field.name)); let value = match &field.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => { - self.flat_in(*j, &e, (&mut *arg, &mut *n), (w, &mut *writes), r) - } + Type::Record(j) => self.flat_in(*j, &e, (&mut *arg, &mut *n), (w, &mut *writes), r), ty if scalar(abi, ty) => { let p = format!("p{n}"); *n += 1; @@ -2984,7 +3089,8 @@ impl<'a> Gen<'a> { } /// The Kotlin value of the record `i` Rust returned as the C value `v`: each scalar, - /// nested records' too, from the next of the slots `a` the glue sets with `slots`, and + /// nested records' too, and each word of an opaque value, from the next of the slots + /// `a` the glue sets with `slots`, and /// each other field from `r`, which the glue writes with `puts`, in field order. fn flat_out( &mut self, @@ -2994,13 +3100,22 @@ impl<'a> Gen<'a> { (r, puts): (&str, &mut Vec), ) -> String { let abi = self.abi; + let class = self.qualified(&abi.record(i)); + if let Some(opaque) = abi.api.records[i].opaque { + let words: Vec = (0..opaque.words()) + .map(|k| { + let slot = format!("{a}[{}]", slots.len()); + slots.push(to_kotlin(&opaque, v, k)); + slot + }) + .collect(); + return self.made(&class, &opaque, &words); + } let mut fields = Vec::new(); for (k, field) in abi.api.records[i].fields.iter().enumerate() { let v = format!("{v}.f{k}"); fields.push(match &field.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => { - self.flat_out(*j, &v, (a, &mut *slots), (r, &mut *puts)) - } + Type::Record(j) => self.flat_out(*j, &v, (a, &mut *slots), (r, &mut *puts)), ty if scalar(abi, ty) => { let slot = format!("{a}[{}]", slots.len()); let (rust, kt) = match ty { @@ -3035,7 +3150,7 @@ impl<'a> Gen<'a> { } }); } - format!("{}({})", self.qualified(&abi.record(i)), fields.join(", ")) + format!("{class}({})", fields.join(", ")) } } @@ -3048,20 +3163,27 @@ fn scalar(abi: &Abi<'_>, ty: &Type) -> bool { } } -/// Whether the record `i`, or one it nests, holds a field that crosses encoded. +/// Whether the record `i`, or one it nests, holds a field that crosses encoded: an opaque +/// value holds none. fn rest(abi: &Abi<'_>, i: usize) -> bool { + if abi.api.records[i].opaque.is_some() { + return false; + } abi.api.records[i].fields.iter().any(|f| match &f.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => rest(abi, *j), + Type::Record(j) => rest(abi, *j), ty => !scalar(abi, ty), }) } /// The JVM parameter slots the record `i` takes flattened: two for each `long` or `double` /// scalar, one for any other, and two for its other fields, if any: their `byte[]` and the -/// arrays and text they name. +/// arrays and text they name. An opaque value takes two for each word. fn weight(abi: &Abi<'_>, i: usize) -> usize { + if let Some(opaque) = abi.api.records[i].opaque { + return 2 * opaque.words() as usize; + } let fields = abi.api.records[i].fields.iter().map(|f| match &f.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => weight(abi, *j) - 2 * usize::from(rest(abi, *j)), + Type::Record(j) => weight(abi, *j) - 2 * usize::from(rest(abi, *j)), Type::F64 => 2, Type::Int(int) | Type::NonZero(int) if jni_int(*int) == "jlong" => 2, ty if scalar(abi, ty) => 1, @@ -3077,16 +3199,14 @@ fn room(unflattened: usize, future: bool, written: bool) -> usize { 255usize.saturating_sub(unflattened + usize::from(future) + usize::from(written)) } -/// The JVM parameter slots the C parameter `c` takes as a native method's at most: two for -/// a `long` or `double`, as an opaque value Kotlin holds in a word is, none for what never -/// crosses, five for bytes (what holds them, a `long` owner, and two `int`s; text takes -/// one), two for an encoded value's `byte[]` and the arrays and text it names (a callback -/// takes one), and one for anything else, such as an opaque value's `long[]`. -fn c_slots(abi: &Abi<'_>, c: &Ty) -> usize { +/// The JVM parameter slots the C parameter `c` takes as a native method's at most, before +/// a record or an opaque value is flattened: two for a `long` or `double`, none for what +/// never crosses, five for bytes (what holds them, a `long` owner, and two `int`s; text +/// takes one), two for an encoded value's `byte[]` and the arrays and text it names (a +/// callback takes one), and one for anything else. +fn c_slots(c: &Ty) -> usize { match c { Ty::Void | Ty::Out(_) | Ty::Data | Ty::Poll => 0, - Ty::Struct(_) | Ty::In(_) if opaque_of(abi, c).is_some_and(|o| word(&o)) => 2, - Ty::Struct(_) | Ty::In(_) if opaque_of(abi, c).is_some() => 1, Ty::Int(int) if jni_int(*int) == "jlong" => 2, Ty::F64 | Ty::Handle { .. } | Ty::Future(_) => 2, Ty::Buf => 5, @@ -3220,10 +3340,7 @@ fn abi_bound(abi: &Abi<'_>, int: Int) -> String { /// The JNI type and the Kotlin native type of the C type `c`, of IR type `ty`. fn jni_type(abi: &Abi<'_>, c: &Ty, ty: &Type) -> (&'static str, &'static str) { match c { - Ty::Struct(_) | Ty::In(_) if let Some(opaque) = opaque_of(abi, c) => match word(&opaque) { - true => ("jlong", "Long"), - false => ("jlongArray", "LongArray"), - }, + Ty::Struct(_) | Ty::In(_) if opaque_of(abi, c).is_some_and(|o| one_word(&o)) => ("jlong", "Long"), Ty::Void => ("()", "Unit"), Ty::Bool => ("jboolean", "Boolean"), Ty::Int(int) => match jni_int(*int) { @@ -3262,40 +3379,47 @@ fn opaque_of(abi: &Abi<'_>, c: &Ty) -> Option { .and_then(|i| abi.api.records[i].opaque) } -/// The property of an opaque value's class holding it. -fn holder(opaque: &Opaque) -> &'static str { +/// The properties of an opaque value's class holding it, a word each: a value class's +/// `bits`, or `w0` and on. +fn holders(opaque: &Opaque) -> Vec { match word(opaque) { - true => "bits", - false => "words", + true => vec!["bits".to_string()], + false => (0..opaque.words()).map(|k| format!("w{k}")).collect(), } } -/// Whether Kotlin holds `opaque` in a `Long`, with no allocation: it fits one and is -/// dense, so values Rust calls equal have equal bits, as the value class compares them. +/// Whether Kotlin holds `opaque` in a value class over a `Long`, with no allocation: it +/// fits one and is dense, so values Rust calls equal have equal bits, as the value class +/// compares them. fn word(opaque: &Opaque) -> bool { opaque.compared() } -/// The Rust expression taking the opaque value Kotlin passed as `p`, as its C struct. -fn from_kotlin(opaque: &Opaque, p: &str) -> String { - match word(opaque) { - true => format!("rt::from_word({p})"), - false => format!("unsafe {{ rt::from_words::<_, {}>(env, {p}) }}", opaque.words()), - } +/// Whether `opaque` crosses JNI as one `long` wherever it crosses alone. +fn one_word(opaque: &Opaque) -> bool { + opaque.words() == 1 } -/// The JNI value Kotlin takes the opaque value's C struct `e` as. -fn to_kotlin(opaque: &Opaque, e: &str) -> String { - match word(opaque) { - true => format!("rt::to_word({e})"), - false => format!("rt::to_words::<_, {}>(env, {e})", opaque.words()), - } +/// The Rust expression taking the opaque value Kotlin passed as the `long`s `words`, as +/// its C struct. +fn from_kotlin(opaque: &Opaque, words: &[String]) -> String { + format!("rt::from_words::<_, {}>([{}])", opaque.words(), words.join(", ")) +} + +/// The JNI `long` word `k` of the opaque value's C struct `e`, as Kotlin holds it. +fn to_kotlin(opaque: &Opaque, e: &str, k: u64) -> String { + format!("rt::to_words::<_, {}>({e})[{k}]", opaque.words()) } /// The Rust expression returning to Kotlin a value `ret` of type `ok` that C returns as `c`. fn ret_expr(abi: &Abi<'_>, c: &Ty, ok: &Type) -> String { match c { - Ty::Struct(_) if let Some(opaque) = opaque_of(abi, c) => to_kotlin(&opaque, "ret"), + Ty::Struct(_) + if let Some(opaque) = opaque_of(abi, c) + && one_word(&opaque) => + { + to_kotlin(&opaque, "ret", 0) + } Ty::Void | Ty::Bool | Ty::F32 | Ty::F64 | Ty::Enum(_) => "ret".to_string(), Ty::Int(int) => format!("ret as {}", jni_int(*int)), Ty::Char => "ret as jint".to_string(), @@ -3311,8 +3435,15 @@ fn ret_expr(abi: &Abi<'_>, c: &Ty, ok: &Type) -> String { } /// The C type of the value a call returns directly, raising its error, if it returns a -/// result of a scalar, a handle, or nothing and writes back no argument: `Void` for nothing. -fn direct(outs: &[(String, Ty)], written: &[(String, Type)], ok: &Type, err: Option<&Type>) -> Option { +/// result of a scalar, a handle, an opaque value, or nothing and writes back no argument: +/// `Void` for nothing. +fn direct( + abi: &Abi<'_>, + outs: &[(String, Ty)], + written: &[(String, Type)], + ok: &Type, + err: Option<&Type>, +) -> Option { if err.is_none() || !written.is_empty() { return None; } @@ -3322,6 +3453,7 @@ fn direct(outs: &[(String, Ty)], written: &[(String, Type)], ok: &Type, err: Opt Ty::Bool | Ty::Int(_) | Ty::F32 | Ty::F64 | Ty::Char | Ty::Enum(_) | Ty::Handle { .. } => { Some((**c).clone()) } + Ty::Struct(_) if opaque_of(abi, c).is_some() => Some((**c).clone()), _ => None, }, _ => None, diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 52e89859e..a2e92024c 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -282,6 +282,17 @@ fun script() { val shifted = shifted(moment) { m -> m.after(500u) } println("shifted ${shifted.millis()} ${shifted == moment.after(500u)}") println("wrapped ${moment.after(ULong.MAX_VALUE).millis()} ${moment == shifted}") + // A record holding one crosses as its words, in and out, and a call with no slots + // left for one passes it encoded. + val clocked = clockedAfter(Clocked(moment, 1u), 500u) + check(clocked == Clocked(moment.after(500u), 2u) && clocked.at.millis() == 2000uL, "a record's moment crosses as its words") + check(crammed(moment, shifted, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL) == 1500uL + 2000uL + 124uL, "a crammed call passes its last moment encoded") + // A `Result` of one returns it directly, or throws. + check(momentAt(1500u, 1000u) == moment && stampAt(5u) == Stamp.fromMillis(5u), "a result's value returns directly") + check(runCatching { momentAt(1u, 0u) }.isFailure && runCatching { stampAt(0u) }.isFailure, "a result's error throws") + // One of 128 words is made with no constructor of a parameter each, and passed encoded. + val broad = Wide.new(ULong.MAX_VALUE) + check(broad.sum() == 8001uL - 1uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") // A value with padding, or bytes that vary, is a handle, as no table says where padding is. val gap = Gap.new(7u, 3u) diff --git a/quest/m1/ffi-speed/kotlin-options.md b/quest/m1/ffi-speed/kotlin-options.md new file mode 100644 index 000000000..531d0cf94 --- /dev/null +++ b/quest/m1/ffi-speed/kotlin-options.md @@ -0,0 +1,20 @@ +# [S] Kotlin options passed flat + +## Goal + +A [rust2-ffi](/ffi/README.md) Kotlin binding passes an `Option` of a record or an opaque +value as its JNI scalars, a `bool` and the value's own, as it passes one bare, instead of +encoded into a `byte[]`. moq's `group::Producer::write_frame` takes an `Option`, +so [the binding benchmark](/bench/ffi/README.md)'s write allocates 208 B a call in Kotlin +(the thread's allocated bytes over the case, measured 2026-11-14), a writer and its array +among them, and costs 220 ns against C's 163. The write then allocates no more than its +frame's bytes take. + +## Plan + +- Generalize `flat_in` in `ffi/src/kotlin.rs` to an `Option` of a record or an opaque value, + as `flat_out` already returns one: a `jboolean`, then the value's scalars, zero for `None`, + within the 255 JVM slots a method takes, and encoded past them. +- Kept by the maintainer on 2026-11-14 ([decision](https://github.com/kixel-ai/rust2/pull/820#issuecomment-6886625138)). +- Measure the write's wall time, CPU time, and allocated bytes against main's, interleaved. + diff --git a/quest/m1/ffi-speed/kotlin-values.md b/quest/m1/ffi-speed/kotlin-values.md deleted file mode 100644 index 036c0590d..000000000 --- a/quest/m1/ffi-speed/kotlin-values.md +++ /dev/null @@ -1,19 +0,0 @@ -# [S] Kotlin values without a LongArray - -## Goal - -A [rust2-ffi](/ffi/README.md) Kotlin binding holds a `Copy` value over 8 bytes, such as -moq's 16-byte `Timestamp`, in one object with no array beside it. Today it is a class -over a `LongArray`, two allocations per value, so -[the binding benchmark](/bench/ffi/README.md)'s stamped write costs 150 ns of CPU more -than the plain write in Kotlin (35 wall), against Swift's 1. The stamped write then costs -within its `from_micros` call of the plain write, as Go's and Dart's do. - -## Plan - -- One `Long` field per 8-byte word in the value's class, passed to and from JNI as that - many `jlong` arguments and a returned struct's words written into the class's fields, - so HotSpot's escape analysis can drop a value that does not escape. -- `equals` and `hashCode` keep today's rules, so only the storage changes. -- Re-measure the stamped write, CPU and wall, on HotSpot and on ART in the nightly - emulator job.