use num::bigint::BigInt; use num::traits::cast::ToPrimitive; use std::borrow::Cow; use std::cmp::Ordering; use std::convert::From; use std::convert::TryFrom; use std::convert::TryInto; use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::ops::Index; use std::ops::IndexMut; use std::string::String; use std::sync::Arc; use std::vec::Vec; pub use std::collections::BTreeSet as Set; pub use std::collections::BTreeMap as Map; use super::signed_integer::SignedInteger; use crate::error::{Error, ExpectedKind, Received}; pub trait Domain: Sized + Debug + Eq + Hash + Ord {} pub trait Embeddable: Domain + Clone {} impl Embeddable for T where T: Domain + Clone {} impl Domain for Arc {} pub trait NestedValue: Sized + Debug + Clone + Eq + Hash + Ord { type Embedded: Embeddable; fn new(v: V) -> Self where Value: From { Value::from(v).wrap() } fn domain(e: E) -> Self where Self::Embedded: From { Value::Embedded(e.into()).wrap() } fn symbol(n: &str) -> Self { Value::symbol(n).wrap() } fn bytestring<'a, V: Into>>(v: V) -> Self { Value::bytestring(v).wrap() } fn wrap(anns: Annotations, v: Value) -> Self; fn annotations(&self) -> &Annotations; fn value(&self) -> &Value; fn pieces(self) -> (Annotations, Value); fn value_owned(self) -> Value; fn value_class(&self) -> ValueClass { self.value().value_class() } fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for ann in self.annotations().slice() { write!(f, "@{:?} ", ann)?; } self.value().fmt(f) } fn strip_annotations>(&self) -> M { M::wrap(Annotations::empty(), self.value().strip_annotations()) } fn copy_via(&self, f: &mut F) -> Result where F: FnMut(&Self::Embedded) -> Result, Err> { Ok(M::wrap(self.annotations().copy_via(f)?, self.value().copy_via(f)?)) } fn foreach_embedded(&self, f: &mut F) -> Result<(), Err> where F: FnMut(&Self::Embedded) -> Result<(), Err> { match &self.annotations().0 { None => (), Some(vs) => for v in vs.iter() { v.foreach_embedded(f)? }, } self.value().foreach_embedded(f) } } /// The `Value`s from the specification. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Value { Boolean(bool), Float(Float), Double(Double), SignedInteger(SignedInteger), String(String), ByteString(Vec), Symbol(String), Record(Record), Sequence(Vec), Set(Set), Dictionary(Map), Embedded(N::Embedded), } /// The kinds of `Value` from the specification. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ValueClass { Atomic(AtomClass), Compound(CompoundClass), Embedded, } /// The kinds of `Atom` from the specification. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum AtomClass { Boolean, Float, Double, SignedInteger, String, ByteString, Symbol, } /// The kinds of `Compound` from the specification. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum CompoundClass { Record, Sequence, Set, Dictionary, } /// Single-precision IEEE 754 Value #[derive(Clone, Copy, Debug)] pub struct Float(pub f32); /// Double-precision IEEE 754 Value #[derive(Clone, Copy, Debug)] pub struct Double(pub f64); /// A Record `Value` -- INVARIANT: length always non-zero #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Record(pub Vec); impl Record { pub fn label(&self) -> &N { &self.0[0] } pub fn label_mut(&mut self) -> &mut N { &mut self.0[0] } pub fn arity(&self) -> usize { self.0.len() - 1 } pub fn fields(&self) -> &[N] { &self.0[1..] } pub fn fields_mut(&mut self) -> &mut [N] { &mut self.0[1..] } pub fn fields_vec(&self) -> &Vec { &self.0 } pub fn fields_vec_mut(&mut self) -> &mut Vec { &mut self.0 } pub fn finish(self) -> Value where N: NestedValue { Value::Record(self) } } impl From for Float { fn from(v: f32) -> Self { Float(v) } } impl From for f32 { fn from(v: Float) -> Self { v.0 } } impl Hash for Float { fn hash(&self, state: &mut H) { self.0.to_bits().hash(state); } } impl PartialEq for Float { fn eq(&self, other: &Self) -> bool { self.0.to_bits() == other.0.to_bits() } } impl Ord for Float { fn cmp(&self, other: &Self) -> Ordering { let mut a: u32 = self.0.to_bits(); let mut b: u32 = other.0.to_bits(); if a & 0x8000_0000 != 0 { a ^= 0x7fff_ffff; } if b & 0x8000_0000 != 0 { b ^= 0x7fff_ffff; } (a as i32).cmp(&(b as i32)) } } impl PartialOrd for Float { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Eq for Float {} impl From for Double { fn from(v: f64) -> Self { Double(v) } } impl From for f64 { fn from(v: Double) -> Self { v.0 } } impl Hash for Double { fn hash(&self, state: &mut H) { self.0.to_bits().hash(state); } } impl PartialEq for Double { fn eq(&self, other: &Self) -> bool { self.0.to_bits() == other.0.to_bits() } } impl Ord for Double { fn cmp(&self, other: &Self) -> Ordering { let mut a: u64 = self.0.to_bits(); let mut b: u64 = other.0.to_bits(); if a & 0x8000_0000_0000_0000 != 0 { a ^= 0x7fff_ffff_ffff_ffff; } if b & 0x8000_0000_0000_0000 != 0 { b ^= 0x7fff_ffff_ffff_ffff; } (a as i64).cmp(&(b as i64)) } } impl PartialOrd for Double { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Eq for Double {} impl From for Value { fn from(v: bool) -> Self { Value::Boolean(v) } } impl From<&bool> for Value { fn from(v: &bool) -> Self { Value::Boolean(*v) } } impl From for Value { fn from(v: f32) -> Self { Value::Float(Float::from(v)) } } impl From<&f32> for Value { fn from(v: &f32) -> Self { Value::Float(Float::from(*v)) } } impl From<&Float> for Value { fn from(v: &Float) -> Self { Value::Float(v.clone()) } } impl From for Value { fn from(v: f64) -> Self { Value::Double(Double::from(v)) } } impl From<&f64> for Value { fn from(v: &f64) -> Self { Value::Double(Double::from(*v)) } } impl From<&Double> for Value { fn from(v: &Double) -> Self { Value::Double(v.clone()) } } impl From for Value { fn from(v: u8) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: i8) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: u16) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: i16) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: u32) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: i32) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: u64) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: i64) -> Self { Value::from(i128::from(v)) } } impl From for Value { fn from(v: usize) -> Self { Value::from(v as u128) } } impl From for Value { fn from(v: isize) -> Self { Value::from(v as i128) } } impl From for Value { fn from(v: u128) -> Self { Value::SignedInteger(SignedInteger::from(v)) } } impl From for Value { fn from(v: i128) -> Self { Value::SignedInteger(SignedInteger::from(v)) } } impl From<&BigInt> for Value { fn from(v: &BigInt) -> Self { Value::SignedInteger(SignedInteger::from(Cow::Borrowed(v))) } } impl From for Value { fn from(v: BigInt) -> Self { Value::SignedInteger(SignedInteger::from(Cow::Owned(v))) } } impl From<&SignedInteger> for Value { fn from(v: &SignedInteger) -> Self { Value::SignedInteger(v.clone()) } } impl From<&str> for Value { fn from(v: &str) -> Self { Value::String(String::from(v)) } } impl From for Value { fn from(v: String) -> Self { Value::String(v) } } impl From<&String> for Value { fn from(v: &String) -> Self { Value::String(v.to_owned()) } } impl From<&[u8]> for Value { fn from(v: &[u8]) -> Self { Value::ByteString(Vec::from(v)) } } // impl From> for Value { fn from(v: Vec) -> Self { Value::ByteString(v) } } impl From> for Value { fn from(v: Vec) -> Self { Value::Sequence(v) } } impl From> for Value { fn from(v: Set) -> Self { Value::Set(v) } } impl From> for Value { fn from(v: Map) -> Self { Value::Dictionary(v) } } impl Debug for Value { // Not *quite* a formatter for the Preserves text syntax, since it // doesn't escape strings/symbols properly. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Value::Boolean(false) => f.write_str("#f"), Value::Boolean(true) => f.write_str("#t"), Value::Float(Float(v)) => write!(f, "{:?}f", v), Value::Double(Double(v)) => write!(f, "{:?}", v), Value::SignedInteger(v) => write!(f, "{}", v), Value::String(v) => write!(f, "{:?}", v), // TODO: proper escaping! Value::ByteString(v) => { f.write_str("#x\"")?; for b in v { write!(f, "{:02x}", b)? } f.write_str("\"") } Value::Symbol(v) => { // TODO: proper escaping! if v.is_empty() { f.write_str("||") } else { write!(f, "{}", v) } } Value::Record(r) => { f.write_str("<")?; r.label().fmt(f)?; for v in r.fields() { f.write_str(" ")?; v.fmt(f)?; } f.write_str(">") } Value::Sequence(v) => v.fmt(f), Value::Set(v) => { f.write_str("#")?; f.debug_set().entries(v.iter()).finish() } Value::Dictionary(v) => f.debug_map().entries(v.iter()).finish(), Value::Embedded(d) => write!(f, "#!{:?}", d), } } } //--------------------------------------------------------------------------- impl Value { pub fn wrap(self) -> N { N::wrap(Annotations::empty(), self) } fn value_class(&self) -> ValueClass { match self { Value::Boolean(_) => ValueClass::Atomic(AtomClass::Boolean), Value::Float(_) => ValueClass::Atomic(AtomClass::Float), Value::Double(_) => ValueClass::Atomic(AtomClass::Double), Value::SignedInteger(_) => ValueClass::Atomic(AtomClass::SignedInteger), Value::String(_) => ValueClass::Atomic(AtomClass::String), Value::ByteString(_) => ValueClass::Atomic(AtomClass::ByteString), Value::Symbol(_) => ValueClass::Atomic(AtomClass::Symbol), Value::Record(_) => ValueClass::Compound(CompoundClass::Record), Value::Sequence(_) => ValueClass::Compound(CompoundClass::Sequence), Value::Set(_) => ValueClass::Compound(CompoundClass::Set), Value::Dictionary(_) => ValueClass::Compound(CompoundClass::Dictionary), Value::Embedded(_) => ValueClass::Embedded, } } pub fn children(&self) -> Vec { match self { Value::Boolean(_) | Value::Float(_) | Value::Double(_) | Value::SignedInteger(_) | Value::String(_) | Value::ByteString(_) | Value::Symbol(_) | Value::Embedded(_) => vec![], Value::Record(r) => r.fields().to_vec(), Value::Sequence(vs) => vs.clone(), Value::Set(s) => s.iter().cloned().collect(), Value::Dictionary(d) => d.values().cloned().collect(), } } fn expected(&self, k: ExpectedKind) -> Error { Error::Expected(k, Received::ReceivedOtherValue(format!("{:?}", self.clone().wrap()))) } pub fn is_boolean(&self) -> bool { self.as_boolean().is_some() } pub fn as_boolean(&self) -> Option { if let Value::Boolean(b) = self { Some(*b) } else { None } } pub fn as_boolean_mut(&mut self) -> Option<&mut bool> { if let Value::Boolean(b) = self { Some(b) } else { None } } pub fn to_boolean(&self) -> Result { self.as_boolean().ok_or_else(|| self.expected(ExpectedKind::Boolean)) } pub fn is_float(&self) -> bool { self.as_float().is_some() } pub fn as_float(&self) -> Option<&Float> { if let Value::Float(f) = self { Some(f) } else { None } } pub fn as_float_mut(&mut self) -> Option<&mut Float> { if let Value::Float(f) = self { Some(f) } else { None } } pub fn to_float(&self) -> Result<&Float, Error> { self.as_float().ok_or_else(|| self.expected(ExpectedKind::Float)) } pub fn is_f32(&self) -> bool { self.is_float() } pub fn as_f32(&self) -> Option { self.as_float().map(|f| f.0) } pub fn as_f32_mut(&mut self) -> Option<&mut f32> { self.as_float_mut().map(|f| &mut f.0) } pub fn to_f32(&self) -> Result { self.to_float().map(|f| f.0) } pub fn is_double(&self) -> bool { self.as_double().is_some() } pub fn as_double(&self) -> Option<&Double> { if let Value::Double(f) = self { Some(f) } else { None } } pub fn as_double_mut(&mut self) -> Option<&mut Double> { if let Value::Double(f) = self { Some(f) } else { None } } pub fn to_double(&self) -> Result<&Double, Error> { self.as_double().ok_or_else(|| self.expected(ExpectedKind::Double)) } pub fn is_f64(&self) -> bool { self.is_double() } pub fn as_f64(&self) -> Option { self.as_double().map(|f| f.0) } pub fn as_f64_mut(&mut self) -> Option<&mut f64> { self.as_double_mut().map(|f| &mut f.0) } pub fn to_f64(&self) -> Result { self.to_double().map(|f| f.0) } pub fn is_signedinteger(&self) -> bool { self.as_signedinteger().is_some() } pub fn as_signedinteger(&self) -> Option<&SignedInteger> { if let Value::SignedInteger(n) = self { Some(n) } else { None } } pub fn as_signedinteger_mut(&mut self) -> Option<&mut SignedInteger> { if let Value::SignedInteger(n) = self { Some(n) } else { None } } pub fn to_signedinteger(&self) -> Result<&SignedInteger, Error> { self.as_signedinteger().ok_or_else(|| self.expected(ExpectedKind::SignedInteger)) } pub fn is_i(&self) -> bool { self.as_i().is_some() } pub fn as_i(&self) -> Option { self.as_signedinteger().and_then(|n| n.try_into().ok()) } pub fn to_i(&self) -> Result { self.as_i().ok_or_else(|| self.expected(ExpectedKind::SignedIntegerI128)) } pub fn is_u(&self) -> bool { self.as_u().is_some() } pub fn as_u(&self) -> Option { self.as_signedinteger().and_then(|n| n.try_into().ok()) } pub fn to_u(&self) -> Result { self.as_u().ok_or_else(|| self.expected(ExpectedKind::SignedIntegerU128)) } pub fn as_u8(&self) -> Option { self.as_u().and_then(|i| i.to_u8()) } pub fn as_i8(&self) -> Option { self.as_i().and_then(|i| i.to_i8()) } pub fn as_u16(&self) -> Option { self.as_u().and_then(|i| i.to_u16()) } pub fn as_i16(&self) -> Option { self.as_i().and_then(|i| i.to_i16()) } pub fn as_u32(&self) -> Option { self.as_u().and_then(|i| i.to_u32()) } pub fn as_i32(&self) -> Option { self.as_i().and_then(|i| i.to_i32()) } pub fn as_u64(&self) -> Option { self.as_u().and_then(|i| i.to_u64()) } pub fn as_i64(&self) -> Option { self.as_i().and_then(|i| i.to_i64()) } pub fn as_u128(&self) -> Option { self.as_u().and_then(|i| i.to_u128()) } pub fn as_i128(&self) -> Option { self.as_i().and_then(|i| i.to_i128()) } pub fn as_usize(&self) -> Option { self.as_u().and_then(|i| i.to_usize()) } pub fn as_isize(&self) -> Option { self.as_i().and_then(|i| i.to_isize()) } pub fn to_i8(&self) -> Result { match self.as_i() { Some(i) => i.to_i8().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_u8(&self) -> Result { match self.as_u() { Some(i) => i.to_u8().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_i16(&self) -> Result { match self.as_i() { Some(i) => i.to_i16().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_u16(&self) -> Result { match self.as_u() { Some(i) => i.to_u16().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_i32(&self) -> Result { match self.as_i() { Some(i) => i.to_i32().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_u32(&self) -> Result { match self.as_u() { Some(i) => i.to_u32().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_i64(&self) -> Result { match self.as_i() { Some(i) => i.to_i64().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_u64(&self) -> Result { match self.as_u() { Some(i) => i.to_u64().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_i128(&self) -> Result { match self.as_i() { Some(i) => i.to_i128().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_u128(&self) -> Result { match self.as_u() { Some(i) => i.to_u128().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_isize(&self) -> Result { match self.as_i() { Some(i) => i.to_isize().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_usize(&self) -> Result { match self.as_u() { Some(i) => i.to_usize().ok_or_else(|| Error::NumberOutOfRange(BigInt::from(i))), None => Err(self.expected(ExpectedKind::SignedInteger)), } } pub fn to_char(&self) -> Result { let fs = self.to_simple_record("UnicodeScalar", Some(1))?; let c = fs[0].value().to_u32()?; char::try_from(c).map_err(|_| Error::InvalidUnicodeScalar(c)) } pub fn is_string(&self) -> bool { self.as_string().is_some() } pub fn as_string(&self) -> Option<&String> { if let Value::String(s) = self { Some(s) } else { None } } pub fn as_string_mut(&mut self) -> Option<&mut String> { if let Value::String(s) = self { Some(s) } else { None } } pub fn to_string(&self) -> Result<&String, Error> { self.as_string().ok_or_else(|| self.expected(ExpectedKind::String)) } pub fn bytestring<'a, V: Into>>(v: V) -> Self { Value::ByteString(v.into().into_owned()) } pub fn is_bytestring(&self) -> bool { self.as_bytestring().is_some() } pub fn as_bytestring(&self) -> Option<&Vec> { if let Value::ByteString(s) = self { Some(s) } else { None } } pub fn as_bytestring_mut(&mut self) -> Option<&mut Vec> { if let Value::ByteString(s) = self { Some(s) } else { None } } pub fn to_bytestring(&self) -> Result<&Vec, Error> { self.as_bytestring().ok_or_else(|| self.expected(ExpectedKind::ByteString)) } pub fn symbol(s: &str) -> Value { Value::Symbol(s.to_string()) } pub fn is_symbol(&self) -> bool { self.as_symbol().is_some() } pub fn as_symbol(&self) -> Option<&String> { if let Value::Symbol(s) = self { Some(s) } else { None } } pub fn as_symbol_mut(&mut self) -> Option<&mut String> { if let Value::Symbol(s) = self { Some(s) } else { None } } pub fn to_symbol(&self) -> Result<&String, Error> { self.as_symbol().ok_or_else(|| self.expected(ExpectedKind::Symbol)) } pub fn record(label: N, expected_arity: usize) -> Record { let mut v = Vec::with_capacity(expected_arity + 1); v.push(label); Record(v) } pub fn is_record(&self) -> bool { matches!(*self, Value::Record(_)) } pub fn as_record(&self, arity: Option) -> Option<&Record> { if let Value::Record(r) = self { match arity { Some(expected) if r.arity() == expected => Some(r), Some(_other) => None, None => Some(r) } } else { None } } pub fn into_record(self) -> Option> { match self { Value::Record(r) => Some(r), _ => None, } } pub fn as_record_mut(&mut self, arity: Option) -> Option<&mut Record> { if let Value::Record(r) = self { match arity { Some(expected) if r.arity() == expected => Some(r), Some(_other) => None, None => Some(r) } } else { None } } pub fn to_record(&self, arity: Option) -> Result<&Record, Error> { self.as_record(arity).ok_or_else(|| self.expected(ExpectedKind::Record(arity))) } pub fn simple_record(label: &str, expected_arity: usize) -> Record { Self::record(N::symbol(label), expected_arity) } pub fn simple_record0(label: &str) -> Value { Self::simple_record(label, 0).finish() } pub fn simple_record1(label: &str, field: N) -> Value { let mut r = Self::simple_record(label, 1); r.fields_vec_mut().push(field); r.finish() } pub fn is_simple_record(&self, label: &str, arity: Option) -> bool { self.as_simple_record(label, arity).is_some() } pub fn as_simple_record(&self, label: &str, arity: Option) -> Option<&[N]> { self.as_record(arity).and_then(|r| { match r.label().value() { Value::Symbol(s) if s == label => Some(r.fields()), _ => None } }) } pub fn to_simple_record(&self, label: &str, arity: Option) -> Result<&[N], Error> { self.as_simple_record(label, arity) .ok_or_else(|| self.expected(ExpectedKind::SimpleRecord(label.to_owned(), arity))) } pub fn to_option(&self) -> Result, Error> { match self.as_simple_record("None", Some(0)) { Some(_fs) => Ok(None), None => match self.as_simple_record("Some", Some(1)) { Some(fs) => Ok(Some(&fs[0])), None => Err(self.expected(ExpectedKind::Option)) } } } pub fn is_sequence(&self) -> bool { self.as_sequence().is_some() } pub fn as_sequence(&self) -> Option<&Vec> { if let Value::Sequence(s) = self { Some(s) } else { None } } pub fn into_sequence(self) -> Option> { match self { Value::Sequence(s) => Some(s), _ => None, } } pub fn as_sequence_mut(&mut self) -> Option<&mut Vec> { if let Value::Sequence(s) = self { Some(s) } else { None } } pub fn to_sequence(&self) -> Result<&Vec, Error> { self.as_sequence().ok_or_else(|| self.expected(ExpectedKind::Sequence)) } pub fn is_set(&self) -> bool { self.as_set().is_some() } pub fn as_set(&self) -> Option<&Set> { if let Value::Set(s) = self { Some(s) } else { None } } pub fn into_set(self) -> Option> { match self { Value::Set(s) => Some(s), _ => None, } } pub fn as_set_mut(&mut self) -> Option<&mut Set> { if let Value::Set(s) = self { Some(s) } else { None } } pub fn to_set(&self) -> Result<&Set, Error> { self.as_set().ok_or_else(|| self.expected(ExpectedKind::Set)) } pub fn is_dictionary(&self) -> bool { self.as_dictionary().is_some() } pub fn as_dictionary(&self) -> Option<&Map> { if let Value::Dictionary(s) = self { Some(s) } else { None } } pub fn into_dictionary(self) -> Option> { match self { Value::Dictionary(s) => Some(s), _ => None, } } pub fn as_dictionary_mut(&mut self) -> Option<&mut Map> { if let Value::Dictionary(s) = self { Some(s) } else { None } } pub fn to_dictionary(&self) -> Result<&Map, Error> { self.as_dictionary().ok_or_else(|| self.expected(ExpectedKind::Dictionary)) } pub fn is_embedded(&self) -> bool { self.as_embedded().is_some() } pub fn as_embedded(&self) -> Option<&N::Embedded> { if let Value::Embedded(d) = self { Some(d) } else { None } } pub fn to_embedded(&self) -> Result<&N::Embedded, Error> { self.as_embedded().ok_or_else(|| self.expected(ExpectedKind::Embedded)) } pub fn strip_annotations>(&self) -> Value { match self { Value::Boolean(b) => Value::Boolean(*b), Value::Float(f) => Value::Float(f.clone()), Value::Double(d) => Value::Double(d.clone()), Value::SignedInteger(n) => Value::SignedInteger(n.clone()), Value::String(s) => Value::String(s.clone()), Value::ByteString(v) => Value::ByteString(v.clone()), Value::Symbol(v) => Value::Symbol(v.clone()), Value::Record(r) => Value::Record(Record(r.fields_vec().iter().map( |a| a.strip_annotations()).collect())), Value::Sequence(v) => Value::Sequence(v.iter().map( |a| a.strip_annotations()).collect()), Value::Set(v) => Value::Set(v.iter().map( |a| a.strip_annotations()).collect()), Value::Dictionary(v) => Value::Dictionary(v.iter().map( |(a,b)| (a.strip_annotations(), b.strip_annotations())).collect()), Value::Embedded(d) => Value::Embedded(d.clone()), } } pub fn copy_via(&self, f: &mut F) -> Result, Err> where F: FnMut(&N::Embedded) -> Result, Err> { Ok(match self { Value::Boolean(b) => Value::Boolean(*b), Value::Float(f) => Value::Float(f.clone()), Value::Double(d) => Value::Double(d.clone()), Value::SignedInteger(n) => Value::SignedInteger(n.clone()), Value::String(s) => Value::String(s.clone()), Value::ByteString(v) => Value::ByteString(v.clone()), Value::Symbol(v) => Value::Symbol(v.clone()), Value::Record(r) => Value::Record(Record(r.fields_vec().iter().map(|a| a.copy_via(f)) .collect::, _>>()?)), Value::Sequence(v) => Value::Sequence(v.iter().map(|a| a.copy_via(f)) .collect::, _>>()?), Value::Set(v) => Value::Set(v.iter().map(|a| a.copy_via(f)) .collect::, _>>()?), Value::Dictionary(v) => Value::Dictionary(v.iter().map(|(a,b)| Ok((a.copy_via(f)?, b.copy_via(f)?))) .collect::, _>>()?), Value::Embedded(d) => f(d)?, }) } pub fn foreach_embedded(&self, f: &mut F) -> Result<(), Err> where F: FnMut(&N::Embedded) -> Result<(), Err> { match self { Value::Boolean(_) | Value::Float(_) | Value::Double(_) | Value::SignedInteger(_) | Value::String(_) | Value::ByteString(_) | Value::Symbol(_) => Ok(()), Value::Record(r) => Ok(for v in r.fields_vec() { v.foreach_embedded(f)? }), Value::Sequence(vs) => Ok(for v in vs { v.foreach_embedded(f)? }), Value::Set(vs) => Ok(for v in vs { v.foreach_embedded(f)? }), Value::Dictionary(d) => Ok(for (k, v) in d { k.foreach_embedded(f)?; v.foreach_embedded(f)?; }), Value::Embedded(d) => f(d), } } } impl Index for Value { type Output = N; fn index(&self, i: usize) -> &Self::Output { &self.as_sequence().unwrap()[i] } } impl IndexMut for Value { fn index_mut(&mut self, i: usize) -> &mut Self::Output { &mut self.as_sequence_mut().unwrap()[i] } } impl Index<&N> for Value { type Output = N; fn index(&self, i: &N) -> &Self::Output { &(*self.as_dictionary().unwrap())[i] } } //--------------------------------------------------------------------------- // This part is a terrible hack impl serde::Serialize for UnwrappedIOValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { super::magic::output_value(serializer, self.clone().wrap()) } } impl<'de> serde::Deserialize<'de> for UnwrappedIOValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { Ok(super::magic::input_value::<'de, D>(deserializer)?.value_owned()) } } //--------------------------------------------------------------------------- #[derive(Clone)] pub struct Annotations(Option>>); impl Annotations { pub fn empty() -> Self { Annotations(None) } pub fn new(anns: Option>) -> Self { Annotations(anns.map(Box::new)) } pub fn maybe_slice(&self) -> Option<&[N]> { match &self.0 { None => None, Some(b) => Some(&b[..]), } } pub fn slice(&self) -> &[N] { self.maybe_slice().unwrap_or(&[]) } pub fn to_vec(self) -> Vec { use std::ops::DerefMut; self.0.map(|mut b| std::mem::take(b.deref_mut())).unwrap_or_default() } pub fn modify(&mut self, f: F) -> &mut Self where F: FnOnce(&mut Vec) { match &mut self.0 { None => { let mut v = Vec::new(); f(&mut v); if !v.is_empty() { self.0 = Some(Box::new(v)); } } Some(b) => { use std::ops::DerefMut; f(b.deref_mut()); if b.is_empty() { self.0 = None; } } } self } pub fn copy_via(&self, f: &mut F) -> Result, Err> where F: FnMut(&N::Embedded) -> Result, Err> { Ok(match &self.0 { None => Annotations(None), Some(b) => Annotations(Some(Box::new(b.iter().map(|a| a.copy_via(f)).collect::, _>>()?))), }) } } /// A possibly-annotated Value, with annotations (themselves /// possibly-annotated) in order of appearance. #[derive(Clone)] pub struct AnnotatedValue(pub Annotations, pub Value); impl AnnotatedValue { fn new(anns: Annotations, value: Value) -> Self { AnnotatedValue(anns, value) } } impl PartialEq for AnnotatedValue { fn eq(&self, other: &Self) -> bool { self.1.eq(&other.1) } } impl Eq for AnnotatedValue {} impl Hash for AnnotatedValue { fn hash(&self, state: &mut H) { self.1.hash(state); } } impl PartialOrd for AnnotatedValue { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for AnnotatedValue { fn cmp(&self, other: &Self) -> Ordering { self.1.cmp(&other.1) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct PlainValue(AnnotatedValue>); impl PlainValue { pub fn annotations_mut(&mut self) -> &mut Annotations { &mut (self.0).0 } pub fn value_mut(&mut self) -> &mut Value { &mut (self.0).1 } } impl NestedValue for PlainValue { type Embedded = D; fn wrap(anns: Annotations, v: Value) -> Self { PlainValue(AnnotatedValue::new(anns, v)) } fn annotations(&self) -> &Annotations { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn pieces(self) -> (Annotations, Value) { let AnnotatedValue(anns, v) = self.0; (anns, v) } fn value_owned(self) -> Value { (self.0).1 } } impl Debug for PlainValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } //--------------------------------------------------------------------------- use std::rc::Rc; #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RcValue(Rc>>); impl NestedValue for RcValue { type Embedded = D; fn wrap(anns: Annotations, v: Value) -> Self { RcValue(Rc::new(AnnotatedValue::new(anns, v))) } fn annotations(&self) -> &Annotations { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn pieces(self) -> (Annotations, Value) { match Rc::try_unwrap(self.0) { Ok(AnnotatedValue(anns, v)) => (anns, v), Err(r) => (r.0.clone(), r.1.clone()), } } fn value_owned(self) -> Value { Rc::try_unwrap(self.0).unwrap_or_else(|_| panic!("value_owned on RcValue with refcount greater than one")).1 } } impl Debug for RcValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ArcValue(Arc>>); impl NestedValue for ArcValue { type Embedded = D; fn wrap(anns: Annotations, v: Value) -> Self { ArcValue(Arc::new(AnnotatedValue::new(anns, v))) } fn annotations(&self) -> &Annotations { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn pieces(self) -> (Annotations, Value) { match Arc::try_unwrap(self.0) { Ok(AnnotatedValue(anns, v)) => (anns, v), Err(r) => (r.0.clone(), r.1.clone()), } } fn value_owned(self) -> Value { Arc::try_unwrap(self.0).unwrap_or_else(|_| panic!("value_owned on ArcValue with refcount greater than one")).1 } } impl Debug for ArcValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct IOValue(Arc>); pub type UnwrappedIOValue = Value; impl Domain for IOValue {} impl NestedValue for IOValue { type Embedded = Self; fn wrap(anns: Annotations, v: Value) -> Self { IOValue(Arc::new(AnnotatedValue::new(anns, v))) } fn annotations(&self) -> &Annotations { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn pieces(self) -> (Annotations, Value) { match Arc::try_unwrap(self.0) { Ok(AnnotatedValue(anns, v)) => (anns, v), Err(r) => (r.0.clone(), r.1.clone()), } } fn value_owned(self) -> Value { match Arc::try_unwrap(self.0) { Ok(AnnotatedValue(_anns, v)) => v, Err(r) => r.1.clone(), } } } impl Debug for IOValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } impl serde::Serialize for IOValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { super::magic::output_value(serializer, self.clone()) } } impl<'de> serde::Deserialize<'de> for IOValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { super::magic::input_value(deserializer) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct DummyValue(AnnotatedValue>); impl Debug for DummyValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("<>") } } impl DummyValue { pub fn new() -> Self { DummyValue(AnnotatedValue::new(Annotations::empty(), Value::Boolean(false))) } } impl NestedValue for DummyValue { type Embedded = D; fn wrap(_anns: Annotations, _v: Value) -> Self { DummyValue::new() } fn annotations(&self) -> &Annotations { &self.0.0 } fn value(&self) -> &Value { &self.0.1 } fn pieces(self) -> (Annotations, Value) { (self.0.0, self.0.1) } fn value_owned(self) -> Value { self.0.1 } }