Skip to main content

rings_core/macros/
mod.rs

1//! Macro for ring-core
2//!
3//! `poll` schedules a future expression repeatedly on wasm runtimes.
4//!
5//! # Example
6//!
7//! ```rust,ignore
8//! # extern crate async_trait;
9//! # extern crate futures;
10//! # extern crate ring_core;
11//! # extern crate log;
12//!
13//! use std::sync::Arc;
14//! use std::time::Duration;
15//!
16//! # use async_trait::async_trait;
17//! # use futures::future::FutureExt;
18//! # use futures::pin_mut;
19//! # use futures::select;
20//! # use futures_timer::Delay;
21//! # use ring_core::dht::Stabilization;
22//! # use ring_core::dht::TStabilize;
23//!
24//! #[async_trait]
25//! impl TStabilize for Stabilization {
26//!     async fn wait(self: Arc<Self>) {
27//!         loop {
28//!             let timeout = Delay::new(Duration::from_secs(self.timeout as u64)).fuse();
29//!             pin_mut!(timeout);
30//!             select! {
31//!                 _ = timeout => self
32//!                     .stabilize()
33//!                     .await
34//!                     .unwrap_or_else(|e| log::error!("failed to stabilize {:?}", e)),
35//!             }
36//!         }
37//!     }
38//! }
39//! ```
40//!
41//! Stabilize function using `futures::select` to await task is finish, but feature wasm not support
42//! Using `poll` can fix this problem.
43//!
44//! ```rust,ignore
45//! # extern crate async_trait;
46//! # extern crate ring_core;
47//! # extern crate log;
48//!
49//! # use std::sync::Arc;
50//!
51//! # use async_trait::async_trait;
52//! # use ring_core::dht::Stabilization;
53//! # use ring_core::dht::TStabilize;
54//! # use ring_core::poll;
55//!  #[async_trait(?Send)]
56//!  impl TStabilize for Stabilization {
57//!      async fn wait(self: Arc<Self>) {
58//!          let caller = Arc::clone(&self);
59//!          poll!(
60//!              {
61//!                  let caller = Arc::clone(&caller);
62//!                  async move {
63//!                      caller
64//!                          .stabilize()
65//!                          .await
66//!                          .unwrap_or_else(|e| log::error!("failed to stabilize {:?}", e));
67//!                  }
68//!              },
69//!              25000
70//!          );
71//!     }
72//!  }
73//!  ```
74
75/// Schedule a future expression repeatedly with a wasm timeout.
76#[macro_export]
77macro_rules! poll {
78    ( $future:expr, $ttl:expr ) => {{
79        $crate::utils::js_utils::spawn_interval($ttl, move || $future);
80    }};
81}