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::marker::PhantomData; 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::IOResult; use super::signed_integer::SignedInteger; use crate::error::{Error, ExpectedKind, Received}; pub trait Domain: Sized + Debug + Eq + Hash + Ord { fn from_preserves(v: IOValue) -> IOResult; fn as_preserves(&self) -> IOValue; } pub trait Embeddable: Domain + Clone {} impl Embeddable for T where T: Domain + Clone {} impl Domain for Arc { fn from_preserves(v: IOValue) -> IOResult { Ok(Arc::new(D::from_preserves(v)?)) } fn as_preserves(&self) -> IOValue { D::as_preserves(self) } } pub trait NestedValue: Sized + Debug + Clone + Eq + Hash + Ord { 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 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 copy_via, E: Embeddable, F>(&self, f: &F) -> IOResult where F: Fn(&D) -> IOResult> { Ok(M::wrap(self.annotations().copy_via(f)?, self.value().copy_via(f)?)) } fn to_io_value(&self) -> IOValue { self.copy_via(&|d| Ok(d.as_preserves().value().clone())).unwrap() } fn from_io_value(v: &IOValue) -> IOResult { v.copy_via(&|d| Ok(Value::Embedded(D::from_preserves(d.clone())?))) } } /// The `Value`s from the specification. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Value where N: NestedValue, D: Embeddable { Boolean(bool), Float(Float), Double(Double), SignedInteger(SignedInteger), String(String), ByteString(Vec), Symbol(String), Record(Record), Sequence(Vec), Set(Set), Dictionary(Map), Embedded(D), } /// Single-precision IEEE 754 Value #[derive(Clone, Debug)] pub struct Float(pub f32); /// Double-precision IEEE 754 Value #[derive(Clone, 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, D: Embeddable> From for Value { fn from(v: bool) -> Self { Value::Boolean(v) } } impl, D: Embeddable> From for Value { fn from(v: f32) -> Self { Value::Float(Float::from(v)) } } impl, D: Embeddable> From<&Float> for Value { fn from(v: &Float) -> Self { Value::Float(v.clone()) } } impl, D: Embeddable> From for Value { fn from(v: f64) -> Self { Value::Double(Double::from(v)) } } impl, D: Embeddable> From<&Double> for Value { fn from(v: &Double) -> Self { Value::Double(v.clone()) } } impl, D: Embeddable> From for Value { fn from(v: u8) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: i8) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: u16) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: i16) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: u32) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: i32) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: u64) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: i64) -> Self { Value::from(i128::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: u128) -> Self { Value::SignedInteger(SignedInteger::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: i128) -> Self { Value::SignedInteger(SignedInteger::from(v)) } } impl, D: Embeddable> From<&BigInt> for Value { fn from(v: &BigInt) -> Self { Value::SignedInteger(SignedInteger::from(Cow::Borrowed(v))) } } impl, D: Embeddable> From<&SignedInteger> for Value { fn from(v: &SignedInteger) -> Self { Value::SignedInteger(v.clone()) } } impl, D: Embeddable> From<&str> for Value { fn from(v: &str) -> Self { Value::String(String::from(v)) } } impl, D: Embeddable> From for Value { fn from(v: String) -> Self { Value::String(v) } } impl, D: Embeddable> From<&String> for Value { fn from(v: &String) -> Self { Value::String(v.to_owned()) } } impl, D: Embeddable> From<&[u8]> for Value { fn from(v: &[u8]) -> Self { Value::ByteString(Vec::from(v)) } } // impl, D: Embeddable> From> for Value { fn from(v: Vec) -> Self { Value::ByteString(v) } } impl, D: Embeddable> From> for Value { fn from(v: Vec) -> Self { Value::Sequence(v) } } impl, D: Embeddable> From> for Value { fn from(v: Set) -> Self { Value::Set(v) } } impl, D: Embeddable> From> for Value { fn from(v: Map) -> Self { Value::Dictionary(v) } } impl, D: Embeddable> 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, D: Embeddable> Value { pub fn wrap(self) -> N { N::wrap(Annotations::empty(), self) } fn expected(&self, k: ExpectedKind) -> Error { Error::Expected(k, Received::ReceivedOtherValue(self.clone().wrap().to_io_value())) } 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 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_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 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 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(Value::symbol(label).wrap(), 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 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 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 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<&D> { if let Value::Embedded(d) = self { Some(d) } else { None } } pub fn to_embedded(&self) -> Result<&D, Error> { self.as_embedded().ok_or_else(|| self.expected(ExpectedKind::Embedded)) } pub fn copy_via, E: Embeddable, F>(&self, f: &F) -> IOResult> where F: Fn(&D) -> IOResult> { 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)?, }) } } impl, D: Embeddable> Index for Value { type Output = N; fn index(&self, i: usize) -> &Self::Output { &self.as_sequence().unwrap()[i] } } impl, D: Embeddable> IndexMut for Value { fn index_mut(&mut self, i: usize) -> &mut Self::Output { &mut self.as_sequence_mut().unwrap()[i] } } impl, D: Embeddable> 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()) } } pub fn serialize_nested_value(v: &N, serializer: S) -> Result where S: serde::Serializer, N: NestedValue + serde::Serialize { super::magic::output_value(serializer, v.to_io_value()) } pub fn deserialize_nested_value<'de, D, N, Dom: Embeddable>(deserializer: D) -> Result where D: serde::Deserializer<'de>, N: NestedValue + serde::Deserialize<'de> { N::from_io_value(&super::magic::input_value(deserializer)?) .map_err(|e| serde::de::Error::custom(format!("{:?}", e))) } //--------------------------------------------------------------------------- #[derive(Clone)] pub struct Annotations, D: Embeddable>(Option>, PhantomData); impl, D: Embeddable> Annotations { pub fn empty() -> Self { Annotations(None, PhantomData) } pub fn new(anns: Option>) -> Self { Annotations(anns, PhantomData) } 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 modify(&mut self, f: F) -> &mut Self where F: FnOnce(&mut Vec) { let mut v: Vec = self.0.take().unwrap_or_else(Vec::new); f(&mut v); self.0 = if v.is_empty() { None } else { Some(v) }; self } pub fn copy_via, E: Embeddable, F>(&self, f: &F) -> IOResult> where F: Fn(&D) -> IOResult> { Ok(match &self.0 { None => Annotations(None, PhantomData), Some(b) => Annotations(Some(b.iter().map(|a| a.copy_via(f)).collect::, _>>()?), PhantomData), }) } } /// A possibly-annotated Value, with annotations (themselves /// possibly-annotated) in order of appearance. #[derive(Clone)] pub struct AnnotatedValue, D: Embeddable>(pub Annotations, pub Value); impl, D: Embeddable> AnnotatedValue { fn new(anns: Annotations, value: Value) -> Self { AnnotatedValue(anns, value) } } impl, D: Embeddable> PartialEq for AnnotatedValue { fn eq(&self, other: &Self) -> bool { self.1.eq(&other.1) } } impl, D: Embeddable> Eq for AnnotatedValue {} impl, D: Embeddable> Hash for AnnotatedValue { fn hash(&self, state: &mut H) { self.1.hash(state); } } impl, D: Embeddable> PartialOrd for AnnotatedValue { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl, D: Embeddable> 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, D>); 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 { 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) } } impl serde::Serialize for PlainValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de, Dom: Embeddable> serde::Deserialize<'de> for PlainValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } } //--------------------------------------------------------------------------- use std::rc::Rc; #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RcValue(Rc, D>>); impl NestedValue for RcValue { 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) } } impl serde::Serialize for RcValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de, Dom: Embeddable> serde::Deserialize<'de> for RcValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ArcValue(Arc, D>>); impl NestedValue for ArcValue { 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) } } impl serde::Serialize for ArcValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de, Dom: Embeddable> serde::Deserialize<'de> for ArcValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct IOValue(Arc>); pub type UnwrappedIOValue = Value; impl Domain for IOValue { fn from_preserves(v: IOValue) -> IOResult { Ok(v) } fn as_preserves(&self) -> IOValue { self.clone() } } lazy_static! { pub static ref FALSE: IOValue = IOValue(Arc::new(AnnotatedValue(Annotations::empty(), Value::Boolean(false)))); pub static ref TRUE: IOValue = IOValue(Arc::new(AnnotatedValue(Annotations::empty(), Value::Boolean(true)))); pub static ref EMPTY_SEQ: IOValue = IOValue(Arc::new(AnnotatedValue(Annotations::empty(), Value::Sequence(Vec::new())))); } impl NestedValue for IOValue { 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(), } } fn to_io_value(&self) -> IOValue { self.clone() } fn from_io_value(v: &IOValue) -> IOResult { Ok(v.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 { serialize_nested_value(self, serializer) } } impl<'de> serde::Deserialize<'de> for IOValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } }