Skip to main content

datex_core/traits/
try_clone.rs

1use crate::values::{core_values::native::DatexNative, value::Value};
2
3/// This trait is completely auto derived for all types and must
4/// not be implemented manually.
5/// It is used to attempt to clone a value into a new [Value].
6pub trait TryClone {
7    /// Attempts to clone [Self] into a new [Value].
8    fn try_clone(&self) -> Result<Value, ()>;
9}
10
11/// Per default, types that do not implement Clone will return an error when try_clone is called.
12impl<T> TryClone for T {
13    default fn try_clone(&self) -> Result<Value, ()> {
14        Err(())
15    }
16}
17
18/// For any [DatexNative] type that implements [Clone],
19/// try_clone gets this default impl that returns a new [CoreValue] containing the cloned value.
20impl<T> TryClone for T
21where
22    T: Clone + DatexNative,
23{
24    default fn try_clone(&self) -> Result<Value, ()> {
25        Ok(Value::native(self.clone()))
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use crate::{
32        prelude::*,
33        traits::{convert_value::ConvertValue, try_clone::TryClone},
34    };
35
36    #[test]
37    fn test_try_string() {
38        let value = "Hello, world!".to_string();
39        let cloned_value = value.try_clone().unwrap();
40        assert_eq!(cloned_value, "Hello, world!".to_string().to_value());
41    }
42
43    #[test]
44    fn test_try_unclonable_type() {
45        struct UnclonableType;
46        let value = UnclonableType;
47        let cloned_value = value.try_clone();
48        assert!(cloned_value.is_err());
49    }
50}