use crate::{
prelude::*,
types::type_definition::{
TypeDefinition, callable::CallableTypeDefinition,
},
values::{
core_value::CoreValue,
core_values::{
callable::{Callable, CallableBody},
integer::typed_integer::TypedInteger,
},
value_container::{ValueContainer, value_key::BorrowedValueKey},
},
};
pub mod apply;
mod child_iterator;
pub mod datex_proxy;
pub mod equality;
pub mod ops;
pub mod serde_dif;
pub mod update_handler;
use crate::shared_values::errors::AccessError;
use core::{
fmt::{Display, Formatter},
result::Result,
};
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct Value {
pub inner: CoreValue,
pub custom_type: Option<TypeDefinition>,
}
impl<T: Into<CoreValue>> From<T> for Value {
fn from(inner: T) -> Self {
let inner = inner.into();
Value {
inner,
custom_type: None,
}
}
}
impl Value {
pub fn null() -> Self {
CoreValue::Null.into()
}
}
impl Value {
pub fn callable(
name: Option<String>,
signature: CallableTypeDefinition,
body: CallableBody,
) -> Self {
Value {
inner: CoreValue::Callable(Callable {
name,
signature: signature.clone(),
body,
}),
custom_type: Some(TypeDefinition::callable(signature)),
}
}
#[deprecated]
pub fn is_null(&self) -> bool {
core::matches!(self.inner, CoreValue::Null)
}
#[deprecated]
pub fn is_text(&self) -> bool {
core::matches!(self.inner, CoreValue::Text(_))
}
#[deprecated]
pub fn is_integer_i8(&self) -> bool {
core::matches!(
&self.inner,
CoreValue::TypedInteger(TypedInteger::I8(_))
)
}
#[deprecated]
pub fn is_map(&self) -> bool {
core::matches!(self.inner, CoreValue::Map(_))
}
pub fn try_as<'a, T: 'a>(&'a self) -> Option<&'a T>
where
&'a T: TryFrom<&'a CoreValue>,
{
<&T>::try_from(&self.inner).ok()
}
pub fn try_as_mut<'a, T: 'a>(&'a mut self) -> Option<&'a mut T>
where
&'a mut T: TryFrom<&'a mut CoreValue>,
{
<&mut T>::try_from(&mut self.inner).ok()
}
pub fn try_into_value<T>(self) -> Option<T>
where
T: TryFrom<CoreValue>,
{
T::try_from(self.inner).ok()
}
pub fn has_default_type(&self) -> bool {
match &self.custom_type {
None => true,
Some(TypeDefinition::CoreType(core_type)) => {
core_type == &self.default_core_type()
}
Some(_) => false,
}
}
pub fn actual_type(&self) -> TypeDefinition {
match &self.custom_type {
Some(actual_type) => actual_type.clone(),
None => TypeDefinition::CoreType(self.default_core_type()),
}
}
pub fn try_get_property<'a>(
&self,
key: impl Into<BorrowedValueKey<'a>>,
) -> Result<ValueContainer, AccessError> {
match self.inner {
CoreValue::Map(ref map) => {
Ok(map.get(key)?.clone())
}
CoreValue::List(ref list) => {
if let Some(index) = key.into().try_as_index() {
Ok(list.try_get(index)?.clone())
} else {
Err(AccessError::InvalidIndexKey)
}
}
CoreValue::Text(ref text) => {
if let Some(index) = key.into().try_as_index() {
let char = text.char_at(index)?;
Ok(ValueContainer::from(char.to_string()))
} else {
Err(AccessError::InvalidIndexKey)
}
}
_ => {
Err(AccessError::InvalidOperation(
"Cannot get property".to_string(),
))
}
}
}
pub fn try_take_property<'a>(
&mut self,
key: impl Into<BorrowedValueKey<'a>>,
) -> Result<ValueContainer, AccessError> {
match self.inner {
CoreValue::Map(ref mut map) => {
Ok(map.try_delete(key)?)
}
CoreValue::List(ref mut list) => {
if let Some(index) = key.into().try_as_index() {
Ok(list.delete(index)?)
} else {
Err(AccessError::InvalidIndexKey)
}
}
CoreValue::Text(ref text) => {
if let Some(index) = key.into().try_as_index() {
let char = text.char_at(index)?;
Ok(ValueContainer::from(char.to_string()))
} else {
Err(AccessError::InvalidIndexKey)
}
}
_ => {
Err(AccessError::InvalidOperation(
"Cannot get property".to_string(),
))
}
}
}
pub fn try_delete_property<'a>(
&mut self,
key: impl Into<BorrowedValueKey<'a>>,
) -> Result<(), AccessError> {
match self.inner {
CoreValue::Map(ref mut map) => {
map.try_delete(key)?;
Ok(())
}
CoreValue::List(ref mut list) => {
if let Some(index) = key.into().try_as_index() {
list.delete(index)?;
Ok(())
} else {
Err(AccessError::InvalidIndexKey)
}
}
CoreValue::Text(_) => Err(AccessError::InvalidOperation(
"Cannot delete property on text".to_string(),
)),
_ => {
Err(AccessError::InvalidOperation(
"Cannot delete property".to_string(),
))
}
}
}
pub fn try_set_property<'a>(
&mut self,
key: impl Into<BorrowedValueKey<'a>>,
val: ValueContainer,
) -> Result<(), AccessError> {
let key = key.into();
match self.inner {
CoreValue::Map(ref mut map) => {
map.try_set(key, val)?;
}
CoreValue::List(ref mut list) => {
if let Some(index) = key.try_as_index() {
list.try_set(index, val)
.map_err(AccessError::IndexOutOfBounds)?;
} else {
return Err(AccessError::InvalidIndexKey);
}
}
CoreValue::Text(ref mut text) => {
if let Some(index) = key.try_as_index() {
if let ValueContainer::Local(v) = &val
&& let CoreValue::Text(new_char) = &v.inner
&& new_char.0.len() == 1
{
let char = new_char.0.chars().next().unwrap_or('\0');
text.set_char_at(index, char).map_err(|err| {
AccessError::IndexOutOfBounds(err)
})?;
} else {
return Err(AccessError::InvalidOperation(
"Can only set char character in text".to_string(),
));
}
} else {
return Err(AccessError::InvalidIndexKey);
}
}
_ => {
return Err(AccessError::InvalidOperation(format!(
"Cannot set property '{}' on non-map value: {:?}",
key, self
)));
}
}
Ok(())
}
}
impl Display for Value {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
core::write!(f, "{}", self.inner)
}
}
impl<T> From<Option<T>> for Value
where
T: Into<Value>,
{
fn from(opt: Option<T>) -> Self {
match opt {
Some(v) => v.into(),
None => Value::null(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
assert_structural_eq, datex_list,
libs::core::type_id::{CoreLibBaseTypeId, CoreLibTypeId},
prelude::*,
types::{r#type::Type, type_definition::impl_type::ImplTypeDefinition},
values::core_values::{
endpoint::Endpoint,
integer::{Integer, typed_integer::TypedInteger},
list::List,
},
};
use core::str::FromStr;
use log::info;
#[test]
fn endpoint() {
let endpoint = Value::from(Endpoint::from_str("@test").unwrap());
assert_eq!(endpoint.to_string(), "@test");
}
#[test]
fn new_addition_assignments() {
let mut x = Value::from(42i8);
let y = Value::from(27i8);
x += y.clone();
assert_eq!(x, Value::from(69i8));
}
#[test]
fn new_additions() {
let x = Value::from(42i8);
let y = Value::from(27i8);
let z = (x.clone() + y.clone()).unwrap();
assert_eq!(z, Value::from(69i8));
}
#[test]
fn list() {
let mut a = List::from(vec![
Value::from("42"),
Value::from(42),
Value::from(true),
]);
a.push(Value::from(42));
a.push(4);
assert_eq!(a.len(), 5);
let b = List::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert_eq!(b.len(), 11);
let c = datex_list![1, "test", 3, true, false];
assert_eq!(c.len(), 5);
assert_eq!(c[0], 1.into());
assert_eq!(c[1], "test".into());
assert_eq!(c[2], 3.into());
}
#[test]
fn boolean() {
let a = Value::from(true);
let b = Value::from(false);
let c = Value::from(false);
assert_ne!(a, b);
assert_eq!(b, c);
let d = (!b.clone()).unwrap();
assert_eq!(a, d);
let a_plus_b = a.clone() + b.clone();
assert!(a_plus_b.is_err());
}
#[test]
fn equality_same_type() {
let a = Value::from(42i8);
let b = Value::from(42i8);
let c = Value::from(27i8);
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(b, c);
info!("{} === {}", a.clone(), b.clone());
info!("{} !== {}", a.clone(), c.clone());
}
#[test]
fn decimal() {
let a = Value::from(42.1f32);
let b = Value::from(27f32);
let a_plus_b = (a.clone() + b.clone()).unwrap();
assert_eq!(a_plus_b, Value::from(69.1f32));
info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
}
#[test]
fn null() {
let null_value = Value::null();
assert_eq!(null_value.to_string(), "null");
let maybe_value: Option<i8> = None;
let null_value = Value::from(maybe_value);
assert_eq!(null_value.to_string(), "null");
assert!(null_value.is_null());
}
#[test]
fn addition() {
let a = Value::from(42i8);
let b = Value::from(27i8);
let a_plus_b = (a.clone() + b.clone()).unwrap();
assert_eq!(a_plus_b, Value::from(69i8));
info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
}
#[test]
fn string_concatenation() {
let a = Value::from("Hello ");
let b = Value::from(42i8);
assert!(a.is_text());
assert!(b.is_integer_i8());
let a_plus_b = (a.clone() + b.clone()).unwrap();
let b_plus_a = (b.clone() + a.clone()).unwrap();
assert!(a_plus_b.is_text());
assert!(b_plus_a.is_text());
assert_eq!(a_plus_b, Value::from("Hello 42"));
assert_eq!(b_plus_a, Value::from("42Hello "));
info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
info!("{} + {} = {}", b.clone(), a.clone(), b_plus_a);
}
#[test]
fn structural_equality() {
let a = Value::from(42_i8);
let b = Value::from(42_i32);
assert!(a.is_integer_i8());
assert_structural_eq!(a, b);
assert_structural_eq!(
Value::from(TypedInteger::I8(42)),
Value::from(TypedInteger::U32(42)),
);
assert_structural_eq!(
Value::from(42_i8),
Value::from(Integer::from(42_i8))
);
}
#[test]
fn default_types() {
let val = Value::from(Integer::from(42));
assert!(val.has_default_type());
let val = Value::from(42i8);
assert!(val.has_default_type());
let val = Value {
inner: CoreValue::Integer(Integer::from(42)),
custom_type: Some(TypeDefinition::CoreType(
CoreLibBaseTypeId::Integer.into(),
)),
};
assert!(val.has_default_type());
let val = Value {
inner: CoreValue::Integer(Integer::from(42)),
custom_type: Some(TypeDefinition::ImplType(
ImplTypeDefinition::new(
Type::core(CoreLibBaseTypeId::Integer),
vec![],
),
)),
};
assert!(!val.has_default_type());
}
}