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
9 changes: 8 additions & 1 deletion ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export's, and adds nothing; another crate's type is refused.
| a generic function or method, at each instance `instances` names | that instance in place of the rules below, at each instance of its type; one whose bounds fail, or that nothing exported reaches, is refused |
| a `pub` field of an object | a getter returning a copy |
| a `pub` trait | a callback interface: a table of C functions and their data |
| a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce`, which no lifetime bound or return lets outlive the call | a C function and its `void *` data, which Rust calls only during the call; any other closure is refused |
| `fn` and inherent `pub` methods | functions named through their type |
| `Result<T, E>` | `bool f(..., T *out, E *err)` |
| a returned tuple `(A, B)` | one out pointer each: `void f(..., A *out0, B *out1)` |
Expand Down Expand Up @@ -119,6 +120,11 @@ refused, and the census counts why.
- **Callbacks** are a struct of a table and its data. Rust calls `free` once it drops the
implementation, and may call the others from any thread. A callback takes scalars and
buffers lent for the call, and returns a scalar.
- **Closures** lent for a call are a function and its data, which Rust calls only during
the call, from any thread. One takes what a callback takes, and objects by reference,
each lent as a handle to the value where it is for that call: C borrows it no further
than Rust lent it, and moving out of it, freeing it, or keeping a borrow past the call
aborts.
- **The contract** is a hash of the header's declarations, its docs included: the header
defines it as `<PREFIX>_CONTRACT`, and `<prefix>_contract()` returns it from the library
built with the header. A binding checks the two match before any other call, so a header
Expand Down Expand Up @@ -173,4 +179,5 @@ moq's crates export through `target/moq-ffi`, an empty library on each that `jus
writes in place of moq-ffi's remainder. `moq/moq.c` publishes and subscribes to a moq-net
track in one process, polling each read, scopes an origin to moq-pattern's patterns and
hands it to a client to publish, polls its driver until the origin's last owner drops, reads an OpusHead into hang's catalog through moq-mux,
and publishes a binary track the catalog lists.
publishes a binary track the catalog lists, and reads the catalog lent to C through
`catalog::Producer::mutate`.
14 changes: 14 additions & 0 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ fn main() {
let mut last = registry.last().unwrap().clone();
let _ = last.add(10);
println!("last {} lent {}", registry.last().unwrap().get(), last.get());
// A closure lent for the call edits the first counter through a handle.
let edited = registry.edit(|counter| {
let _ = counter.add(5);
counter.edited() && counter.get() == 6
});
println!("edit {edited} {}", registry.first.get());
println!("walk {}", api_lib::walk(3, |cursor| cursor.at() * 2));
println!("offset {}", api_lib::offset(|| 7, 3));

let name = Name::owned("a".to_string());
let mut joined = name.join(&Name::owned("b".to_string()));
Expand Down Expand Up @@ -148,6 +156,11 @@ fn main() {
println!("write {}", logger.write("hi"));
drop(logger);
println!("dropped");
let kept = api_lib::filter(vec![1, 2, 3, 4], |level, line| {
println!("filter {level} {line}");
level > 2
});
println!("filtered {kept}");

let channel = Channel::new();
let count = Arc::new(Count(AtomicUsize::new(0)));
Expand Down Expand Up @@ -196,6 +209,7 @@ fn main() {
tally.bump();
println!("tally {} {}", tally.bump(), tally == tally);
println!("both {}", api_lib::bump_both(&tally, &tally));
println!("peek {}", api_lib::peek(&tally, |tally| tally.bump()));

let area = api_lib::grow(&dep::Area::new(Size { width: 2, height: 3 }), 1);
let size = area.size();
Expand Down
54 changes: 54 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ impl Counter {
}
}

/// Whether this is the counter [`Registry::edit`] lends, by its address, which a handle
/// lent for the call keeps.
pub fn edited(&self) -> bool {
std::ptr::from_ref(self) as usize == EDITING.load(std::sync::atomic::Ordering::Relaxed)
}

/// Consumes the counter.
pub fn into_label(self, at: Option<Point>) -> Label {
Label {
Expand Down Expand Up @@ -176,8 +182,21 @@ impl Registry {
pub fn push(&mut self, counter: Counter) {
self.last = Some(counter);
}

/// The first counter lent to `edit` for the call, returning what `edit` does: a closure
/// called only during the call, which C lends as a function.
pub fn edit(&mut self, edit: impl FnOnce(&mut Counter) -> bool) -> bool {
EDITING.store(
std::ptr::from_ref(&self.first) as usize,
std::sync::atomic::Ordering::Relaxed,
);
edit(&mut self.first)
}
}

/// The address of the counter [`Registry::edit`] lends.
static EDITING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// A name that may borrow its text: its only generic parameter is a lifetime, so a
/// handle holds `Name<'static>`, which borrows nothing.
#[derive(Clone, Debug, PartialEq)]
Expand Down Expand Up @@ -389,6 +408,15 @@ pub fn emit(log: impl Log, lines: Vec<u8>) -> u32 {
lines.iter().filter(|&&n| log.log(n, &format!("line {n}"))).count() as u32
}

/// Each line to `keep` on another thread, returning how many it kept: a lent closure may
/// run on any thread until the call returns.
pub fn filter(lines: Vec<u8>, mut keep: impl FnMut(u8, &str) -> bool + Send) -> u32 {
std::thread::scope(|scope| {
let kept = scope.spawn(move || lines.iter().filter(|&&n| keep(n, &format!("line {n}"))).count());
kept.join().expect("the thread finishes") as u32
})
}

/// Holds a foreign implementation as a trait object, dropping it with itself.
pub struct Logger {
sink: Box<dyn Log>,
Expand Down Expand Up @@ -499,6 +527,32 @@ pub fn bump_both(a: &Tally, b: &Tally) -> u32 {
a.bump() + b.bump()
}

/// What `by` returns, plus `by_data`: a closure taking nothing, whose data C names apart.
pub fn offset(by: impl Fn() -> u32, by_data: u32) -> u32 {
by() + by_data
}

/// A position, which C reaches only as [`walk`] lends it.
pub struct Cursor {
at: u64,
}

impl Cursor {
pub fn at(&self) -> u64 {
self.at
}
}

/// A cursor at each of `0..steps` lent shared to `visit`, summing what it returns.
pub fn walk(steps: u64, mut visit: impl FnMut(&Cursor) -> u64) -> u64 {
(0..steps).map(|at| visit(&Cursor { at })).sum()
}

/// The tally lent shared to `peek` for the call, on one thread, as it is not `Sync`.
pub fn peek(tally: &Tally, peek: impl FnOnce(&Tally) -> u32) -> u32 {
peek(tally)
}

/// The length of a payload, borrowed for the call.
pub fn len(payload: &[u8]) -> usize {
payload.len()
Expand Down
5 changes: 5 additions & 0 deletions ffi/fixtures/reject/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ fixtures/reject/src/lib.rs:192:1: rust2-ffi: cannot export fn `lend`: Waker outs
fixtures/reject/src/lib.rs:19:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:207:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C
fixtures/reject/src/lib.rs:199:2: note: field `reject_fixture::Limit::max` is here
fixtures/reject/src/lib.rs:213:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:218:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:229:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:235:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option<std::boxed::Box<std::option::Option<u32>>>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:36:1: rust2-ffi: instance `Opaque<u8>` in the config exports nothing: `reject_fixture::Opaque` takes no type arguments
Expand Down
27 changes: 27 additions & 0 deletions ffi/fixtures/reject/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,30 @@ impl Limit {
self.max.max(1)
}
}

/// A closure kept past the call, as a `'static` bound lets it be.
pub fn spawn(task: impl FnOnce() + Send + 'static) {
std::thread::spawn(task);
}

/// A closure the future holds past the call.
pub async fn later(task: impl FnOnce()) {
task()
}

/// A closure bound by more than C's function can meet.
pub fn twice(f: impl Fn() + Clone) {
f.clone()();
f()
}

/// One closure type for two parameters, which C's two functions cannot be.
pub fn both<F: Fn()>(a: F, b: F) {
a();
b()
}

/// An object lent only for as long as it borrows, which a handle's `'static` outlives.
pub fn read(f: impl FnOnce(&Text<'_>)) {
f(&Text(""))
}
1 change: 0 additions & 1 deletion ffi/moq/ffi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,6 @@ exclude = [
"catalog::Producer::json_snapshot",
"catalog::Producer::json_stream",
"catalog::Producer::modify",
"catalog::Producer::mutate",
"catalog::Producer::stats",
"catalog::Producer::text",
"catalog::Producer::track",
Expand Down
20 changes: 19 additions & 1 deletion ffi/moq/moq.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* moq's exported C API against the real library: a broadcast's track, published and
* subscribed to in one process, with every read polled as a future, and an origin.
* moq-pattern, moq-clock, moq-tokio, hang, and moq-mux export into the same library, and
* each names the others' types.
* each names the others' types, and the catalog is lent to C for a call.
*
* It needs no runtime: the waker counts wakes, and each poll that must wait is polled
* again after the write that wakes it. */
Expand Down Expand Up @@ -35,6 +35,21 @@ static int is(moq_buf buf, const char *s) {
return same;
}

/* The catalog `mutate` lends for its call, which lists the binary track: counts it in
* data. */
static void lists_state(void *data, moq_hang_catalog *catalog) {
moq_buf json;
moq_hang_error *hang_err = NULL;
CHECK(moq_hang_catalog_to_json(catalog, &json, &hang_err));
for (size_t i = 0; i + 5 <= json.len; i++) {
if (memcmp(json.ptr + i, "state", 5) == 0) {
(*(int *)data)++;
break;
}
}
moq_buf_free(json);
}

static int wakes = 0;

static void wake(void *data) {
Expand Down Expand Up @@ -262,6 +277,9 @@ int main(void) {
moq_track_producer_free(state);
CHECK(is(moq_binary_snapshot_name(snapshot), "state"));
CHECK(moq_binary_snapshot_update(snapshot, str("latest"), &mux_err));
int listed_state = 0;
CHECK(moq_catalog_producer_mutate(catalog, lists_state, &listed_state, &mux_err));
CHECK(listed_state == 1);
moq_binary_snapshot_free(snapshot);
moq_catalog_producer_free(catalog);
moq_broadcast_producer_free(publisher);
Expand Down
Loading