rune/modules/
clone.rs

1//! The cloning trait for Rune.
2
3use crate as rune;
4use crate::runtime::{Protocol, Value, VmResult};
5use crate::{ContextError, Module};
6
7/// Cloning for Rune.
8///
9/// This module defines methods and types used when cloning values.
10///
11/// By default all values in rune are structurally shared, so in order to get a
12/// unique instance of it you must clone it.
13#[rune::module(::std::clone)]
14pub fn module() -> Result<Module, ContextError> {
15    let mut m = Module::from_meta(self::module_meta)?;
16    m.function_meta(clone)?;
17
18    let mut t = m.define_trait(["Clone"])?;
19
20    t.docs(docstring! {
21        /// The `Clone` trait is used to explicitly clone values.
22        ///
23        /// # Examples
24        ///
25        /// ```rune
26        /// let a = 42;
27        /// let b = a.clone();
28        ///
29        /// assert_eq!(a, b);
30        /// ```
31    })?;
32
33    t.handler(|cx| {
34        _ = cx.find(&Protocol::CLONE)?;
35        Ok(())
36    })?;
37
38    t.function("clone")?
39        .argument_types::<(Value,)>()?
40        .return_type::<Value>()?
41        .docs(docstring! {
42            /// Clone the specified `value`.
43            ///
44            /// # Examples
45            ///
46            /// ```rune
47            /// let a = 42;
48            /// let b = a;
49            /// let c = a.clone();
50            ///
51            /// a += 1;
52            ///
53            /// assert_eq!(a, 43);
54            /// assert_eq!(b, 42);
55            /// assert_eq!(c, 42);
56            /// ```
57        })?;
58
59    Ok(m)
60}
61
62/// Clone the specified `value`.
63///
64/// # Examples
65///
66/// ```rune
67/// let a = 42;
68/// let b = a;
69/// let c = clone(a);
70///
71/// a += 1;
72///
73/// assert_eq!(a, 43);
74/// assert_eq!(b, 42);
75/// assert_eq!(c, 42);
76/// ```
77#[rune::function]
78fn clone(value: Value) -> VmResult<Value> {
79    value.clone_()
80}