1
0
dust/src/value/mod.rs

899 lines
25 KiB
Rust
Raw Normal View History

2023-08-28 14:12:41 +00:00
//! Types that represent runtime values.
2023-08-22 15:40:50 +00:00
use crate::{
error::{Error, Result},
2024-01-06 08:47:54 +00:00
Function, Identifier, List, Map, Structure, Type, TypeDefinition,
2023-08-22 15:40:50 +00:00
};
use serde::{
de::{MapAccess, SeqAccess, Visitor},
ser::SerializeTuple,
Deserialize, Serialize, Serializer,
};
use std::{
cmp::Ordering,
convert::TryFrom,
fmt::{self, Display, Formatter},
marker::PhantomData,
2023-10-13 23:56:57 +00:00
ops::{Add, AddAssign, Div, Mul, Rem, Sub, SubAssign},
sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
2023-08-22 15:40:50 +00:00
};
pub mod function;
2023-10-26 22:03:59 +00:00
pub mod list;
2023-10-25 20:44:50 +00:00
pub mod map;
2024-01-06 08:47:54 +00:00
pub mod structure;
2023-08-22 15:40:50 +00:00
2023-11-07 00:15:22 +00:00
/// Dust value representation.
2023-08-22 15:40:50 +00:00
///
2023-11-07 00:15:22 +00:00
/// Every dust variable has a key and a Value. Variables are represented by
2023-08-22 15:40:50 +00:00
/// storing them in a VariableMap. This means the map of variables is itself a
/// value that can be treated as any other.
#[derive(Debug, Clone)]
2023-08-22 15:40:50 +00:00
pub enum Value {
2023-10-26 22:03:59 +00:00
List(List),
2023-10-25 20:44:50 +00:00
Map(Map),
2023-08-22 15:40:50 +00:00
Function(Function),
String(Arc<RwLock<String>>),
2023-10-05 12:03:14 +00:00
Float(f64),
Integer(i64),
Boolean(bool),
Option(Option<Box<Value>>),
2024-01-06 08:47:54 +00:00
Structure(Structure),
}
impl Default for Value {
fn default() -> Self {
2023-12-30 14:29:33 +00:00
Value::none()
}
2023-08-22 15:40:50 +00:00
}
2023-10-10 17:29:11 +00:00
impl Value {
2024-01-01 18:12:41 +00:00
pub fn string<T: Into<String>>(string: T) -> Self {
Value::String(Arc::new(RwLock::new(string.into())))
}
2023-12-09 22:55:47 +00:00
pub fn r#type(&self) -> Type {
2023-11-30 00:23:42 +00:00
let r#type = match self {
Value::List(list) => {
2023-11-30 05:57:15 +00:00
let mut previous_type = None;
2023-11-30 00:23:42 +00:00
2023-11-30 05:57:15 +00:00
for value in list.items().iter() {
2023-12-09 22:55:47 +00:00
let value_type = value.r#type();
2023-11-30 05:57:15 +00:00
if let Some(previous) = &previous_type {
if &value_type != previous {
2023-12-09 22:55:47 +00:00
return Type::List(Box::new(Type::Any));
2023-11-30 05:57:15 +00:00
}
}
previous_type = Some(value_type);
}
2023-11-30 07:09:55 +00:00
if let Some(previous) = previous_type {
2023-12-05 22:08:22 +00:00
Type::List(Box::new(previous))
2023-11-30 07:09:55 +00:00
} else {
Type::List(Box::new(Type::Any))
}
2023-11-30 00:23:42 +00:00
}
2024-01-04 00:57:06 +00:00
Value::Map(map) => {
let mut identifier_types = Vec::new();
for (key, (value, _)) in map.variables().unwrap().iter() {
identifier_types.push((
Identifier::new(key.clone()),
TypeDefinition::new(value.r#type()),
));
}
2024-01-06 08:47:54 +00:00
Type::Map(None)
2024-01-04 00:57:06 +00:00
}
2023-12-05 22:08:22 +00:00
Value::Function(function) => function.r#type().clone(),
2023-11-30 01:59:58 +00:00
Value::String(_) => Type::String,
Value::Float(_) => Type::Float,
Value::Integer(_) => Type::Integer,
Value::Boolean(_) => Type::Boolean,
Value::Option(option) => {
if let Some(value) = option {
2023-12-26 22:19:12 +00:00
Type::Option(Box::new(value.r#type()))
} else {
2023-12-26 22:19:12 +00:00
Type::None
}
}
2024-01-06 06:05:13 +00:00
Value::Structure(_) => todo!(),
2023-11-30 00:23:42 +00:00
};
2023-12-09 22:55:47 +00:00
r#type
2023-11-21 18:42:47 +00:00
}
2023-12-30 14:29:33 +00:00
pub fn none() -> Self {
Value::Option(None)
}
2024-01-01 18:12:41 +00:00
pub fn some(value: Value) -> Self {
Value::Option(Some(Box::new(value)))
}
2024-01-01 15:31:53 +00:00
pub fn option(option: Option<Value>) -> Self {
Value::Option(option.map(|value| Box::new(value)))
}
2023-08-22 15:40:50 +00:00
pub fn is_string(&self) -> bool {
2023-10-05 12:03:14 +00:00
matches!(self, Value::String(_))
2023-08-22 15:40:50 +00:00
}
pub fn is_integer(&self) -> bool {
2023-10-05 12:03:14 +00:00
matches!(self, Value::Integer(_))
2023-08-22 15:40:50 +00:00
}
pub fn is_float(&self) -> bool {
2023-10-05 12:03:14 +00:00
matches!(self, Value::Float(_))
2023-08-22 15:40:50 +00:00
}
pub fn is_number(&self) -> bool {
2023-10-05 12:03:14 +00:00
matches!(self, Value::Integer(_) | Value::Float(_))
2023-08-22 15:40:50 +00:00
}
pub fn is_boolean(&self) -> bool {
2023-10-05 12:03:14 +00:00
matches!(self, Value::Boolean(_))
2023-08-22 15:40:50 +00:00
}
pub fn is_list(&self) -> bool {
matches!(self, Value::List(_))
}
pub fn is_option(&self) -> bool {
matches!(self, Value::Option(_))
}
pub fn is_none(&self) -> bool {
matches!(self, Value::Option(None))
2023-08-22 15:40:50 +00:00
}
pub fn is_map(&self) -> bool {
matches!(self, Value::Map(_))
}
pub fn is_function(&self) -> bool {
matches!(self, Value::Map(_))
}
/// Borrows the value stored in `self` as `&str`, or returns `Err` if `self` is not a `Value::String`.
pub fn as_string(&self) -> Result<RwLockReadGuard<String>> {
match self {
Value::String(string) => Ok(string.read()?),
value => Err(Error::ExpectedString {
actual: value.clone(),
}),
}
}
2023-10-05 12:03:14 +00:00
/// Borrows the value stored in `self` as `String`, or returns `Err` if `self` is not a `Value::String`.
pub fn as_string_mut(&self) -> Result<RwLockWriteGuard<String>> {
2023-08-22 15:40:50 +00:00
match self {
Value::String(string) => Ok(string.write()?),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedString {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
/// Copies the value stored in `self` as `i64`, or returns `Err` if `self` is not a `Value::Int`.
2023-10-28 14:28:43 +00:00
pub fn as_integer(&self) -> Result<i64> {
2023-08-22 15:40:50 +00:00
match self {
2023-10-05 12:03:14 +00:00
Value::Integer(i) => Ok(*i),
2023-11-27 15:27:44 +00:00
value => Err(Error::ExpectedInteger {
2023-10-13 16:26:44 +00:00
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
2023-10-02 21:15:05 +00:00
/// Copies the value stored in `self` as `f64`, or returns `Err` if `self` is not a `Primitive::Float`.
2023-08-22 15:40:50 +00:00
pub fn as_float(&self) -> Result<f64> {
match self {
2023-10-05 12:03:14 +00:00
Value::Float(f) => Ok(*f),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedFloat {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
2023-10-02 21:15:05 +00:00
/// Copies the value stored in `self` as `f64`, or returns `Err` if `self` is not a `Primitive::Float` or `Value::Int`.
2023-08-22 15:40:50 +00:00
/// Note that this method silently converts `i64` to `f64`, if `self` is a `Value::Int`.
pub fn as_number(&self) -> Result<f64> {
match self {
2023-10-05 12:03:14 +00:00
Value::Float(f) => Ok(*f),
Value::Integer(i) => Ok(*i as f64),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedNumber {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
2023-10-02 21:15:05 +00:00
/// Copies the value stored in `self` as `bool`, or returns `Err` if `self` is not a `Primitive::Boolean`.
2023-08-22 15:40:50 +00:00
pub fn as_boolean(&self) -> Result<bool> {
match self {
2023-10-05 12:03:14 +00:00
Value::Boolean(boolean) => Ok(*boolean),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedBoolean {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
/// Borrows the value stored in `self` as `Vec<Value>`, or returns `Err` if `self` is not a `Value::List`.
2023-10-26 22:03:59 +00:00
pub fn as_list(&self) -> Result<&List> {
2023-08-22 15:40:50 +00:00
match self {
Value::List(list) => Ok(list),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedList {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
/// Takes ownership of the value stored in `self` as `Vec<Value>`, or returns `Err` if `self` is not a `Value::List`.
2023-10-26 22:03:59 +00:00
pub fn into_inner_list(self) -> Result<List> {
2023-08-22 15:40:50 +00:00
match self {
Value::List(list) => Ok(list),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedList {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
/// Borrows the value stored in `self` as `Vec<Value>`, or returns `Err` if `self` is not a `Value::Map`.
2023-10-25 20:44:50 +00:00
pub fn as_map(&self) -> Result<&Map> {
2023-08-22 15:40:50 +00:00
match self {
Value::Map(map) => Ok(map),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedMap {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
/// Borrows the value stored in `self` as `Function`, or returns `Err` if
/// `self` is not a `Value::Function`.
pub fn as_function(&self) -> Result<&Function> {
match self {
Value::Function(function) => Ok(function),
2023-10-13 16:26:44 +00:00
value => Err(Error::ExpectedFunction {
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
2023-12-27 00:33:19 +00:00
/// Returns `Option`, or returns `Err` if `self` is not a `Value::Option`.
pub fn as_option(&self) -> Result<&Option<Box<Value>>> {
match self {
Value::Option(option) => Ok(option),
value => Err(Error::ExpectedOption {
actual: value.clone(),
}),
}
}
2023-12-31 14:14:43 +00:00
/// Returns `()`, or returns `Err` if `self` is not a `Value::none()`.
pub fn as_none(&self) -> Result<()> {
2023-08-22 15:40:50 +00:00
match self {
Value::Option(option) => {
if option.is_none() {
Ok(())
} else {
Err(Error::ExpectedNone {
actual: self.clone(),
})
}
}
value => Err(Error::ExpectedNone {
2023-10-13 16:26:44 +00:00
actual: value.clone(),
}),
2023-08-22 15:40:50 +00:00
}
}
}
2023-11-28 23:28:07 +00:00
impl Default for &Value {
fn default() -> Self {
&Value::Option(None)
2023-11-28 23:28:07 +00:00
}
}
2023-09-29 03:53:37 +00:00
impl Add for Value {
type Output = Result<Value>;
2023-09-29 10:02:46 +00:00
fn add(self, other: Self) -> Self::Output {
2023-11-04 03:42:10 +00:00
if let (Ok(left), Ok(right)) = (self.as_integer(), other.as_integer()) {
return Ok(Value::Integer(left + right));
2023-10-22 21:04:14 +00:00
}
2023-11-04 03:42:10 +00:00
if let (Ok(left), Ok(right)) = (self.as_number(), other.as_number()) {
return Ok(Value::Float(left + right));
2023-10-22 21:04:14 +00:00
}
2023-11-04 03:42:10 +00:00
if let (Ok(left), Ok(right)) = (self.as_string(), other.as_string()) {
return Ok(Value::string(left.to_string() + right.as_str()));
2023-11-04 03:42:10 +00:00
}
if self.is_string() || other.is_string() {
return Ok(Value::string(self.to_string() + &other.to_string()));
2023-10-22 21:04:14 +00:00
}
let non_number_or_string = if !self.is_number() == !self.is_string() {
self
} else {
other
2023-10-09 19:54:47 +00:00
};
2023-10-22 21:04:14 +00:00
Err(Error::ExpectedNumberOrString {
actual: non_number_or_string,
})
2023-10-09 19:54:47 +00:00
}
}
impl Sub for Value {
type Output = Result<Self>;
fn sub(self, other: Self) -> Self::Output {
2023-12-30 03:39:50 +00:00
if let (Ok(left), Ok(right)) = (self.as_integer(), other.as_integer()) {
return Ok(Value::Integer(left - right));
}
2023-12-30 03:39:50 +00:00
if let (Ok(left), Ok(right)) = (self.as_number(), other.as_number()) {
return Ok(Value::Float(left - right));
}
let non_number = if !self.is_number() { self } else { other };
2023-10-09 19:54:47 +00:00
Err(Error::ExpectedNumber { actual: non_number })
2023-09-29 03:53:37 +00:00
}
}
2023-10-13 23:56:57 +00:00
impl Mul for Value {
type Output = Result<Self>;
fn mul(self, other: Self) -> Self::Output {
if let (Ok(left), Ok(right)) = (self.as_integer(), other.as_integer()) {
Ok(Value::Integer(left.saturating_mul(right)))
} else if let (Ok(left), Ok(right)) = (self.as_number(), other.as_number()) {
Ok(Value::Float(left * right))
2023-10-13 23:56:57 +00:00
} else {
let non_number = if !self.is_number() { self } else { other };
2023-10-13 23:56:57 +00:00
Err(Error::ExpectedNumber { actual: non_number })
2023-10-13 23:56:57 +00:00
}
}
}
impl Div for Value {
type Output = Result<Self>;
fn div(self, other: Self) -> Self::Output {
if let (Ok(left), Ok(right)) = (self.as_number(), other.as_number()) {
let divided = left / right;
let is_even = divided % 2.0 == 0.0;
if self.is_integer() && other.is_integer() && is_even {
Ok(Value::Integer(divided as i64))
} else {
Ok(Value::Float(divided))
}
2023-10-13 23:56:57 +00:00
} else {
let non_number = if !self.is_number() { self } else { other };
2023-10-13 23:56:57 +00:00
Err(Error::ExpectedNumber { actual: non_number })
}
2023-10-13 23:56:57 +00:00
}
}
impl Rem for Value {
type Output = Result<Self>;
fn rem(self, other: Self) -> Self::Output {
2023-10-28 14:28:43 +00:00
let left = self.as_integer()?;
let right = other.as_integer()?;
2023-10-13 23:56:57 +00:00
let result = left % right;
Ok(Value::Integer(result))
}
}
2023-10-09 19:54:47 +00:00
impl AddAssign for Value {
fn add_assign(&mut self, other: Self) {
match (self, other) {
(Value::Integer(left), Value::Integer(right)) => *left += right,
(Value::Float(left), Value::Float(right)) => *left += right,
(Value::Float(left), Value::Integer(right)) => *left += right as f64,
(Value::String(left), Value::String(right)) => {
*left.write().unwrap() += right.read().unwrap().as_str()
}
2023-10-26 22:03:59 +00:00
(Value::List(list), value) => list.items_mut().push(value),
2023-10-09 19:54:47 +00:00
_ => {}
}
}
}
2023-09-29 10:02:46 +00:00
2023-10-09 19:54:47 +00:00
impl SubAssign for Value {
fn sub_assign(&mut self, other: Self) {
match (self, other) {
(Value::Integer(left), Value::Integer(right)) => *left -= right,
(Value::Float(left), Value::Float(right)) => *left -= right,
(Value::Float(left), Value::Integer(right)) => *left -= right as f64,
2023-11-27 22:53:12 +00:00
(Value::List(list), value) => {
let index_to_remove = list
.items()
.iter()
.enumerate()
.find_map(|(i, list_value)| if list_value == &value { Some(i) } else { None });
if let Some(index) = index_to_remove {
list.items_mut().remove(index);
}
}
2023-10-09 19:54:47 +00:00
_ => {}
}
2023-09-29 10:02:46 +00:00
}
}
2023-08-22 15:40:50 +00:00
impl Eq for Value {}
2023-10-01 16:17:27 +00:00
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
2023-10-05 12:42:23 +00:00
(Value::Integer(left), Value::Integer(right)) => left == right,
(Value::Float(left), Value::Float(right)) => left == right,
(Value::Boolean(left), Value::Boolean(right)) => left == right,
(Value::String(left), Value::String(right)) => {
left.read().unwrap().as_str() == right.read().unwrap().as_str()
}
2023-10-01 16:17:27 +00:00
(Value::List(left), Value::List(right)) => left == right,
(Value::Map(left), Value::Map(right)) => left == right,
(Value::Function(left), Value::Function(right)) => left == right,
(Value::Option(left), Value::Option(right)) => left == right,
2024-01-06 06:05:13 +00:00
(Value::Structure(left), Value::Structure(right)) => left == right,
2023-10-01 16:17:27 +00:00
_ => false,
}
}
}
2023-08-22 15:40:50 +00:00
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Value {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Value::String(left), Value::String(right)) => left
.read()
.unwrap()
.as_str()
.cmp(right.read().unwrap().as_str()),
2023-10-05 12:03:14 +00:00
(Value::String(_), _) => Ordering::Greater,
(Value::Float(left), Value::Float(right)) => left.total_cmp(right),
(Value::Integer(left), Value::Integer(right)) => left.cmp(right),
2023-10-28 14:28:43 +00:00
(Value::Float(float), Value::Integer(integer)) => {
let int_as_float = *integer as f64;
float.total_cmp(&int_as_float)
}
(Value::Integer(integer), Value::Float(float)) => {
let int_as_float = *integer as f64;
int_as_float.total_cmp(float)
}
(Value::Float(_), _) => Ordering::Greater,
2023-10-05 12:03:14 +00:00
(Value::Integer(_), _) => Ordering::Greater,
(Value::Boolean(left), Value::Boolean(right)) => left.cmp(right),
(Value::Boolean(_), _) => Ordering::Greater,
2023-08-22 15:40:50 +00:00
(Value::List(left), Value::List(right)) => left.cmp(right),
(Value::List(_), _) => Ordering::Greater,
(Value::Map(left), Value::Map(right)) => left.cmp(right),
(Value::Map(_), _) => Ordering::Greater,
(Value::Function(left), Value::Function(right)) => left.cmp(right),
(Value::Function(_), _) => Ordering::Greater,
2024-01-06 06:05:13 +00:00
(Value::Structure(left), Value::Structure(right)) => left.cmp(right),
(Value::Structure(_), _) => Ordering::Greater,
(Value::Option(left), Value::Option(right)) => left.cmp(right),
(Value::Option(_), _) => Ordering::Less,
2023-08-22 15:40:50 +00:00
}
}
}
impl Serialize for Value {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Value::String(inner) => serializer.serialize_str(inner.read().unwrap().as_str()),
2023-10-05 12:03:14 +00:00
Value::Float(inner) => serializer.serialize_f64(*inner),
Value::Integer(inner) => serializer.serialize_i64(*inner),
Value::Boolean(inner) => serializer.serialize_bool(*inner),
2023-08-22 15:40:50 +00:00
Value::List(inner) => {
2023-10-26 22:03:59 +00:00
let items = inner.items();
let mut list = serializer.serialize_tuple(items.len())?;
2023-08-22 15:40:50 +00:00
2023-10-26 22:03:59 +00:00
for value in items.iter() {
2023-10-24 00:45:47 +00:00
list.serialize_element(value)?;
2023-08-22 15:40:50 +00:00
}
2023-10-24 00:45:47 +00:00
list.end()
2023-08-22 15:40:50 +00:00
}
Value::Option(inner) => inner.serialize(serializer),
2023-08-22 15:40:50 +00:00
Value::Map(inner) => inner.serialize(serializer),
Value::Function(inner) => inner.serialize(serializer),
2024-01-06 06:05:13 +00:00
Value::Structure(inner) => inner.serialize(serializer),
2023-08-22 15:40:50 +00:00
}
}
}
impl Display for Value {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
2024-01-06 13:53:31 +00:00
Value::String(string) => write!(f, "{}", string.read().unwrap()),
2023-10-14 18:18:13 +00:00
Value::Float(float) => write!(f, "{float}"),
Value::Integer(int) => write!(f, "{int}"),
Value::Boolean(boolean) => write!(f, "{boolean}"),
Value::Option(option) => {
if let Some(value) = option {
write!(f, "some({})", value)
} else {
write!(f, "none")
}
}
2024-01-01 15:09:11 +00:00
Value::List(list) => write!(f, "{list}"),
2023-08-22 15:40:50 +00:00
Value::Map(map) => write!(f, "{map}"),
Value::Function(function) => write!(f, "{function}"),
2024-01-06 08:47:54 +00:00
Value::Structure(structure) => write!(f, "{structure}"),
2023-08-22 15:40:50 +00:00
}
}
}
impl From<String> for Value {
fn from(string: String) -> Self {
Value::string(string)
2023-08-22 15:40:50 +00:00
}
}
impl From<&str> for Value {
fn from(string: &str) -> Self {
Value::string(string.to_string())
2023-08-22 15:40:50 +00:00
}
}
impl From<f64> for Value {
fn from(float: f64) -> Self {
2023-10-05 12:03:14 +00:00
Value::Float(float)
2023-08-22 15:40:50 +00:00
}
}
impl From<i64> for Value {
fn from(int: i64) -> Self {
2023-10-05 12:03:14 +00:00
Value::Integer(int)
2023-08-22 15:40:50 +00:00
}
}
impl From<bool> for Value {
fn from(boolean: bool) -> Self {
2023-10-05 12:03:14 +00:00
Value::Boolean(boolean)
2023-08-22 15:40:50 +00:00
}
}
impl From<Vec<Value>> for Value {
2023-10-24 00:45:47 +00:00
fn from(vec: Vec<Value>) -> Self {
2023-10-26 22:03:59 +00:00
Value::List(List::with_items(vec))
2023-08-22 15:40:50 +00:00
}
}
impl From<Value> for Result<Value> {
fn from(value: Value) -> Self {
Ok(value)
}
}
impl From<()> for Value {
fn from(_: ()) -> Self {
2023-12-31 14:14:43 +00:00
Value::none()
2023-08-22 15:40:50 +00:00
}
}
impl TryFrom<Value> for String {
type Error = Error;
fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
if let Value::String(rw_lock) = value {
Ok(rw_lock.read()?.to_string())
2023-08-22 15:40:50 +00:00
} else {
Err(Error::ExpectedString { actual: value })
}
}
}
impl TryFrom<Value> for f64 {
type Error = Error;
fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
2023-10-05 12:03:14 +00:00
if let Value::Float(value) = value {
2023-08-22 15:40:50 +00:00
Ok(value)
} else {
Err(Error::ExpectedFloat { actual: value })
}
}
}
impl TryFrom<Value> for i64 {
type Error = Error;
fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
2023-10-05 12:03:14 +00:00
if let Value::Integer(value) = value {
2023-08-22 15:40:50 +00:00
Ok(value)
} else {
2023-11-27 15:27:44 +00:00
Err(Error::ExpectedInteger { actual: value })
2023-08-22 15:40:50 +00:00
}
}
}
impl TryFrom<Value> for bool {
type Error = Error;
fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
2023-10-05 12:03:14 +00:00
if let Value::Boolean(value) = value {
2023-08-22 15:40:50 +00:00
Ok(value)
} else {
Err(Error::ExpectedBoolean { actual: value })
}
}
}
struct ValueVisitor {
marker: PhantomData<fn() -> Value>,
}
impl ValueVisitor {
fn new() -> Self {
ValueVisitor {
marker: PhantomData,
}
}
}
impl<'de> Visitor<'de> for ValueVisitor {
type Value = Value;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("Dust-compatible data format.")
2023-08-22 15:40:50 +00:00
}
fn visit_bool<E>(self, v: bool) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
2023-10-05 12:03:14 +00:00
Ok(Value::Boolean(v))
2023-08-22 15:40:50 +00:00
}
fn visit_i8<E>(self, v: i8) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_i64(v as i64)
}
fn visit_i16<E>(self, v: i16) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_i64(v as i64)
}
fn visit_i32<E>(self, v: i32) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_i64(v as i64)
}
fn visit_i64<E>(self, v: i64) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
2023-10-05 12:03:14 +00:00
Ok(Value::Integer(v))
2023-08-22 15:40:50 +00:00
}
fn visit_i128<E>(self, v: i128) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
if v > i64::MAX as i128 {
2023-10-05 12:03:14 +00:00
Ok(Value::Integer(i64::MAX))
2023-08-22 15:40:50 +00:00
} else {
2023-10-05 12:03:14 +00:00
Ok(Value::Integer(v as i64))
2023-08-22 15:40:50 +00:00
}
}
fn visit_u8<E>(self, v: u8) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_u64(v as u64)
}
fn visit_u16<E>(self, v: u16) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_u64(v as u64)
}
fn visit_u32<E>(self, v: u32) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_u64(v as u64)
}
fn visit_u64<E>(self, v: u64) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_i64(v as i64)
}
fn visit_u128<E>(self, v: u128) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_i128(v as i128)
}
fn visit_f32<E>(self, v: f32) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_f64(v as f64)
}
fn visit_f64<E>(self, v: f64) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
2023-10-05 12:03:14 +00:00
Ok(Value::Float(v))
2023-08-22 15:40:50 +00:00
}
fn visit_char<E>(self, v: char) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(&v.to_string())
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Value::string(v.to_string()))
2023-08-22 15:40:50 +00:00
}
fn visit_borrowed_str<E>(self, v: &'de str) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(v)
}
fn visit_string<E>(self, v: String) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Value::string(v))
2023-08-22 15:40:50 +00:00
}
fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
let _ = v;
Err(serde::de::Error::invalid_type(
serde::de::Unexpected::Bytes(v),
&self,
))
}
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_bytes(v)
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_bytes(&v)
}
fn visit_none<E>(self) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
2023-12-31 14:14:43 +00:00
Ok(Value::none())
2023-08-22 15:40:50 +00:00
}
fn visit_some<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Value::Option(Some(Box::new(Value::deserialize(
deserializer,
)?))))
2023-08-22 15:40:50 +00:00
}
fn visit_unit<E>(self) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
2023-12-31 14:14:43 +00:00
Ok(Value::none())
2023-08-22 15:40:50 +00:00
}
fn visit_newtype_struct<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
let _ = deserializer;
Err(serde::de::Error::invalid_type(
serde::de::Unexpected::NewtypeStruct,
&self,
))
}
fn visit_seq<A>(self, mut access: A) -> std::result::Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut list = Vec::new();
while let Some(value) = access.next_element()? {
list.push(value);
}
2023-10-26 22:03:59 +00:00
Ok(Value::List(List::with_items(list)))
2023-08-22 15:40:50 +00:00
}
fn visit_map<M>(self, mut access: M) -> std::result::Result<Value, M::Error>
where
M: MapAccess<'de>,
{
2023-10-29 23:31:06 +00:00
let map = Map::new();
2023-08-22 15:40:50 +00:00
while let Some((key, value)) = access.next_entry::<String, Value>()? {
map.set(key, value, None).unwrap();
2023-08-22 15:40:50 +00:00
}
Ok(Value::Map(map))
}
fn visit_enum<A>(self, data: A) -> std::result::Result<Self::Value, A::Error>
where
A: serde::de::EnumAccess<'de>,
{
let _ = data;
Err(serde::de::Error::invalid_type(
serde::de::Unexpected::Enum,
&self,
))
}
fn __private_visit_untagged_option<D>(self, _: D) -> std::result::Result<Self::Value, ()>
where
D: serde::Deserializer<'de>,
{
Err(())
}
}
impl<'de> Deserialize<'de> for Value {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(ValueVisitor::new())
}
}