ankurah_core/property/
mod.rs

1pub mod backend;
2pub mod traits;
3pub mod value;
4
5use ankurah_proto::EntityId;
6
7pub use traits::{FromActiveType, FromEntity, InitializeWith, PropertyError};
8pub use value::YrsString;
9
10use crate::value::Value;
11
12pub type PropertyName = String;
13
14pub trait Property: Sized {
15    fn into_value(&self) -> Result<Option<Value>, PropertyError>;
16    fn from_value(value: Option<Value>) -> Result<Self, PropertyError>;
17}
18
19impl<T> Property for Option<T>
20where T: Property
21{
22    fn into_value(&self) -> Result<Option<Value>, PropertyError> {
23        match self {
24            Some(value) => Ok(<T as Property>::into_value(value)?),
25            None => Ok(None),
26        }
27    }
28    fn from_value(value: Option<Value>) -> Result<Self, PropertyError> {
29        match T::from_value(value) {
30            Ok(value) => Ok(Some(value)),
31            Err(PropertyError::Missing) => Ok(None),
32            Err(err) => Err(err),
33        }
34    }
35}
36
37macro_rules! into {
38    ($ty:ty => $variant:ident) => {
39        impl Property for $ty {
40            fn into_value(&self) -> Result<Option<Value>, PropertyError> { Ok(Some(Value::$variant(self.clone()))) }
41            fn from_value(value: Option<Value>) -> Result<Self, PropertyError> {
42                match value {
43                    Some(Value::$variant(value)) => Ok(value),
44                    Some(variant) => Err(PropertyError::InvalidVariant { given: variant, ty: stringify!($ty).to_owned() }),
45                    None => Err(PropertyError::Missing),
46                }
47            }
48        }
49        impl From<$ty> for Value {
50            fn from(value: $ty) -> Self { Value::$variant(value) }
51        }
52    };
53}
54
55into!(String => String);
56into!(i16 => I16);
57into!(i32 => I32);
58into!(i64 => I64);
59into!(f64 => F64);
60into!(bool => Bool);
61into!(EntityId => EntityId);
62
63impl<'a> Property for std::borrow::Cow<'a, str> {
64    fn into_value(&self) -> Result<Option<Value>, PropertyError> { Ok(Some(Value::String(self.to_string()))) }
65
66    fn from_value(value: Option<Value>) -> Result<Self, PropertyError> {
67        match value {
68            Some(Value::String(value)) => Ok(value.into()),
69            Some(variant) => Err(PropertyError::InvalidVariant { given: variant, ty: stringify!($ty).to_owned() }),
70            None => Err(PropertyError::Missing),
71        }
72    }
73}
74
75impl From<&str> for Value {
76    fn from(value: &str) -> Self { Value::String(value.to_string()) }
77}