runestick_time/lib.rs
1//! The runestick time package.
2//!
3//! ## Usage
4//!
5//! Add the following to your `Cargo.toml`:
6//!
7//! ```toml
8//! runestick = "0.2"
9//! runestick-time = "0.2"
10//! ```
11//!
12//! Install it into your context:
13//!
14//! ```rust
15//! # fn main() -> runestick::Result<()> {
16//! let mut context = runestick::Context::with_default_packages()?;
17//! context.install(&runestick_time::module()?)?;
18//! # Ok(())
19//! # }
20//! ```
21//!
22//! Use it in Rune:
23//!
24//! ```rust,ignore
25//! use time;
26//!
27//! fn main() {
28//! time::delay_for(time::Duration::from_secs(10)).await;
29//! }
30//! ```
31
32use runestick::{ContextError, Module};
33
34#[derive(Debug, Clone, Copy)]
35struct Duration {
36 inner: tokio::time::Duration,
37}
38
39impl Duration {
40 /// Construct a duration from seconds.
41 fn from_secs(secs: u64) -> Self {
42 Self {
43 inner: tokio::time::Duration::from_secs(secs),
44 }
45 }
46}
47
48/// Convert any value to a json string.
49async fn delay_for(duration: &Duration) {
50 tokio::time::delay_for(duration.inner).await;
51}
52
53runestick::decl_external!(Duration);
54
55/// Get the module for the bytes package.
56pub fn module() -> Result<Module, ContextError> {
57 let mut module = Module::new(&["time"]);
58 module.function(&["Duration", "from_secs"], Duration::from_secs)?;
59 module.async_function(&["delay_for"], delay_for)?;
60 Ok(module)
61}