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
36 changes: 25 additions & 11 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,9 @@ public path names, or an error taken by value, is held by value as an opaque han
| `Arc<T>` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc<rustls::ServerConfig>`, or `Arc<dyn Trait>` and `&'static dyn Trait` of another crate's trait without generic arguments, whose auto traits are `Send` and `Sync` but those the trait implies, borrowing nothing C lends, as rustls's `Arc<dyn ResolvesServerCert>` | an opaque object named by `T`'s crate and name, such as `<prefix>_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust |
| another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names, or a standard library type no other rule maps, such as `io::Error`, named by its full path, `<prefix>_std_io_Error` | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value |
| a type implementing `PartialEq` and `Hash` | beside `<T>_eq`, `uint64_t <T>_hash`, its `Hash` through std's hasher with its fixed keys, so equal values hash alike in every binding |
| `std::time::Instant` | an object `<prefix>_Instant`, which only Rust makes, copied into each call that takes it and compared by `_eq`, with none of its methods |
| `tracing::Level` | `<prefix>_Level`: a C enum of its five levels, `TRACE` to `ERROR` |
| a type implementing `PartialOrd` with itself | `int8_t <T>_partial_cmp(a, b)`: -1, 0, or 1 as `a` is less than, equal to, or greater than `b`, or 2 when the two are unordered; with `Ord`, `int8_t <T>_cmp(a, b)` too, -1, 0, or 1. Every binding's `<` and its kin call `_partial_cmp`, as Rust's do, and its total order, where it has one, `_cmp` |
| `std::time::Instant` | an object `<prefix>_Instant`, which only Rust makes, copied into each call that takes it and compared by `_eq` and ordered by `_cmp`, with none of its methods |
| `tracing::Level` | `<prefix>_Level`: a C enum of its five levels, `ERROR` (0) to `TRACE` (4), numbered in tracing's `Ord`, the more verbose after the less, so every language's own order of it agrees with Rust's |
| `tracing::level_filters::LevelFilter` | `Option<tracing::Level>`, whose `None` is `OFF` |
| `serde_json::Value` | an object `<prefix>_Json`, made by `<prefix>_Json_parse` from JSON text, which fails with serde_json's message, and read back by `_to_text`; its contents are the caller's JSON library's to read |
| `Vec<T>`, `&[T]`, and `Box<[T]>` of any other `T` | `<prefix>_vec_<T>`: an array of `T`'s C values, viewed passed in and owned returned, a slice as a clone; of references only returned; a boxed slice of bytes is refused |
Expand Down Expand Up @@ -179,8 +180,8 @@ is the call's. A signature may not lend C's borrow for one that is `'static`, bu
exclusive lend: a `&mut self` method of an object returning an object, bare or as a
`Result`'s `Ok`, that borrows the receiver's lifetime alone and is not `Copy`, as a lock's
guard does, which its handle holds with the receiver's exclusive borrow; a copy would
carry the borrow past it. Each of its `Clone`, `PartialEq`, `Hash`, `Debug`, `Display`,
`Deref`, and `DerefMut` must hold at every lifetime, as the binding calls them on the
carry the borrow past it. Each of its `Clone`, `PartialEq`, `Hash`, `PartialOrd`, `Ord`,
`Debug`, `Display`, `Deref`, and `DerefMut` must hold at every lifetime, as the binding calls them on the
`'static` form, and its `Deref` target must name no lifetime. So must each of the
method's own bounds naming the receiver's lifetime, as the binding's lend gives the call a
borrow of any lifetime. A parameter is a reference
Expand Down Expand Up @@ -518,7 +519,10 @@ packages place it in.
- **Objects** are classes owning their handle through a `std::unique_ptr` whose deleter
calls `_free`, so they move and never copy, and a `Clone` type's `clone()` crosses into
Rust for a value of its own. A type implementing `Hash` has `hash()`, Rust's, by which
`std::hash` hashes it. A type whose copies may share one value, by the rule below,
`std::hash` hashes it. Every type implementing `PartialOrd` has `<`, `<=`, `>`, and `>=`,
through Rust's `partial_cmp`, and from C++20 `<=>`: a `std::weak_ordering` through `cmp`
with `Ord`, since Rust's `Equal` promises agreement with `==` alone, and else a
`std::partial_ordering`. A type whose copies may share one value, by the rule below,
owns it through a `std::shared_ptr` instead: a copy shares the handle without crossing
into Rust, and the last copy frees it, on whichever thread drops it. `&self` methods are
`const`, and `self` methods are `&&`, so a call that moves the value out reads
Expand Down Expand Up @@ -659,7 +663,10 @@ the rest cross encoded.
the GC frees it once it collects it, on a daemon thread a phantom reference queue feeds. A `self`
method, or passing the object by value, moves its value out and closes it once the call
returns. `Clone` is `clone()`, `PartialEq` is `equals`, and `Hash` is `hashCode`, Rust's
hash folded as `Long.hashCode` folds it, or 0 without one. A value that is not `Send`
hash folded as `Long.hashCode` folds it, or 0 without one. `PartialOrd` is
`partialCompareTo`, null when unordered, and `Ord` makes it `Comparable`, whose
`compareTo`, and so `<`, is Rust's `cmp`; an enum class's `compareTo` stays Kotlin's
own by declaration order, which Kotlin makes final. A value that is not `Send`
throws an `IllegalStateException` when used on another thread than the one that made
it, and closed or collected on another, it drops on its own at its next call or as it
exits. A future that is not `Send` made from none lives on a home, so a coroutine a
Expand Down Expand Up @@ -825,7 +832,7 @@ caller imports it with no ignores.
- **Objects** are classes owning their handle, freed once their last reference goes,
which the caller's reference keeps through a call, so there is no `close()`. A `self`
method, or passing the object by value, moves its value out, after which a call raises
`ValueError`. `Clone` is `clone()`, and `PartialEq` is `==`, unhashable unless the type implements `Hash`, which `hash()` hashes it by. An object, as
`ValueError`. `Clone` is `clone()`, and `PartialEq` is `==`, unhashable unless the type implements `Hash`, which `hash()` hashes it by. `PartialOrd` is `<`, `<=`, `>`, and `>=`, through Rust's `partial_cmp`, each false when the two are unordered. An object, as
an opaque value and a record, takes weak references (`weakref.ref`). A field is a
property, `first_get`, and its setter a method, `first_set(value)`, named as the C ones,
since setting an object moves it in and closes it, which an assignment would hide.
Expand Down Expand Up @@ -952,7 +959,8 @@ value of a Rust type crosses as one Swift type that holds it exactly, and back u
`clamped()`, `clamped(low:)`, `clamped(high:)` and `clamped(low:high:)`, up to two per
function; `Option<&mut T>` is `inout T?`. `Clone` is `clone()`, and `PartialEq` is `==`, which Swift 6.4 makes
`Equatable` unless it throws, as below, and `Hashable` with `Hash`, whose `hash(into:)`
combines Rust's hash; `Display` is `description` and `Debug`
combines Rust's hash; `PartialOrd` is `<`, `<=`, `>`, and `>=`, through Rust's
`partial_cmp`, and with `Ord` makes it `Comparable` unless it throws; `Display` is `description` and `Debug`
`debugDescription`, which Swift conforms no noncopyable type to yet. A `Copy` object,
which Rust copies where it takes one by value, and an object thrown as an error, which
`Swift.Error` requires be copyable, are final classes instead, whose handle a call
Expand Down Expand Up @@ -1166,7 +1174,9 @@ other than one in its own form, `module <path>` and `go 1.24`.
variant (`ShapeSquare`). An enum with data is an interface each variant's struct
implements (`EventMoved{V0: p}`), sealed so only the package's do; its methods are the
interface's. Positional fields are `V0`, `V1`, and so on. `Display` is `String()`,
`Debug` `GoString()`, `PartialEq` `Equal(other)`, all through Rust's, and `Default` a
`Debug` `GoString()`, `PartialEq` `Equal(other)`, `PartialOrd` `PartialCompare(other)`,
-1, 0, or 1 and false when unordered, and `Ord` `Compare(other)`, the shape
`slices.SortFunc` takes, all through Rust's, and `Default` a
function of the package, `PointDefault()`. An object's exported `Handle_` field, and a
trait's `<Trait>Vtable_` function, are how one generated package reaches another's,
since cgo gives each its own C types: callers use neither. An **opaque value** is a
Expand Down Expand Up @@ -1309,7 +1319,9 @@ the library's own URI, mapped to the library by a build hook or by `--native-ass
with data a sealed class with a final class per variant (`EventMoved`), so a `switch`
over it is exhaustive. `Display` is `toString()`, `Debug` `debug()`, `PartialEq` `==`, and
`Hash` `hashCode`, all through Rust's; without `Hash`, `hashCode` throws an
`UnsupportedError`, since no hash Dart computes agrees with Rust's `==`. `Default` is a
`UnsupportedError`, since no hash Dart computes agrees with Rust's `==`. `PartialOrd` is
`<`, `<=`, `>`, `>=`, and `partialCompareTo`, null when unordered, through Rust's
`partial_cmp`, and `Ord` makes it `Comparable`, whose `compareTo` is Rust's `cmp`. `Default` is a
constructor, `default_()`. An
**opaque value** is a final class of its bytes as `int`s, with a private constructor,
so only Rust makes one. It never changes: a `&mut self` method, a field's setter
Expand Down Expand Up @@ -1564,7 +1576,9 @@ packs the api fixture's with npm, installs it into a project of its own, type-ch
once it drops an implementation, and **closures** are functions: each is a C function
the module imports from `rust2`, whose data is a token the binding finds the value by, so
JavaScript never writes the module's function table. Its std traits are functions of its
module: `toString`, `debug`, an object's `clone`, `eq`, with `Hash` `hash`, and `default`.
module: `toString`, `debug`, an object's `clone`, `eq`, with `Hash` `hash`, `partialCmp`
from `PartialOrd`, undefined when unordered, `cmp` from `Ord`, the shape
`Array.prototype.sort` takes, and `default`.
- **Futures** are an `rt.Call`, a `Promise` with `cancel()`: the call polls once as it is
made, and each wake polls again on a microtask, never inside the wake. Cancelling frees
the future in Rust, losing nothing, and rejects with `rt.Cancelled`. A future JavaScript
Expand Down
69 changes: 68 additions & 1 deletion ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::task::{Context, Poll, Wake, Waker};

use api::{
Channel, Counter, Event, LIMIT, Label, Log, Logger, Message, Name, Node, Pair, Point, Registry, Shape, Size, Stack,
Stamp, Tally, Waiter, Window,
Stamp, Tally, Tier, Version, Waiter, Window,
};
use bytes::Bytes;

Expand Down Expand Up @@ -995,6 +995,73 @@ fn main() {
a.hash_of() == api::Key::new("a").hash_of(),
a.hash_of() == b.hash_of()
);
// A version orders by its derived `Ord`, and its `<` by `PartialOrd`, which agrees.
let (v1, v2) = (Version { major: 1, minor: 2 }, Version { major: 1, minor: 10 });
println!(
"version {} {} {} {} {} {} {}",
v1 < v2,
v1 <= v2,
v1 > v2,
v1 >= v2,
v1.cmp(&v2) as i8,
v2.cmp(&v1) as i8,
v1.cmp(&v1) as i8
);
// A quantity orders by its hand-written `PartialOrd`, which leaves two units unordered.
let (m1, m2, g1) = (
api::Quantity::new(1, 'm'),
api::Quantity::new(2, 'm'),
api::Quantity::new(1, 'g'),
);
println!(
"quantity {} {} {} {} {} {} {} {} {}",
m1 < m2,
m1 <= m2,
m1 > m2,
m1 >= m2,
m1 <= api::Quantity::new(1, 'm'),
m1 < g1,
m1 <= g1,
m1 > g1,
m1 >= g1
);
println!(
"tier {} {} {} {} {}",
Tier::Low < Tier::High,
Tier::CompareTo < Tier::PartialCompareTo,
Tier::Low >= Tier::Low,
Tier::High.cmp(&Tier::Low) as i8,
Tier::Low.cmp(&Tier::High) as i8
);
// A pass's handle is checked, so its comparisons can fail, yet it still orders by `Ord`.
let (t1, t2) = (api::Pass::new(1), api::Pass::new(2));
println!(
"pass {} {} {} {} {}",
t1 < t2,
t1 >= t2,
t1.cmp(&t2) as i8,
t2.cmp(&t1) as i8,
t1.cmp(&t1) as i8
);
// A rank's fields are named as the comparison methods, which each binding keeps apart.
let ranked = api::Rank::Ranked {
compare: 1,
partial_compare: 2,
compare_to: 3,
partial_compare_to: 4,
};
println!(
"rank {} {} {}",
api::Rank::Unranked < ranked,
ranked.cmp(&api::Rank::Unranked) as i8,
ranked
== api::Rank::Ranked {
compare: 1,
partial_compare: 2,
compare_to: 3,
partial_compare_to: 4
}
);
println!(
"lossless ip {} {}",
ip_hex(api::same_ip_addr("255.255.255.255".parse().unwrap())),
Expand Down
68 changes: 68 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5170,6 +5170,74 @@ pub fn same_ip_addr(v: std::net::IpAddr) -> std::net::IpAddr {
v
}

/// A version: a record whose derived `Ord` is a total order, `major` first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
pub major: u16,
pub minor: u16,
}

/// A quantity: an object whose hand-written `PartialOrd` leaves quantities of two units
/// unordered, as moq's timestamps of two scales are, so it has no `Ord`.
#[derive(Debug, PartialEq)]
pub struct Quantity {
value: i64,
unit: char,
}

impl Quantity {
pub fn new(value: i64, unit: char) -> Quantity {
Quantity { value, unit }
}
}

impl PartialOrd for Quantity {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
(self.unit == other.unit).then(|| self.value.cmp(&other.value))
}
}

/// A pass: an object whose derived `Ord` is a total order, and whose handle a call checks,
/// since `redeem` moves it out.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Pass {
number: u32,
}

impl Pass {
pub fn new(number: u32) -> Pass {
Pass { number }
}

/// Its number, using it up.
pub fn redeem(self) -> u32 {
self.number
}
}

/// A rank: a data enum with `Ord` whose fields are named as the comparison methods a
/// binding gives it, which each binding's names for them must keep apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rank {
Unranked,
Ranked {
compare: u8,
partial_compare: u8,
compare_to: u8,
partial_compare_to: u8,
},
}

/// A tier: an enum whose derived `Ord` orders its variants as declared.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Tier {
Low,
High,
/// Named as Dart's comparison methods are, which its constants keep apart.
CompareTo,
PartialCompareTo,
}

/// A key: an object whose `Hash` agrees with its `PartialEq`, so a binding hashes it by
/// Rust's, as a map keyed by it needs.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
Expand Down
6 changes: 6 additions & 0 deletions ffi/moq/moq.c
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,12 @@ int main(void) {
uint64_t secs = 0;
CHECK(moq_Timestamp_from_millis(1500, &at, &overflow));
CHECK(moq_Timestamp_as_secs(&at, &secs, &overflow) && secs == 1);
/* Timestamps order in time across scales, and a scaled one and an unscaled key not at all. */
moq_Timestamp second;
CHECK(moq_Timestamp_from_secs(1, &second, &overflow));
CHECK(moq_Timestamp_partial_cmp(&second, &at) == -1);
CHECK(moq_Timestamp_partial_cmp(&at, &second) == 1);
CHECK(moq_Timestamp_partial_cmp(&key, &at) == 2);
CHECK(!moq_group_Producer_write_frame(writer, at, str("late"), &err, NULL));
CHECK(err != NULL && is(moq_Error_to_string(err, NULL), "frame timestamp doesn't fit its track"));
moq_Error_free(err);
Expand Down
6 changes: 6 additions & 0 deletions ffi/moq/moq.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ int main() {
// untimed, so a timed frame is refused.
auto at = moq::Timestamp::from_millis(1500);
CHECK(at && at->as_secs() && *at->as_secs() == 1);
// Timestamps order in time across scales, and a scaled one and an unscaled key not at all.
{
auto second = moq::Timestamp::from_secs(1);
auto key = moq::Timestamp::unscaled(0);
CHECK(second && *second < *at && *at > *second && !(key < *at) && !(key >= *at));
}
auto late = writer->write_frame(*at, "late");
CHECK(!late && is(late.error().to_string(), "frame timestamp doesn't fit its track"));
CHECK(at->as_secs() && *at->as_secs() == 1);
Expand Down
5 changes: 5 additions & 0 deletions ffi/moq/moq.dart
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ Future<void> local() async {
// untimed, so a timed frame is refused.
final at = moq.Timestamp.fromMillis(moq.U64(1500));
expect(at.asSecs() == moq.U64(1), '1500 ms is 1 s');
// Timestamps order in time across scales, and a scaled one and an unscaled key not at all.
final second = moq.Timestamp.fromSecs(moq.U64(1));
final key = moq.Timestamp.unscaled(moq.U64(0));
expect(second < at && at > second && second.partialCompareTo(at) == -1, '1 s is before 1500 ms');
expect(!(key < at) && !(key >= at) && key.partialCompareTo(at) == null, 'an unscaled key is unordered against a time');
throws<moq.Error>(
() => writer.writeFrame(at, utf8.encode('late')),
(e) => '$e' == "frame timestamp doesn't fit its track",
Expand Down
7 changes: 7 additions & 0 deletions ffi/moq/moq.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,13 @@ func script() {
// untimed, so a timed frame is refused.
at := must(net.TimestampFromMillis(1500))
expect(must(at.AsSecs()) == 1, "1500 ms is 1 s")
// Timestamps order in time across scales, and a scaled one and an unscaled key not at all.
second := must(net.TimestampFromSecs(1))
key := net.TimestampUnscaled(0)
order, ordered := second.PartialCompare(at)
expect(ordered && order == -1, "1 s is before 1500 ms")
_, ordered = key.PartialCompare(at)
expect(!ordered, "an unscaled key is unordered against a time")
err = writer.WriteFrame(at, rt.NewBytes([]byte("late")))
expect(errors.As(err, &merr) && err.Error() == "frame timestamp doesn't fit its track", "the late frame's error is Rust's")
expect(must(at.AsSecs()) == 1, "a copied timestamp stays usable")
Expand Down
5 changes: 5 additions & 0 deletions ffi/moq/moq.kt
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ fun main() {
// untimed, so a timed frame is refused.
val at = Timestamp.fromMillis(1500u)
expect(at.asSecs() == 1uL, "1500 ms is 1 s")
// Timestamps order in time across scales, and a scaled one and an unscaled key not at all.
val second = Timestamp.fromSecs(1u)
val key = Timestamp.unscaled(0u)
expect(second.partialCompareTo(at) == -1 && at.partialCompareTo(second) == 1, "1 s is before 1500 ms")
expect(key.partialCompareTo(at) == null, "an unscaled key is unordered against a time")
try {
writer.writeFrame(at, Bytes("late".encodeToByteArray()))
expect(false, "a timed frame on an untimed track is an error")
Expand Down
5 changes: 5 additions & 0 deletions ffi/moq/moq.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ def local(loop):
# untimed, so a timed frame is refused.
at = moq.Timestamp.from_millis(1500)
expect(at.as_secs() == 1, "1500 ms is 1 s")
# Timestamps order in time across scales, and a scaled one and an unscaled key not at all.
second = moq.Timestamp.from_secs(1)
key = moq.Timestamp.unscaled(0)
expect(second < at and at > second, "1 s is before 1500 ms")
expect(not key < at and not key >= at, "an unscaled key is unordered against a time")
try:
writer.write_frame(at, b"late")
expect(False, "a timed frame on an untimed track is an error")
Expand Down
5 changes: 5 additions & 0 deletions ffi/moq/moq.swift
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,11 @@ func script() throws {
// untimed, so a timed frame is refused.
let at = try Timestamp.fromMillis(1500)
expect(try at.asSecs() == 1, "1500 ms is 1 s")
// Timestamps order in time across scales, and a scaled one and an unscaled key not at all.
let second = try Timestamp.fromSecs(1)
let key = Timestamp.unscaled(0)
expect(second < at && at > second, "1 s is before 1500 ms")
expect(!(key < at) && !(key >= at), "an unscaled key is unordered against a time")
do {
try Bytes("late".utf8).withSpan { try writer.writeFrame(at, $0) }
expect(false, "a timed frame on an untimed track is an error")
Expand Down
Loading