diff --git a/CHANGELOG.md b/CHANGELOG.md index aa2b630..b6e49c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +#### v0.11.0-kixelated.7+v0.32.2 + +---- +- C: Render `Duration` as `_duration`, an `int64_t` count of nanoseconds like the C++ + binding's +- Core: Fail on a negative `Duration`, which reached Rust as a huge one, and on one from Rust + longer than `std::chrono::nanoseconds` holds, which overflowed + #### v0.11.0-kixelated.6+v0.32.2 ---- diff --git a/Cargo.lock b/Cargo.lock index f4ae84a..b466b7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -874,7 +874,7 @@ dependencies = [ [[package]] name = "uniffi-bindgen-cpp" -version = "0.11.0-kixelated.6+v0.32.2" +version = "0.11.0-kixelated.7+v0.32.2" dependencies = [ "anyhow", "askama 0.13.1", diff --git a/README.md b/README.md index 2273924..bad0d9a 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ the `error_style = "expected"`, `strip_type_prefix`, and `strip_function_prefix` collide with upstream's: ```bash -cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.6+v0.32.2 +cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.7+v0.32.2 ``` # How to generate bindings @@ -90,6 +90,9 @@ handle is `my_object *`, released with `my_object_free`. The rest follows from a the matching `_free` (`_string_free` for strings). * Optional strings, objects, and structs are pointers that are NULL when absent; optional scalars are `{ has_value, value }` structs. Bytes, lists, and maps are pointer and length structs. +* A duration is `_duration`, an `int64_t` count of nanoseconds like the C++ + binding's. Passing a negative one, or receiving one longer than `INT64_MAX` nanoseconds (about + 292 years), aborts. * An async call takes a callback and `user_data` and returns a `_task *`. The callback runs once on the dispatcher with the result, which it owns, unless the dispatcher refuses the work or has shut down, which abandons the call. Free every task: freeing a pending @@ -99,7 +102,7 @@ handle is `my_object *`, released with `my_object_free`. The rest follows from a host's own, which receives `_work *` items to run with `_work_run`. The C backend refuses what it cannot render faithfully, such as callback interfaces, custom and -external types, timestamps, durations, and exported traits other than `Display` on errors. +external types, timestamps, and exported traits other than `Display` on errors. # Configuration options diff --git a/bindgen/Cargo.toml b/bindgen/Cargo.toml index 4c060cc..6f009c9 100644 --- a/bindgen/Cargo.toml +++ b/bindgen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "uniffi-bindgen-cpp" -version = "0.11.0-kixelated.6+v0.32.2" +version = "0.11.0-kixelated.7+v0.32.2" edition = "2021" [dependencies] diff --git a/bindgen/src/bindings/c/gen_c.rs b/bindgen/src/bindings/c/gen_c.rs index 63a700e..43bd3b9 100644 --- a/bindgen/src/bindings/c/gen_c.rs +++ b/bindgen/src/bindings/c/gen_c.rs @@ -402,6 +402,7 @@ impl<'a> Gen<'a> { Type::Float32 => scalar("float", "f32"), Type::Float64 => scalar("double", "f64"), Type::Boolean => scalar("bool", "bool"), + Type::Duration => scalar(&format!("{ns}_duration"), "duration"), Type::String => (Kind::String, "const char *".into(), "string".into()), Type::Bytes => (Kind::Bytes, format!("{ns}_bytes"), "bytes".into()), Type::Record { name, .. } => { @@ -462,7 +463,7 @@ impl<'a> Gen<'a> { ) } Type::Box { inner_type } => return self.ctype(inner_type), - Type::Timestamp | Type::Duration | Type::Set { .. } | Type::Custom { .. } => { + Type::Timestamp | Type::Set { .. } | Type::Custom { .. } => { bail!("the C backend does not support `{cpp}` yet") } Type::CallbackInterface { name, .. } => { @@ -505,6 +506,16 @@ impl<'a> Gen<'a> { let types: Vec = self.types.values().cloned().collect(); + // A typedef, so the unit shows wherever a duration is declared. Nanoseconds in an + // int64_t mirror the C++ binding's `std::chrono::nanoseconds`. + if let Some(ct) = types.iter().find(|ct| matches!(ct.ty, Type::Duration)) { + self.claim(&ct.c)?; + h.push_str(&line_doc( + "A duration in nanoseconds. Passing a negative one, or receiving one past INT64_MAX, aborts.", + )); + writeln!(h, "typedef int64_t {};\n", ct.c)?; + } + // Flat enums first: C cannot forward-declare an enum. for ct in types.iter().filter(|ct| matches!(ct.kind, Kind::FlatEnum)) { self.render_flat_enum(h, ct)?; @@ -1248,6 +1259,12 @@ impl<'a> Gen<'a> { decl(&format!("{field} &"), "value") ); match &ct.kind { + // The C++ converters refuse a negative duration and one past INT64_MAX nanoseconds. + Kind::Scalar if matches!(ct.ty, Type::Duration) => { + writeln!(out, "{to} {{\n return value.count();\n}}\n")?; + writeln!(out, "{from} {{\n return {}(value);\n}}\n", ct.cpp)?; + writeln!(out, "{free} {{\n (void)value;\n}}\n")?; + } Kind::Scalar => { writeln!(out, "{to} {{\n return value;\n}}\n")?; writeln!(out, "{from} {{\n return value;\n}}\n")?; diff --git a/bindgen/src/bindings/cpp/templates/duration_helper.cpp b/bindgen/src/bindings/cpp/templates/duration_helper.cpp index 9bb69bc..6f941b7 100644 --- a/bindgen/src/bindings/cpp/templates/duration_helper.cpp +++ b/bindgen/src/bindings/cpp/templates/duration_helper.cpp @@ -23,16 +23,30 @@ RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { stream >> secs; stream >> nanos; - return std::chrono::seconds(secs) + std::chrono::nanoseconds(nanos); + // Rust's Duration reaches about 584 billion years, far past what int64_t nanoseconds hold. + constexpr auto max = {{ type_name }}::max(); + constexpr auto max_secs = std::chrono::duration_cast(max); + constexpr auto max_nanos = static_cast((max - max_secs).count()); + if (secs > static_cast(max_secs.count()) || + (secs == static_cast(max_secs.count()) && nanos > max_nanos)) { + {% call macros::fail("Duration does not fit in int64_t nanoseconds") %} + } + + return std::chrono::seconds(static_cast(secs)) + std::chrono::nanoseconds(nanos); } void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - auto secs = std::chrono::duration_cast>(val); + auto secs = std::chrono::duration_cast(val); auto nanos = (val - secs).count(); - stream << secs.count() << static_cast(nanos); + stream << static_cast(secs.count()) << static_cast(nanos); } -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &) { +uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &val) { + // Rust's Duration is unsigned. Every lower sizes its value before allocating or writing it, + // so refusing here leaks nothing when the refusal throws. + if (val.count() < 0) { + {% call macros::fail("Duration must not be negative") %} + } return static_cast(sizeof(uint64_t) + sizeof(uint32_t)); } diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 989ba31..5671d9a 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -213,6 +213,16 @@ endmacro(c_test_case) c_test_case(c_api) c_test_case(c_dispatcher) +# A duration Rust cannot represent, or C cannot, aborts rather than wrapping. +add_test(NAME c-negative-duration-test COMMAND c_api-test negative-duration) +set_tests_properties(c-negative-duration-test PROPERTIES + TIMEOUT 30 + PASS_REGULAR_EXPRESSION "uniffi: Duration must not be negative") +add_test(NAME c-long-duration-test COMMAND c_api-test long-duration) +set_tests_properties(c-long-duration-test PROPERTIES + TIMEOUT 30 + PASS_REGULAR_EXPRESSION "uniffi: Duration does not fit in int64_t nanoseconds") + # The C backend refuses what it cannot render instead of emitting half of it. add_test(NAME c-refuses-callbacks-test COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX} diff --git a/cpp-tests/tests/c_api/main.c b/cpp-tests/tests/c_api/main.c index e14c989..1e65995 100644 --- a/cpp-tests/tests/c_api/main.c +++ b/cpp-tests/tests/c_api/main.c @@ -3,6 +3,8 @@ #include +#include +#include #include static int streq(const char *a, const char *b) { @@ -209,6 +211,40 @@ static void scalars(void) { capi_string_free(text); } +/* Durations cross as nanoseconds, split into Rust's seconds and nanoseconds on the way. */ +static void durations(void) { + const capi_duration laps[] = {1, 1000000001, INT64_MAX}; + capi_optional_duration delay; + capi_timer timer = capi_timer_default(); + capi_timer *echo; + + CHECK(capi_twice(0) == 0); + CHECK(capi_twice(1234567891) == 2469135782); + CHECK(capi_make_duration(9223372036, 854775807) == INT64_MAX); + + delay.has_value = false; + delay.value = 0; + CHECK(!capi_halve(delay).has_value); + delay.has_value = true; + delay.value = 3000000001; + delay = capi_halve(delay); + CHECK(delay.has_value && delay.value == 1500000000); + + CHECK(timer.period == 0 && !timer.delay.has_value && timer.laps.len == 0); + timer.period = 2500000000; + timer.delay.has_value = true; + timer.delay.value = 7; + timer.laps.data = laps; + timer.laps.len = 3; + echo = capi_echo_timer(&timer); + CHECK(echo->period == 2500000000); + CHECK(echo->delay.has_value && echo->delay.value == 7); + CHECK(echo->laps.len == 3); + CHECK(echo->laps.data[0] == 1 && echo->laps.data[1] == 1000000001); + CHECK(echo->laps.data[2] == INT64_MAX); + capi_timer_free(echo); +} + static void errors(void) { capi_error *error; capi_flat_error *flat; @@ -448,11 +484,28 @@ static void async_calls(void) { test_latch_free(r.done); } -int main(void) { +static void exit_on_abort(int sig) { + (void)sig; + _Exit(0); +} + +int main(int argc, char **argv) { + /* Each aborts as expected; its test matches the message printed before the abort. */ + if (argc > 1) { + signal(SIGABRT, exit_on_abort); + if (strcmp(argv[1], "negative-duration") == 0) { + (void)capi_twice(-1); + } else if (strcmp(argv[1], "long-duration") == 0) { + (void)capi_make_duration(9223372036, 854775808); + } + return 1; + } + defaults(); records(); enums(); scalars(); + durations(); errors(); objects(); async_calls(); diff --git a/cpp-tests/tests/chronological/main.cpp b/cpp-tests/tests/chronological/main.cpp index 744443c..e6d7b55 100644 --- a/cpp-tests/tests/chronological/main.cpp +++ b/cpp-tests/tests/chronological/main.cpp @@ -127,6 +127,9 @@ int main() { chronological::return_duration(std::chrono::nanoseconds::max()) ); + // Rust's Duration is unsigned. + EXPECT_EXCEPTION(chronological::return_duration(-1ns), std::runtime_error); + test_string_timestamps(); auto before = std::chrono::system_clock::now(); diff --git a/fixtures/c-api/src/lib.rs b/fixtures/c-api/src/lib.rs index f87309b..97e2862 100644 --- a/fixtures/c-api/src/lib.rs +++ b/fixtures/c-api/src/lib.rs @@ -1,6 +1,6 @@ //! Every construct the C backend renders: objects, records with defaults, flat and data -//! enums, errors with and without `Display`, bytes, optionals, lists, maps, and async calls -//! that complete, fail, or stay pending until cancelled. +//! enums, errors with and without `Display`, bytes, durations, optionals, lists, maps, and +//! async calls that complete, fail, or stay pending until cancelled. use std::{ collections::{HashMap, VecDeque}, @@ -11,6 +11,7 @@ use std::{ Arc, Mutex, }, task::{Context, Poll, Waker}, + time::Duration, }; uniffi::setup_scaffolding!("capi"); @@ -333,6 +334,38 @@ pub fn capi_flat_fail(gone: bool) -> Result<(), CapiFlatError> { }) } +/// Durations in every position: a field, an optional, and a list. +#[derive(Clone, Debug, PartialEq, uniffi::Record)] +pub struct CapiTimer { + pub period: Duration, + #[uniffi(default = None)] + pub delay: Option, + #[uniffi(default = [])] + pub laps: Vec, +} + +#[uniffi::export] +pub fn capi_echo_timer(timer: CapiTimer) -> CapiTimer { + timer +} + +#[uniffi::export] +pub fn capi_twice(duration: Duration) -> Duration { + duration * 2 +} + +/// Half of `delay`, or none. +#[uniffi::export] +pub fn capi_halve(delay: Option) -> Option { + delay.map(|delay| delay / 2) +} + +/// Builds a duration on the Rust side, which may be longer than C can hold. +#[uniffi::export] +pub fn capi_make_duration(secs: u64, nanos: u32) -> Duration { + Duration::new(secs, nanos) +} + /// Ready on its first poll. #[uniffi::export] pub async fn capi_sum(values: Vec) -> u64 {