1use std::fmt;
31use std::future::Future;
32use std::pin::Pin;
33use std::task::{Context, Poll};
34
35pub use day_process::Support;
38
39#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum Error {
42 Unsupported,
44 Foreign(String),
47 Encoding,
49 Runtime,
52}
53
54impl fmt::Display for Error {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Error::Unsupported => write!(f, "unsupported on this platform"),
58 Error::Foreign(msg) => write!(f, "{msg}"),
59 Error::Encoding => write!(f, "invalid UTF-8 across the bridge"),
60 Error::Runtime => write!(f, "platform runtime unavailable"),
61 }
62 }
63}
64
65impl std::error::Error for Error {}
66
67pub struct Registry<T: 'static> {
75 inner: day_async::TokenRegistry<Result<T, Error>>,
76}
77
78impl<T: Send + 'static> Default for Registry<T> {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84impl<T: Send + 'static> Registry<T> {
85 #[must_use]
87 pub const fn new() -> Self {
88 Self {
89 inner: day_async::TokenRegistry::new(),
90 }
91 }
92
93 pub fn complete(&self, token: u64, value: Result<T, Error>) -> bool {
96 self.inner.complete(token, value)
97 }
98
99 pub fn is_pending(&self, token: u64) -> bool {
101 self.inner.contains(token)
102 }
103
104 fn cancel(&self, token: u64) -> bool {
106 self.inner.remove(token)
107 }
108}
109
110pub struct Done<T: Send + 'static> {
116 token: u64,
117 registry: &'static Registry<T>,
118}
119
120impl<T: Send + 'static> Done<T> {
121 pub fn new(
123 registry: &'static Registry<T>,
124 cb: impl FnOnce(Result<T, Error>) + Send + 'static,
125 ) -> Self {
126 Self {
127 token: registry.inner.insert(cb),
128 registry,
129 }
130 }
131
132 #[must_use]
134 pub fn token(&self) -> u64 {
135 self.token
136 }
137
138 #[must_use]
141 pub fn into_token(self) -> u64 {
142 self.token
143 }
144
145 pub fn complete(self, value: Result<T, Error>) {
147 self.registry.complete(self.token, value);
148 }
149}
150
151pub struct Completion<T: Send + 'static> {
158 rx: day_async::Oneshot<Result<T, Error>>,
159 token: u64,
160 registry: &'static Registry<T>,
161 on_drop: Option<Box<dyn FnOnce() + Send>>,
162}
163
164impl<T: Send + 'static> Completion<T> {
165 #[must_use]
167 pub fn on_cancel(mut self, f: impl FnOnce() + Send + 'static) -> Self {
168 self.on_drop = Some(Box::new(f));
169 self
170 }
171
172 #[must_use]
174 pub fn is_ready(&self) -> bool {
175 self.rx.is_ready()
176 }
177
178 #[must_use]
180 pub fn token(&self) -> u64 {
181 self.token
182 }
183}
184
185impl<T: Send + 'static> Future for Completion<T> {
186 type Output = Result<T, Error>;
187
188 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
189 match Pin::new(&mut self.rx).poll(cx) {
190 Poll::Ready(Ok(v)) => Poll::Ready(v),
191 Poll::Ready(Err(day_async::Dropped)) => Poll::Ready(Err(Error::Runtime)),
192 Poll::Pending => Poll::Pending,
193 }
194 }
195}
196
197impl<T: Send + 'static> Drop for Completion<T> {
198 fn drop(&mut self) {
199 if self.registry.cancel(self.token)
200 && let Some(f) = self.on_drop.take()
201 {
202 f();
203 }
204 }
205}
206
207pub fn start_async<T: Send + 'static>(
218 registry: &'static Registry<T>,
219 cb: impl FnOnce(Result<T, Error>) + Send + 'static,
220 call: impl FnOnce(Done<T>) -> Result<(), Error>,
221) -> Result<u64, Error> {
222 let done = Done::new(registry, cb);
223 let token = done.token();
224 match call(done) {
225 Ok(()) => Ok(token),
226 Err(e) => {
227 registry.complete(token, Err(e.clone()));
228 Err(e)
229 }
230 }
231}
232
233pub fn start_future<T: Send + 'static>(
235 registry: &'static Registry<T>,
236 call: impl FnOnce(Done<T>) -> Result<(), Error>,
237) -> Completion<T> {
238 let (tx, rx) = day_async::oneshot();
239 let done = Done::new(registry, move |v| tx.send(v));
240 let token = done.token();
241 if let Err(e) = call(done) {
242 registry.complete(token, Err(e));
245 }
246 Completion {
247 rx,
248 token,
249 registry,
250 on_drop: None,
251 }
252}
253
254#[derive(Clone, Debug, PartialEq, Eq)]
261pub enum Item<T> {
262 Value(T),
263 End,
264 Failed(Error),
265}
266
267type StreamCallback<T> = Box<dyn FnMut(Item<T>) + Send>;
268
269struct SlotState<T> {
270 queue: std::collections::VecDeque<Item<T>>,
271 delivering: bool,
273 accepting: bool,
275 stopped: bool,
277}
278
279struct StreamSlot<T> {
280 state: std::sync::Mutex<SlotState<T>>,
281 callback: std::sync::Mutex<Option<StreamCallback<T>>>,
282}
283
284fn lock_ignoring_poison<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
285 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
286}
287
288pub struct Streams<T: 'static> {
301 slots: std::sync::Mutex<std::collections::BTreeMap<u64, std::sync::Arc<StreamSlot<T>>>>,
302}
303
304impl<T: Send + 'static> Default for Streams<T> {
305 fn default() -> Self {
306 Self::new()
307 }
308}
309
310impl<T: Send + 'static> Streams<T> {
311 #[must_use]
313 pub const fn new() -> Self {
314 Self {
315 slots: std::sync::Mutex::new(std::collections::BTreeMap::new()),
316 }
317 }
318
319 fn insert(&self, cb: impl FnMut(Item<T>) + Send + 'static) -> u64 {
320 let token = day_async::next_token();
321 let slot = std::sync::Arc::new(StreamSlot {
322 state: std::sync::Mutex::new(SlotState {
323 queue: std::collections::VecDeque::new(),
324 delivering: false,
325 accepting: true,
326 stopped: false,
327 }),
328 callback: std::sync::Mutex::new(Some(Box::new(cb))),
329 });
330 lock_ignoring_poison(&self.slots).insert(token, slot);
331 token
332 }
333
334 pub fn deliver(&self, token: u64, status: i32, outcome: Result<T, Error>) -> bool {
337 let item = match (status, outcome) {
338 (0, Ok(v)) => Item::Value(v),
339 (2, _) => Item::End,
340 (_, Err(e)) => Item::Failed(e),
341 (_, Ok(_)) => Item::Failed(Error::Runtime),
342 };
343 self.push(token, item)
344 }
345
346 pub fn emit(&self, token: u64, value: T) -> bool {
348 self.push(token, Item::Value(value))
349 }
350
351 pub fn end(&self, token: u64) -> bool {
353 self.push(token, Item::End)
354 }
355
356 pub fn fail(&self, token: u64, error: Error) -> bool {
358 self.push(token, Item::Failed(error))
359 }
360
361 pub fn is_open(&self, token: u64) -> bool {
363 lock_ignoring_poison(&self.slots).contains_key(&token)
364 }
365
366 pub fn stop(&self, token: u64) -> bool {
369 let Some(slot) = lock_ignoring_poison(&self.slots).remove(&token) else {
370 return false;
371 };
372 {
373 let mut st = lock_ignoring_poison(&slot.state);
374 st.stopped = true;
375 st.accepting = false;
376 st.queue.clear();
377 }
378 if let Ok(mut cb) = slot.callback.try_lock() {
381 *cb = None;
382 }
383 true
384 }
385
386 fn push(&self, token: u64, item: Item<T>) -> bool {
387 let terminal = !matches!(item, Item::Value(_));
388 let slot = {
389 let mut map = lock_ignoring_poison(&self.slots);
390 if terminal {
391 map.remove(&token)
392 } else {
393 map.get(&token).cloned()
394 }
395 };
396 let Some(slot) = slot else {
397 return false;
398 };
399 {
400 let mut st = lock_ignoring_poison(&slot.state);
401 if !st.accepting {
402 return false;
403 }
404 st.queue.push_back(item);
405 if terminal {
406 st.accepting = false;
407 }
408 if st.delivering {
409 return true;
410 }
411 st.delivering = true;
412 }
413 loop {
414 let next = {
415 let mut st = lock_ignoring_poison(&slot.state);
416 if st.stopped {
417 st.queue.clear();
418 }
419 if let Some(item) = st.queue.pop_front() {
420 item
421 } else {
422 st.delivering = false;
423 break;
424 }
425 };
426 let ends = !matches!(next, Item::Value(_));
427 let mut cb = lock_ignoring_poison(&slot.callback);
428 if let Some(f) = cb.as_mut() {
429 f(next);
430 }
431 if ends || lock_ignoring_poison(&slot.state).stopped {
432 *cb = None;
433 }
434 }
435 true
436 }
437}
438
439pub struct Emit<T: Send + 'static> {
443 token: u64,
444 streams: &'static Streams<T>,
445}
446
447impl<T: Send + 'static> Clone for Emit<T> {
448 fn clone(&self) -> Self {
449 Self {
450 token: self.token,
451 streams: self.streams,
452 }
453 }
454}
455
456impl<T: Send + 'static> Emit<T> {
457 pub fn new(streams: &'static Streams<T>, cb: impl FnMut(Item<T>) + Send + 'static) -> Self {
459 Self {
460 token: streams.insert(cb),
461 streams,
462 }
463 }
464
465 #[must_use]
467 pub fn token(&self) -> u64 {
468 self.token
469 }
470
471 #[must_use]
474 pub fn into_token(self) -> u64 {
475 self.token
476 }
477
478 pub fn emit(&self, value: T) -> bool {
480 self.streams.emit(self.token, value)
481 }
482
483 pub fn end(&self) -> bool {
485 self.streams.end(self.token)
486 }
487
488 #[must_use]
490 pub fn fail(&self, error: Error) -> bool {
491 self.streams.fail(self.token, error)
492 }
493
494 #[must_use]
496 pub fn is_open(&self) -> bool {
497 self.streams.is_open(self.token)
498 }
499}
500
501pub fn start_stream<T: Send + 'static>(
509 streams: &'static Streams<T>,
510 cb: impl FnMut(Item<T>) + Send + 'static,
511 call: impl FnOnce(Emit<T>) -> Result<(), Error>,
512) -> Result<u64, Error> {
513 let emit = Emit::new(streams, cb);
514 let token = emit.token();
515 match call(emit) {
516 Ok(()) => Ok(token),
517 Err(e) => {
518 streams.fail(token, e.clone());
519 Err(e)
520 }
521 }
522}
523
524pub fn guard(f: impl FnOnce()) {
527 day_process::ffi_guard::contain((), f);
528}
529
530#[doc(hidden)]
538#[expect(
539 clippy::same_length_and_capacity,
540 reason = "the safety contract is a buffer allocated with capacity `len` and filled with `len` bytes"
541)]
542pub unsafe fn __take_wasm(ptr: *mut u8, len: usize) -> Vec<u8> {
543 if ptr.is_null() || len == 0 {
544 return Vec::new();
545 }
546 unsafe { Vec::from_raw_parts(ptr, len, len) }
548}
549
550#[cfg(all(target_os = "linux", target_env = "ohos"))]
556pub mod arkts {
557 use std::ffi::{c_char, c_int, c_void};
558
559 #[repr(C)]
562 pub struct Arg {
563 pub kind: i32,
564 pub i: i64,
565 pub f: f64,
566 pub ptr: *const u8,
567 pub len: usize,
568 }
569
570 impl Arg {
571 fn plain(kind: i32, i: i64, f: f64) -> Self {
572 Self {
573 kind,
574 i,
575 f,
576 ptr: std::ptr::null(),
577 len: 0,
578 }
579 }
580 #[must_use]
581 pub fn bool(v: bool) -> Self {
582 Self::plain(0, i64::from(v), 0.0)
583 }
584 #[must_use]
585 pub fn i32(v: i32) -> Self {
586 Self::plain(1, i64::from(v), 0.0)
587 }
588 #[must_use]
589 pub fn i64(v: i64) -> Self {
590 Self::plain(2, v, 0.0)
591 }
592 #[must_use]
593 pub fn f64(v: f64) -> Self {
594 Self::plain(3, 0, v)
595 }
596 #[must_use]
597 pub fn str(v: &str) -> Self {
598 Self {
599 kind: 4,
600 i: 0,
601 f: 0.0,
602 ptr: v.as_ptr(),
603 len: v.len(),
604 }
605 }
606 #[must_use]
607 pub fn bytes(v: &[u8]) -> Self {
608 Self {
609 kind: 5,
610 i: 0,
611 f: 0.0,
612 ptr: v.as_ptr(),
613 len: v.len(),
614 }
615 }
616 }
617
618 type InvokeFn = unsafe extern "C" fn(*const c_char, *const Arg, usize, u64, *mut Arg) -> c_int;
619 type OnJsThreadFn = unsafe extern "C" fn() -> c_int;
620
621 unsafe extern "C" {
622 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
623 fn dladdr(addr: *const c_void, info: *mut DlInfo) -> c_int;
624 fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void;
625 }
626
627 #[repr(C)]
629 #[expect(
630 clippy::struct_field_names,
631 reason = "the fields keep the names C's `Dl_info` gives them"
632 )]
633 struct DlInfo {
634 dli_fname: *const c_char,
635 dli_fbase: *mut c_void,
636 dli_sname: *const c_char,
637 dli_saddr: *mut c_void,
638 }
639
640 const RTLD_NOW: c_int = 2;
641 const RTLD_NOLOAD: c_int = 4;
643
644 #[must_use]
652 pub fn lookup(name: &std::ffi::CStr) -> *mut c_void {
653 let global = unsafe { dlsym(std::ptr::null_mut(), name.as_ptr()) };
655 if !global.is_null() {
656 return global;
657 }
658 let own = own_library();
659 if own.is_null() {
660 return std::ptr::null_mut();
661 }
662 unsafe { dlsym(own, name.as_ptr()) }
664 }
665
666 fn own_library() -> *mut c_void {
668 static HANDLE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
669 *HANDLE.get_or_init(|| {
670 let mut info = DlInfo {
671 dli_fname: std::ptr::null(),
672 dli_fbase: std::ptr::null_mut(),
673 dli_sname: std::ptr::null(),
674 dli_saddr: std::ptr::null_mut(),
675 };
676 let found = unsafe { dladdr(lookup as *const c_void, &raw mut info) } != 0;
679 if !found || info.dli_fname.is_null() {
680 return 0;
681 }
682 unsafe { dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD) as usize }
684 }) as *mut c_void
685 }
686
687 pub fn invoke(symbol: &str, args: &[Arg], done: u64) -> Result<(), super::Error> {
697 invoke_value(symbol, args, done).map(|_| ())
698 }
699
700 pub fn invoke_value(symbol: &str, args: &[Arg], done: u64) -> Result<Arg, super::Error> {
709 let entry = lookup(c"day_arkui_bridge_invoke");
710 if entry.is_null() {
711 return Err(super::Error::Runtime);
712 }
713 let Ok(name) = std::ffi::CString::new(symbol) else {
714 return Err(super::Error::Encoding);
715 };
716 let mut ret = Arg::plain(-1, 0, 0.0);
717 let invoke: InvokeFn = unsafe { std::mem::transmute(entry) };
719 match unsafe { invoke(name.as_ptr(), args.as_ptr(), args.len(), done, &raw mut ret) } {
720 0 => Ok(ret),
721 2 => Err(super::Error::Runtime),
722 _ => Err(super::Error::Foreign(format!("{symbol} failed"))),
723 }
724 }
725
726 #[must_use]
729 pub fn on_js_thread() -> bool {
730 let entry = lookup(c"day_arkui_bridge_on_js_thread");
731 if entry.is_null() {
732 return false;
733 }
734 let f: OnJsThreadFn = unsafe { std::mem::transmute(entry) };
736 unsafe { f() != 0 }
737 }
738
739 #[doc(hidden)]
745 #[must_use]
746 pub unsafe fn __bytes(ptr: *const u8, len: usize) -> Vec<u8> {
747 if ptr.is_null() || len == 0 {
748 return Vec::new();
749 }
750 unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()
752 }
753}
754
755#[macro_export]
771macro_rules! bridge {
772 ($($body:tt)*) => {
773 $crate::__bridge_generated!();
774 };
775}
776
777#[doc(hidden)]
778pub use day_macros::bridge_generated as __bridge_generated;
779
780#[cfg(test)]
781mod tests {
782 use super::*;
783 use std::sync::{Arc, Mutex};
784 use std::task::{Wake, Waker};
785
786 fn block_on<F: Future>(mut fut: F) -> F::Output {
787 struct Unpark(std::thread::Thread);
788 impl Wake for Unpark {
789 fn wake(self: Arc<Self>) {
790 self.0.unpark();
791 }
792 }
793 let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
794 let mut cx = Context::from_waker(&waker);
795 let mut fut = unsafe { Pin::new_unchecked(&mut fut) };
797 loop {
798 if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
799 return v;
800 }
801 std::thread::park();
802 }
803 }
804
805 static REG: Registry<bool> = Registry::new();
806
807 #[test]
808 fn a_rust_arm_completes_and_the_future_resolves() {
809 let fut = start_future(®, |done| {
810 std::thread::spawn(move || done.complete(Ok(true)));
811 Ok(())
812 });
813 assert_eq!(block_on(fut), Ok(true));
814 }
815
816 #[test]
817 fn a_foreign_style_token_round_trip() {
818 let fut = start_future(®, |done| {
819 let token = done.into_token();
820 assert!(REG.is_pending(token));
821 std::thread::spawn(move || {
822 assert!(REG.complete(token, Ok(false)));
823 assert!(!REG.complete(token, Ok(true)), "at most once");
824 });
825 Ok(())
826 });
827 assert_eq!(block_on(fut), Ok(false));
828 }
829
830 #[test]
831 fn an_arm_that_fails_to_start_fails_the_future_with_its_own_error() {
832 let fut = start_future(®, |_done| Err(Error::Foreign("no engine".into())));
833 assert_eq!(block_on(fut), Err(Error::Foreign("no engine".into())));
834 }
835
836 #[test]
837 fn an_arm_that_returns_ok_without_completing_leaves_the_future_pending() {
838 let fut = start_future(®, |done| {
839 let _ = done.into_token();
840 Ok(())
841 });
842 assert!(!fut.is_ready());
843 }
844
845 #[test]
846 fn dropping_the_future_cancels_the_slot_and_runs_the_hook() {
847 let hook = Arc::new(Mutex::new(false));
848 let h = hook.clone();
849 let mut token = 0;
850 let fut = start_future(®, |done| {
851 token = done.into_token();
852 Ok(())
853 })
854 .on_cancel(move || *h.lock().unwrap() = true);
855 assert!(REG.is_pending(token));
856 drop(fut);
857 assert!(!REG.is_pending(token));
858 assert!(*hook.lock().unwrap());
859 assert!(
860 !REG.complete(token, Ok(true)),
861 "a late completion is a no-op"
862 );
863 }
864
865 #[test]
866 fn the_callback_form_fires_exactly_once_on_start_failure() {
867 let hits = Arc::new(Mutex::new(0));
868 let h = hits.clone();
869 let r = start_async(
870 ®,
871 move |v| {
872 assert_eq!(v, Err(Error::Runtime));
873 *h.lock().unwrap() += 1;
874 },
875 |_done| Err(Error::Runtime),
876 );
877 assert_eq!(r, Err(Error::Runtime));
878 assert_eq!(*hits.lock().unwrap(), 1);
879 let token = start_async(®, |_| {}, |_done| Ok(())).expect("started");
880 assert!(REG.is_pending(token), "the token names the live slot");
881 }
882
883 static STREAMS: Streams<u32> = Streams::new();
884
885 type Seen = Arc<Mutex<Vec<Item<u32>>>>;
886
887 fn collector() -> (Seen, impl FnMut(Item<u32>) + Send + 'static) {
888 let seen: Seen = Arc::new(Mutex::new(Vec::new()));
889 let s = seen.clone();
890 (seen, move |item| s.lock().unwrap().push(item))
891 }
892
893 #[test]
894 fn a_stream_delivers_in_order_then_ends_once() {
895 let (seen, cb) = collector();
896 let token = start_stream(&STREAMS, cb, |emit| {
897 let token = emit.into_token();
898 std::thread::spawn(move || {
899 for v in 0..100 {
900 assert!(STREAMS.emit(token, v));
901 }
902 assert!(STREAMS.end(token));
903 assert!(!STREAMS.emit(token, 999), "nothing after the end");
904 assert!(!STREAMS.end(token), "the end is delivered once");
905 })
906 .join()
907 .unwrap();
908 Ok(())
909 })
910 .expect("started");
911 let seen = seen.lock().unwrap();
912 assert_eq!(seen.len(), 101);
913 assert!(
914 seen[..100]
915 .iter()
916 .enumerate()
917 .all(|(i, v)| *v == Item::Value(i as u32))
918 );
919 assert_eq!(seen[100], Item::End);
920 assert!(!STREAMS.is_open(token));
921 }
922
923 #[test]
924 fn pushes_from_many_threads_reach_the_consumer_serially() {
925 let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
926 let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
927 let (b, c) = (busy.clone(), count.clone());
928 let emit = Emit::new(&STREAMS, move |_item| {
929 assert!(
930 !b.swap(true, std::sync::atomic::Ordering::SeqCst),
931 "two deliveries overlapped"
932 );
933 std::thread::yield_now();
934 c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
935 b.store(false, std::sync::atomic::Ordering::SeqCst);
936 });
937 let workers: Vec<_> = (0..8)
938 .map(|_| {
939 let e = emit.clone();
940 std::thread::spawn(move || {
941 for v in 0..200 {
942 e.emit(v);
943 }
944 })
945 })
946 .collect();
947 for w in workers {
948 w.join().unwrap();
949 }
950 emit.end();
951 assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 8 * 200 + 1);
952 }
953
954 #[test]
955 fn the_consumer_may_stop_its_own_stream_from_inside_the_callback() {
956 let token_cell = Arc::new(Mutex::new(0u64));
957 let seen = Arc::new(Mutex::new(Vec::new()));
958 let (t, s) = (token_cell.clone(), seen.clone());
959 let emit = Emit::new(&STREAMS, move |item| {
960 s.lock().unwrap().push(item.clone());
961 if item == Item::Value(2) {
962 assert!(STREAMS.stop(*t.lock().unwrap()));
963 }
964 });
965 *token_cell.lock().unwrap() = emit.token();
966 for v in 0..5 {
967 emit.emit(v);
968 }
969 assert!(!emit.end(), "stopped streams refuse the end");
970 assert_eq!(
971 *seen.lock().unwrap(),
972 vec![Item::Value(0), Item::Value(1), Item::Value(2)]
973 );
974 assert!(!emit.is_open());
975 }
976
977 #[test]
978 fn a_stream_that_fails_to_start_delivers_that_failure_once() {
979 let (seen, cb) = collector();
980 let r = start_stream(&STREAMS, cb, |_emit| Err(Error::Foreign("no radio".into())));
981 assert_eq!(r, Err(Error::Foreign("no radio".into())));
982 assert_eq!(
983 *seen.lock().unwrap(),
984 vec![Item::Failed(Error::Foreign("no radio".into()))]
985 );
986 }
987
988 #[test]
989 fn deliver_maps_export_statuses() {
990 let (seen, cb) = collector();
991 let emit = Emit::new(&STREAMS, cb);
992 let token = emit.token();
993 assert!(STREAMS.deliver(token, 0, Ok(7)));
994 assert!(STREAMS.deliver(token, 0, Err(Error::Encoding)));
995 assert!(
996 !STREAMS.deliver(token, 2, Err(Error::Runtime)),
997 "already failed"
998 );
999 assert_eq!(
1000 *seen.lock().unwrap(),
1001 vec![Item::Value(7), Item::Failed(Error::Encoding)]
1002 );
1003 }
1004}