ToConstValue

Derive Macro ToConstValue 

Source
#[derive(ToConstValue)]
{
    // Attributes available to this derive:
    #[const_value]
}
Expand description

Derive for the ToConstValue trait.

This is principally used for associated constants in native modules, since Rune has to be provided a constant-compatible method for constructing values of the given type.

ยงExamples

use rune::{docstring, Any, ContextError, Module, ToConstValue};

#[derive(Any, ToConstValue)]
pub struct Duration {
    #[const_value(with = const_duration)]
    inner: std::time::Duration,
}

mod const_duration {
    use rune::runtime::{ConstValue, RuntimeError, Value};
    use std::time::Duration;

    #[inline]
    pub(super) fn to_const_value(duration: Duration) -> Result<ConstValue, RuntimeError> {
        let secs = duration.as_secs();
        let nanos = duration.subsec_nanos();
        rune::to_const_value((secs, nanos))
    }

    #[inline]
    pub(super) fn from_const_value(value: &ConstValue) -> Result<Duration, RuntimeError> {
        let (secs, nanos) = rune::from_const_value::<(u64, u32)>(value)?;
        Ok(Duration::new(secs, nanos))
    }

    #[inline]
    pub(super) fn from_value(value: Value) -> Result<Duration, RuntimeError> {
        let (secs, nanos) = rune::from_value::<(u64, u32)>(value)?;
        Ok(Duration::new(secs, nanos))
    }
}

#[rune::module(::time)]
pub fn module() -> Result<Module, ContextError> {
    let mut m = Module::from_meta(module__meta)?;
    m.ty::<Duration>()?;

    m
        .constant(
            "SECOND",
            Duration {
                inner: std::time::Duration::from_secs(1),
            },
        )
        .build_associated::<Duration>()?
        .docs(docstring! {
            /// The duration of one second.
            ///
            /// # Examples
            ///
            /// ```rune
            /// use time::Duration;
            ///
            /// let duration = Duration::SECOND;
            /// ```
        })?;

    Ok(m)
}