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
3 changes: 2 additions & 1 deletion ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export's, and adds nothing; another crate's type 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)` |
| a tuple inside another type, or as a field or parameter | `<prefix>_tuple_<A>_<B>`: a struct of fields `_0`, `_1`, and so on; of references only returned |
| `async fn`, or a return that implements `Future` | a future: `f` makes it, `f_poll` polls it, `f_future_free` drops it; a function that is not `async` runs at the call, as in Rust |
| `poll_x`, when `x` exports as a future | left out: the future is its poll |
| `bool`, integers but 128-bit, floats, `char` | `bool`, `<stdint.h>` types, `float`, `double`, a `uint32_t` code point |
Expand Down Expand Up @@ -241,7 +242,7 @@ in as a `ByteArray`, bytes returned as their owner, and anything else encoded in
as a read-only direct `ByteBuffer` until `close()` frees it, or, never closed, until the
GC collects that buffer; `Bytes(ByteArray)` holds Kotlin's for a record passed in.
Strings are `String`, `Option<T>` `T?`, a tuple `Pair`,
`Triple`, or past them a generated `Tuple<n>`, `Duration` `kotlin.time.Duration`, and an `Err` a thrown `<E>Exception`
`Triple`, or else a generated `Tuple<n>`, though a tuple of one returned whole is its element, `Duration` `kotlin.time.Duration`, and an `Err` a thrown `<E>Exception`
holding it, whose message is its `Display`.
- A **path** is a `String`: one Rust returns that is not UTF-8 throws. A `SocketAddr`,
`SocketAddrV4`, or `SocketAddrV6` is a `java.net.InetSocketAddress`, which must be
Expand Down
54 changes: 54 additions & 0 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,52 @@ fn main() {
Err(e) => println!("divide err {e}"),
}
}
for n in [98305, 0] {
match api_lib::spread(n) {
Some((a, b, c, d)) => println!("spread {a} {b} {c} {d}"),
None => println!("spread none"),
}
}
for needle in [&b"lo"[..], b"x"] {
match api_lib::find(b"hello", needle) {
Some((at, len)) => println!("find {at} {len}"),
None => println!("find none"),
}
}
let rows = api_lib::rows(&[Point { x: 1, y: 2 }, Point { x: 3, y: 3 }]);
let rows: Vec<String> = (rows.iter())
.map(|(name, shape, p)| format!("{name} {shape:?} {} {}", p.x, p.y))
.collect();
println!("rows {}", rows.join(", "));
let board = api_lib::Board::new(vec![
("low".to_string(), Counter::new("l", 1)),
("high".to_string(), Counter::new("h", 9)),
]);
let ranked: Vec<String> = (board.ranked())
.map(|(name, counter)| format!("{name} {} {}", counter.name(), counter.get()))
.collect();
println!("ranked {}", ranked.join(", "));
let span = api_lib::Span {
bounds: (2, 10),
named: Some(("s".to_string(), Shape::Square)),
};
let ((a, b), (c, d)) = api_lib::halves(&span);
println!("halves {a} {b} {c} {d} {span:?}");
let (n, text) = api_lib::swapped(("t".to_string(), 4));
println!("swapped {n} {text}");
for value in [None, Some((None,)), Some((Some(3),))] {
println!("doubled {:?}", api_lib::doubled(value));
}
let lent = (vec![1, 2],);
let (lent,) = api_lib::lent_back(&lent);
let (boxed,) = *api_lib::boxed_tuple(vec![3]);
println!("lent back {lent:?} boxed {boxed:?}");
println!(
"title {:?} {:?} named {:?}",
api_lib::title(true),
api_lib::title(false),
api_lib::named("x")
);

// Each lent counter is a new handle to a clone.
let mut registry = Registry::new(Counter::new("first", 1));
Expand Down Expand Up @@ -144,6 +190,14 @@ fn main() {
api_lib::count((Bound::Excluded(2), Bound::Included(4)))
);
println!("end {:?} {:?}", api_lib::end(3), api_lib::end(0));
let (start, end) = api_lib::ends(3);
println!("ends {start:?} {end:?}");
for n in [2, 5] {
match api_lib::below(n, 3) {
Ok(n) => println!("below {n}"),
Err((start, end)) => println!("below err {start:?} {end:?}"),
}
}
let window = Window {
range: 2..8,
end: api_lib::end(5),
Expand Down
110 changes: 110 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,101 @@ pub fn divide(a: u64, b: u64) -> Result<(u64, u64), Error> {
}
}

/// `n` narrowed as [`widths`] does, unless 0: a tuple inside an `Option` is a struct.
pub fn spread(n: u64) -> Option<(u8, i16, u32, u64)> {
(n != 0).then(|| widths(n))
}

/// Where `needle` first starts in `haystack`, and its length, as moq-mux's
/// `find_start_code` returns it.
pub fn find(haystack: &[u8], needle: &[u8]) -> Option<(usize, usize)> {
(haystack.windows(needle.len()))
.position(|window| window == needle)
.map(|at| (at, needle.len()))
}

/// Each point named by its index, with its shape: rows of tuples, as moq-net's stats
/// snapshots return them.
pub fn rows(points: &[Point]) -> Vec<(String, Shape, Point)> {
(points.iter().enumerate())
.map(|(i, p)| {
let shape = match p.x == p.y {
true => Shape::Square,
false => Shape::Circle,
};
(format!("p{i}"), shape, *p)
})
.collect()
}

/// Counters by name, which takes each counter's handle in a tuple.
pub struct Board {
counters: std::collections::BTreeMap<String, Counter>,
}

impl Board {
pub fn new(counters: Vec<(String, Counter)>) -> Self {
Self {
counters: counters.into_iter().collect(),
}
}

/// Each name and its counter, highest first, as hang's `ranked`: each pair borrowed,
/// so each crosses as a clone.
pub fn ranked(&self) -> impl Iterator<Item = (&String, &Counter)> {
let mut ranked: Vec<_> = self.counters.iter().collect();
ranked.sort_by_key(|(_, counter)| std::cmp::Reverse(counter.get()));
ranked.into_iter()
}
}

/// A span: a record whose fields are tuples, one holding text.
#[derive(Clone, Debug, PartialEq)]
pub struct Span {
pub bounds: (u32, u32),
pub named: Option<(String, Shape)>,
}

/// The span's two halves, each a tuple inside the tuple returned.
pub fn halves(span: &Span) -> ((u32, u32), (u32, u32)) {
let (start, end) = span.bounds;
let mid = start + (end - start) / 2;
((start, mid), (mid, end))
}

/// `value` doubled: a tuple of one inside an `Option` keeps `None` apart from
/// `Some((None,))`.
pub fn doubled(value: Option<(Option<u32>,)>) -> Option<(Option<u32>,)> {
value.map(|(n,)| (n.map(|n| n * 2),))
}

/// A title, for formal speech: a tuple of one borrowed string, whose C struct one of an
/// owned string shares.
pub fn title(formal: bool) -> Option<(&'static str,)> {
formal.then_some(("Dr",))
}

/// `name`, unless empty: a tuple of one owned string.
pub fn named(name: &str) -> Option<(String,)> {
(!name.is_empty()).then(|| (name.to_string(),))
}

/// `value` lent back: a borrowed tuple of one, returned as a clone, is a tuple, not its
/// element, as only a tuple returned whole is.
pub fn lent_back(value: &(Vec<u8>,)) -> &(Vec<u8>,) {
value
}

/// `bytes` in a boxed tuple of one, which is a tuple too.
pub fn boxed_tuple(bytes: Vec<u8>) -> Box<(Vec<u8>,)> {
Box::new((bytes,))
}

/// `pair` with its sides swapped: a tuple taken by value.
pub fn swapped(pair: (String, u32)) -> (u32, String) {
(pair.1, pair.0)
}

/// Holds counters and lends them: each borrowed return is a new handle to a clone.
#[derive(Default)]
pub struct Registry {
Expand Down Expand Up @@ -275,6 +370,21 @@ pub fn end(limit: u64) -> Bound<u64> {
}
}

/// A range's two bounds, up to the end `limit` puts on it: returned whole, a tuple, not
/// the pair a `RangeBounds` parameter takes.
pub fn ends(limit: u64) -> (Bound<u64>, Bound<u64>) {
(Bound::Included(0), end(limit))
}

/// `n` if below `limit`, or else the bounds it falls outside: an error is the pair a
/// `RangeBounds` parameter takes, not a tuple.
pub fn below(n: u64, limit: u64) -> Result<u64, (Bound<u64>, Bound<u64>)> {
match n < limit {
true => Ok(n),
false => Err(ends(limit)),
}
}

/// A record of a range and a bound, which C holds after the structs they are.
#[derive(Clone, Debug, PartialEq)]
pub struct Window {
Expand Down
4 changes: 3 additions & 1 deletion ffi/fixtures/reject/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ fixtures/reject/src/lib.rs:113:2: rust2-ffi: cannot export method `Text::replace
fixtures/reject/src/lib.rs:118:2: rust2-ffi: cannot export method `Text::later`: returned object that borrows `impl std::future::Future<Output = Text<'_>>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:125:1: rust2-ffi: cannot export fn `either`: reference inside a parameter `std::option::Option<&str>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:130:1: rust2-ffi: cannot export struct `Lease`: object no export returns; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:139:1: rust2-ffi: tuple `((u8, u16), u32)` and tuple `((u8, u16, u32),)` are both `reject_tuple_tuple_u8_u16_u32` in C
fixtures/reject/src/lib.rs:139:1: note: tuple `((u8, u16, u32),)` is here
fixtures/reject/src/lib.rs:149:1: rust2-ffi: cannot export instance `Cell<std::vec::Vec<String>>`: type argument `std::vec::Vec<String>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:14:1: rust2-ffi: cannot export fn `map`: foreign type `std::collections::HashMap`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:159:2: rust2-ffi: cannot export method `Cell<u8>::nest`: instance holding an instance of a type inside it `reject_fixture::Cell<reject_fixture::Cell<u8>>`; exclude it in the config to leave it out
Expand Down Expand Up @@ -82,5 +84,5 @@ fixtures/reject/src/lib.rs:86:2: rust2-ffi: cannot export method `Text::view`: r
fixtures/reject/src/lib.rs:92:1: rust2-ffi: cannot export fn `retext`: 'static borrow `&'a str`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:92:15: note: `'a` is `'static`, as a handle outlives every call
fixtures/reject/src/lib.rs:97:1: rust2-ffi: cannot export fn `first`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:9:1: rust2-ffi: cannot export fn `pair`: tuple; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:9:1: rust2-ffi: cannot export fn `pair`: tuple of references `(&str, u8)`; exclude it in the config to leave it out
no span: rust2-ffi: rename `field@Limit::min` in the config names nothing exported
12 changes: 9 additions & 3 deletions ffi/fixtures/reject/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use std::collections::HashMap;
/// A generic type.
pub struct Wrap<T>(pub T);

/// A tuple inside an `Option`: only a returned tuple crosses, as out pointers.
pub fn pair() -> Option<(u8, u8)> {
Some((1, 2))
/// A tuple of references taken: C lends nothing inside a value.
pub fn pair(pair: (&str, u8)) -> u8 {
pair.1
}

/// Another crate's type, which has no mapping.
Expand Down Expand Up @@ -574,3 +574,9 @@ impl std::str::pattern::Pattern for Slash {
pub fn halves() -> impl Iterator<Item = &'static str> {
"a/b".split(Slash)
}

/// Two tuples whose C names run their elements together alike: both are
/// `reject_tuple_tuple_u8_u16_u32`.
pub fn mixed(a: Option<((u8, u16), u32)>, b: Option<((u8, u16, u32),)>) -> bool {
a.is_some() && b.is_some()
}
6 changes: 0 additions & 6 deletions ffi/moq/ffi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ exclude = [
"group::Producer::write_frames",
"origin::Requesting",
"server::Handshake",
"stats::Snapshot::control",
"stats::Snapshot::sessions",
"stats::Snapshot::traffic",
"time::Driver",
"track::Fetching",
"track::Resolving",
Expand Down Expand Up @@ -250,7 +247,6 @@ exclude = [
"Catalog::from_reader",
"Catalog::subscribe",
"catalog::Audio::enabled",
"catalog::Audio::ranked",
"catalog::Audio::renditions",
"catalog::Binary::tracks",
"catalog::BinaryConfig::extra",
Expand All @@ -262,7 +258,6 @@ exclude = [
"catalog::UnknownContainer",
"catalog::UnknownProjection",
"catalog::Video::enabled",
"catalog::Video::ranked",
"catalog::Video::renditions",
"container::Frame::encode",
"echo::Snapshot",
Expand Down Expand Up @@ -323,7 +318,6 @@ exclude = [
"codec::aac::Config::parse",
"codec::annexb::NalIterator",
"codec::annexb::build_prefix",
"codec::annexb::find_start_code",
"codec::annexb::from_length_prefixed",
"codec::annexb::length_prefixed_to_annexb",
"codec::av1::Error",
Expand Down
Loading