use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
pub use day_spec::Support;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
Unsupported,
Foreign(String),
Encoding,
Runtime,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Unsupported => write!(f, "unsupported on this platform"),
Error::Foreign(msg) => write!(f, "{msg}"),
Error::Encoding => write!(f, "invalid UTF-8 across the bridge"),
Error::Runtime => write!(f, "platform runtime unavailable"),
}
}
}
impl std::error::Error for Error {}
pub struct Registry<T: 'static> {
inner: day_async::TokenRegistry<Result<T, Error>>,
}
impl<T: Send + 'static> Default for Registry<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Send + 'static> Registry<T> {
#[must_use]
pub const fn new() -> Self {
Self {
inner: day_async::TokenRegistry::new(),
}
}
pub fn complete(&self, token: u64, value: Result<T, Error>) -> bool {
self.inner.complete(token, value)
}
pub fn is_pending(&self, token: u64) -> bool {
self.inner.contains(token)
}
fn cancel(&self, token: u64) -> bool {
self.inner.remove(token)
}
}
pub struct Done<T: Send + 'static> {
token: u64,
registry: &'static Registry<T>,
}
impl<T: Send + 'static> Done<T> {
pub fn new(
registry: &'static Registry<T>,
cb: impl FnOnce(Result<T, Error>) + Send + 'static,
) -> Self {
Self {
token: registry.inner.insert(cb),
registry,
}
}
#[must_use]
pub fn token(&self) -> u64 {
self.token
}
#[must_use]
pub fn into_token(self) -> u64 {
self.token
}
pub fn complete(self, value: Result<T, Error>) {
self.registry.complete(self.token, value);
}
}
pub struct Completion<T: Send + 'static> {
rx: day_async::Oneshot<Result<T, Error>>,
token: u64,
registry: &'static Registry<T>,
on_drop: Option<Box<dyn FnOnce() + Send>>,
}
impl<T: Send + 'static> Completion<T> {
#[must_use]
pub fn on_cancel(mut self, f: impl FnOnce() + Send + 'static) -> Self {
self.on_drop = Some(Box::new(f));
self
}
#[must_use]
pub fn is_ready(&self) -> bool {
self.rx.is_ready()
}
#[must_use]
pub fn token(&self) -> u64 {
self.token
}
}
impl<T: Send + 'static> Future for Completion<T> {
type Output = Result<T, Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Pin::new(&mut self.rx).poll(cx) {
Poll::Ready(Ok(v)) => Poll::Ready(v),
Poll::Ready(Err(day_async::Dropped)) => Poll::Ready(Err(Error::Runtime)),
Poll::Pending => Poll::Pending,
}
}
}
impl<T: Send + 'static> Drop for Completion<T> {
fn drop(&mut self) {
if self.registry.cancel(self.token)
&& let Some(f) = self.on_drop.take()
{
f();
}
}
}
pub fn start_async<T: Send + 'static>(
registry: &'static Registry<T>,
cb: impl FnOnce(Result<T, Error>) + Send + 'static,
call: impl FnOnce(Done<T>) -> Result<(), Error>,
) -> Result<u64, Error> {
let done = Done::new(registry, cb);
let token = done.token();
match call(done) {
Ok(()) => Ok(token),
Err(e) => {
registry.complete(token, Err(e.clone()));
Err(e)
}
}
}
pub fn start_future<T: Send + 'static>(
registry: &'static Registry<T>,
call: impl FnOnce(Done<T>) -> Result<(), Error>,
) -> Completion<T> {
let (tx, rx) = day_async::oneshot();
let done = Done::new(registry, move |v| tx.send(v));
let token = done.token();
if let Err(e) = call(done) {
registry.complete(token, Err(e));
}
Completion {
rx,
token,
registry,
on_drop: None,
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item<T> {
Value(T),
End,
Failed(Error),
}
type StreamCallback<T> = Box<dyn FnMut(Item<T>) + Send>;
struct SlotState<T> {
queue: std::collections::VecDeque<Item<T>>,
delivering: bool,
accepting: bool,
stopped: bool,
}
struct StreamSlot<T> {
state: std::sync::Mutex<SlotState<T>>,
callback: std::sync::Mutex<Option<StreamCallback<T>>>,
}
fn lock_ignoring_poison<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub struct Streams<T: 'static> {
slots: std::sync::Mutex<std::collections::BTreeMap<u64, std::sync::Arc<StreamSlot<T>>>>,
}
impl<T: Send + 'static> Default for Streams<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Send + 'static> Streams<T> {
#[must_use]
pub const fn new() -> Self {
Self {
slots: std::sync::Mutex::new(std::collections::BTreeMap::new()),
}
}
fn insert(&self, cb: impl FnMut(Item<T>) + Send + 'static) -> u64 {
let token = day_async::next_token();
let slot = std::sync::Arc::new(StreamSlot {
state: std::sync::Mutex::new(SlotState {
queue: std::collections::VecDeque::new(),
delivering: false,
accepting: true,
stopped: false,
}),
callback: std::sync::Mutex::new(Some(Box::new(cb))),
});
lock_ignoring_poison(&self.slots).insert(token, slot);
token
}
pub fn deliver(&self, token: u64, status: i32, outcome: Result<T, Error>) -> bool {
let item = match (status, outcome) {
(0, Ok(v)) => Item::Value(v),
(2, _) => Item::End,
(_, Err(e)) => Item::Failed(e),
(_, Ok(_)) => Item::Failed(Error::Runtime),
};
self.push(token, item)
}
pub fn emit(&self, token: u64, value: T) -> bool {
self.push(token, Item::Value(value))
}
pub fn end(&self, token: u64) -> bool {
self.push(token, Item::End)
}
pub fn fail(&self, token: u64, error: Error) -> bool {
self.push(token, Item::Failed(error))
}
pub fn is_open(&self, token: u64) -> bool {
lock_ignoring_poison(&self.slots).contains_key(&token)
}
pub fn stop(&self, token: u64) -> bool {
let Some(slot) = lock_ignoring_poison(&self.slots).remove(&token) else {
return false;
};
{
let mut st = lock_ignoring_poison(&slot.state);
st.stopped = true;
st.accepting = false;
st.queue.clear();
}
if let Ok(mut cb) = slot.callback.try_lock() {
*cb = None;
}
true
}
fn push(&self, token: u64, item: Item<T>) -> bool {
let terminal = !matches!(item, Item::Value(_));
let slot = {
let mut map = lock_ignoring_poison(&self.slots);
if terminal {
map.remove(&token)
} else {
map.get(&token).cloned()
}
};
let Some(slot) = slot else {
return false;
};
{
let mut st = lock_ignoring_poison(&slot.state);
if !st.accepting {
return false;
}
st.queue.push_back(item);
if terminal {
st.accepting = false;
}
if st.delivering {
return true;
}
st.delivering = true;
}
loop {
let next = {
let mut st = lock_ignoring_poison(&slot.state);
if st.stopped {
st.queue.clear();
}
if let Some(item) = st.queue.pop_front() {
item
} else {
st.delivering = false;
break;
}
};
let ends = !matches!(next, Item::Value(_));
let mut cb = lock_ignoring_poison(&slot.callback);
if let Some(f) = cb.as_mut() {
f(next);
}
if ends || lock_ignoring_poison(&slot.state).stopped {
*cb = None;
}
}
true
}
}
pub struct Emit<T: Send + 'static> {
token: u64,
streams: &'static Streams<T>,
}
impl<T: Send + 'static> Clone for Emit<T> {
fn clone(&self) -> Self {
Self {
token: self.token,
streams: self.streams,
}
}
}
impl<T: Send + 'static> Emit<T> {
pub fn new(streams: &'static Streams<T>, cb: impl FnMut(Item<T>) + Send + 'static) -> Self {
Self {
token: streams.insert(cb),
streams,
}
}
#[must_use]
pub fn token(&self) -> u64 {
self.token
}
#[must_use]
pub fn into_token(self) -> u64 {
self.token
}
pub fn emit(&self, value: T) -> bool {
self.streams.emit(self.token, value)
}
pub fn end(&self) -> bool {
self.streams.end(self.token)
}
#[must_use]
pub fn fail(&self, error: Error) -> bool {
self.streams.fail(self.token, error)
}
#[must_use]
pub fn is_open(&self) -> bool {
self.streams.is_open(self.token)
}
}
pub fn start_stream<T: Send + 'static>(
streams: &'static Streams<T>,
cb: impl FnMut(Item<T>) + Send + 'static,
call: impl FnOnce(Emit<T>) -> Result<(), Error>,
) -> Result<u64, Error> {
let emit = Emit::new(streams, cb);
let token = emit.token();
match call(emit) {
Ok(()) => Ok(token),
Err(e) => {
streams.fail(token, e.clone());
Err(e)
}
}
}
pub fn guard(f: impl FnOnce()) {
day_spec::ffi_guard::contain((), f);
}
#[doc(hidden)]
#[expect(
clippy::same_length_and_capacity,
reason = "the safety contract is a buffer allocated with capacity `len` and filled with `len` bytes"
)]
pub unsafe fn __take_wasm(ptr: *mut u8, len: usize) -> Vec<u8> {
if ptr.is_null() || len == 0 {
return Vec::new();
}
unsafe { Vec::from_raw_parts(ptr, len, len) }
}
#[cfg(all(target_os = "linux", target_env = "ohos"))]
pub mod arkts {
use std::ffi::{c_char, c_int, c_void};
#[repr(C)]
pub struct Arg {
pub kind: i32,
pub i: i64,
pub f: f64,
pub ptr: *const u8,
pub len: usize,
}
impl Arg {
fn plain(kind: i32, i: i64, f: f64) -> Self {
Self {
kind,
i,
f,
ptr: std::ptr::null(),
len: 0,
}
}
#[must_use]
pub fn bool(v: bool) -> Self {
Self::plain(0, i64::from(v), 0.0)
}
#[must_use]
pub fn i32(v: i32) -> Self {
Self::plain(1, i64::from(v), 0.0)
}
#[must_use]
pub fn i64(v: i64) -> Self {
Self::plain(2, v, 0.0)
}
#[must_use]
pub fn f64(v: f64) -> Self {
Self::plain(3, 0, v)
}
#[must_use]
pub fn str(v: &str) -> Self {
Self {
kind: 4,
i: 0,
f: 0.0,
ptr: v.as_ptr(),
len: v.len(),
}
}
#[must_use]
pub fn bytes(v: &[u8]) -> Self {
Self {
kind: 5,
i: 0,
f: 0.0,
ptr: v.as_ptr(),
len: v.len(),
}
}
}
type InvokeFn = unsafe extern "C" fn(*const c_char, *const Arg, usize, u64, *mut Arg) -> c_int;
type OnJsThreadFn = unsafe extern "C" fn() -> c_int;
unsafe extern "C" {
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
fn dladdr(addr: *const c_void, info: *mut DlInfo) -> c_int;
fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void;
}
#[repr(C)]
#[expect(
clippy::struct_field_names,
reason = "the fields keep the names C's `Dl_info` gives them"
)]
struct DlInfo {
dli_fname: *const c_char,
dli_fbase: *mut c_void,
dli_sname: *const c_char,
dli_saddr: *mut c_void,
}
const RTLD_NOW: c_int = 2;
const RTLD_NOLOAD: c_int = 4;
#[must_use]
pub fn lookup(name: &std::ffi::CStr) -> *mut c_void {
let global = unsafe { dlsym(std::ptr::null_mut(), name.as_ptr()) };
if !global.is_null() {
return global;
}
let own = own_library();
if own.is_null() {
return std::ptr::null_mut();
}
unsafe { dlsym(own, name.as_ptr()) }
}
fn own_library() -> *mut c_void {
static HANDLE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
*HANDLE.get_or_init(|| {
let mut info = DlInfo {
dli_fname: std::ptr::null(),
dli_fbase: std::ptr::null_mut(),
dli_sname: std::ptr::null(),
dli_saddr: std::ptr::null_mut(),
};
let found = unsafe { dladdr(lookup as *const c_void, &raw mut info) } != 0;
if !found || info.dli_fname.is_null() {
return 0;
}
unsafe { dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD) as usize }
}) as *mut c_void
}
pub fn invoke(symbol: &str, args: &[Arg], done: u64) -> Result<(), super::Error> {
invoke_value(symbol, args, done).map(|_| ())
}
pub fn invoke_value(symbol: &str, args: &[Arg], done: u64) -> Result<Arg, super::Error> {
let entry = lookup(c"day_arkui_bridge_invoke");
if entry.is_null() {
return Err(super::Error::Runtime);
}
let Ok(name) = std::ffi::CString::new(symbol) else {
return Err(super::Error::Encoding);
};
let mut ret = Arg::plain(-1, 0, 0.0);
let invoke: InvokeFn = unsafe { std::mem::transmute(entry) };
match unsafe { invoke(name.as_ptr(), args.as_ptr(), args.len(), done, &raw mut ret) } {
0 => Ok(ret),
2 => Err(super::Error::Runtime),
_ => Err(super::Error::Foreign(format!("{symbol} failed"))),
}
}
#[must_use]
pub fn on_js_thread() -> bool {
let entry = lookup(c"day_arkui_bridge_on_js_thread");
if entry.is_null() {
return false;
}
let f: OnJsThreadFn = unsafe { std::mem::transmute(entry) };
unsafe { f() != 0 }
}
#[doc(hidden)]
#[must_use]
pub unsafe fn __bytes(ptr: *const u8, len: usize) -> Vec<u8> {
if ptr.is_null() || len == 0 {
return Vec::new();
}
unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()
}
}
#[macro_export]
macro_rules! bridge {
($($body:tt)*) => {
$crate::__bridge_generated!();
};
}
#[doc(hidden)]
pub use day_macros::bridge_generated as __bridge_generated;
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
use std::task::{Wake, Waker};
fn block_on<F: Future>(mut fut: F) -> F::Output {
struct Unpark(std::thread::Thread);
impl Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
let mut cx = Context::from_waker(&waker);
let mut fut = unsafe { Pin::new_unchecked(&mut fut) };
loop {
if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
return v;
}
std::thread::park();
}
}
static REG: Registry<bool> = Registry::new();
#[test]
fn a_rust_arm_completes_and_the_future_resolves() {
let fut = start_future(®, |done| {
std::thread::spawn(move || done.complete(Ok(true)));
Ok(())
});
assert_eq!(block_on(fut), Ok(true));
}
#[test]
fn a_foreign_style_token_round_trip() {
let fut = start_future(®, |done| {
let token = done.into_token();
assert!(REG.is_pending(token));
std::thread::spawn(move || {
assert!(REG.complete(token, Ok(false)));
assert!(!REG.complete(token, Ok(true)), "at most once");
});
Ok(())
});
assert_eq!(block_on(fut), Ok(false));
}
#[test]
fn an_arm_that_fails_to_start_fails_the_future_with_its_own_error() {
let fut = start_future(®, |_done| Err(Error::Foreign("no engine".into())));
assert_eq!(block_on(fut), Err(Error::Foreign("no engine".into())));
}
#[test]
fn an_arm_that_returns_ok_without_completing_leaves_the_future_pending() {
let fut = start_future(®, |done| {
let _ = done.into_token();
Ok(())
});
assert!(!fut.is_ready());
}
#[test]
fn dropping_the_future_cancels_the_slot_and_runs_the_hook() {
let hook = Arc::new(Mutex::new(false));
let h = hook.clone();
let mut token = 0;
let fut = start_future(®, |done| {
token = done.into_token();
Ok(())
})
.on_cancel(move || *h.lock().unwrap() = true);
assert!(REG.is_pending(token));
drop(fut);
assert!(!REG.is_pending(token));
assert!(*hook.lock().unwrap());
assert!(
!REG.complete(token, Ok(true)),
"a late completion is a no-op"
);
}
#[test]
fn the_callback_form_fires_exactly_once_on_start_failure() {
let hits = Arc::new(Mutex::new(0));
let h = hits.clone();
let r = start_async(
®,
move |v| {
assert_eq!(v, Err(Error::Runtime));
*h.lock().unwrap() += 1;
},
|_done| Err(Error::Runtime),
);
assert_eq!(r, Err(Error::Runtime));
assert_eq!(*hits.lock().unwrap(), 1);
let token = start_async(®, |_| {}, |_done| Ok(())).expect("started");
assert!(REG.is_pending(token), "the token names the live slot");
}
static STREAMS: Streams<u32> = Streams::new();
type Seen = Arc<Mutex<Vec<Item<u32>>>>;
fn collector() -> (Seen, impl FnMut(Item<u32>) + Send + 'static) {
let seen: Seen = Arc::new(Mutex::new(Vec::new()));
let s = seen.clone();
(seen, move |item| s.lock().unwrap().push(item))
}
#[test]
fn a_stream_delivers_in_order_then_ends_once() {
let (seen, cb) = collector();
let token = start_stream(&STREAMS, cb, |emit| {
let token = emit.into_token();
std::thread::spawn(move || {
for v in 0..100 {
assert!(STREAMS.emit(token, v));
}
assert!(STREAMS.end(token));
assert!(!STREAMS.emit(token, 999), "nothing after the end");
assert!(!STREAMS.end(token), "the end is delivered once");
})
.join()
.unwrap();
Ok(())
})
.expect("started");
let seen = seen.lock().unwrap();
assert_eq!(seen.len(), 101);
assert!(
seen[..100]
.iter()
.enumerate()
.all(|(i, v)| *v == Item::Value(i as u32))
);
assert_eq!(seen[100], Item::End);
assert!(!STREAMS.is_open(token));
}
#[test]
fn pushes_from_many_threads_reach_the_consumer_serially() {
let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (b, c) = (busy.clone(), count.clone());
let emit = Emit::new(&STREAMS, move |_item| {
assert!(
!b.swap(true, std::sync::atomic::Ordering::SeqCst),
"two deliveries overlapped"
);
std::thread::yield_now();
c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
b.store(false, std::sync::atomic::Ordering::SeqCst);
});
let workers: Vec<_> = (0..8)
.map(|_| {
let e = emit.clone();
std::thread::spawn(move || {
for v in 0..200 {
e.emit(v);
}
})
})
.collect();
for w in workers {
w.join().unwrap();
}
emit.end();
assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 8 * 200 + 1);
}
#[test]
fn the_consumer_may_stop_its_own_stream_from_inside_the_callback() {
let token_cell = Arc::new(Mutex::new(0u64));
let seen = Arc::new(Mutex::new(Vec::new()));
let (t, s) = (token_cell.clone(), seen.clone());
let emit = Emit::new(&STREAMS, move |item| {
s.lock().unwrap().push(item.clone());
if item == Item::Value(2) {
assert!(STREAMS.stop(*t.lock().unwrap()));
}
});
*token_cell.lock().unwrap() = emit.token();
for v in 0..5 {
emit.emit(v);
}
assert!(!emit.end(), "stopped streams refuse the end");
assert_eq!(
*seen.lock().unwrap(),
vec![Item::Value(0), Item::Value(1), Item::Value(2)]
);
assert!(!emit.is_open());
}
#[test]
fn a_stream_that_fails_to_start_delivers_that_failure_once() {
let (seen, cb) = collector();
let r = start_stream(&STREAMS, cb, |_emit| Err(Error::Foreign("no radio".into())));
assert_eq!(r, Err(Error::Foreign("no radio".into())));
assert_eq!(
*seen.lock().unwrap(),
vec![Item::Failed(Error::Foreign("no radio".into()))]
);
}
#[test]
fn deliver_maps_export_statuses() {
let (seen, cb) = collector();
let emit = Emit::new(&STREAMS, cb);
let token = emit.token();
assert!(STREAMS.deliver(token, 0, Ok(7)));
assert!(STREAMS.deliver(token, 0, Err(Error::Encoding)));
assert!(
!STREAMS.deliver(token, 2, Err(Error::Runtime)),
"already failed"
);
assert_eq!(
*seen.lock().unwrap(),
vec![Item::Value(7), Item::Failed(Error::Encoding)]
);
}
}