preserves/implementations/rust/oo/src/repr.rs

827 lines
33 KiB
Rust

use bytemuck::TransparentWrapper;
use std::borrow::{Cow, Borrow};
use std::cmp::Ordering;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::io;
use std::marker::PhantomData;
use std::sync::Arc;
use std::vec::Vec;
pub use std::collections::BTreeSet as Set;
pub use std::collections::BTreeMap as Map;
use crate::AtomClass;
use crate::CompoundClass;
use crate::Domain;
use crate::SignedInteger;
use crate::ValueClass;
use crate::Writer;
use crate::boundary as B;
use crate::domain::{NoEmbeddedDomainCodec, DomainEncode, IOValueDomainCodec};
use super::float::{eq_f32, eq_f64, cmp_f32, cmp_f64};
/// Atomic values from the specification.
pub trait Value<D: Domain>: Debug {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()>;
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static;
fn value_class(&self) -> ValueClass;
fn as_boolean(&self) -> Option<bool> { None }
fn as_float(&self) -> Option<f32> { None }
fn as_double(&self) -> Option<f64> { None }
fn is_signed_integer(&self) -> bool { false }
fn as_signed_integer(&self) -> Option<SignedInteger> { None }
fn as_string(&self) -> Option<Cow<'_, str>> { None }
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> { None }
fn as_symbol(&self) -> Option<Cow<'_, str>> { None }
fn is_record(&self) -> bool { false }
fn label(&self) -> &dyn Value<D> { panic!("Not a record") }
fn is_sequence(&self) -> bool { false }
fn len(&self) -> usize { panic!("Has no length") }
fn index(&self, _i: usize) -> &dyn Value<D> { panic!("Not indexable") }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> { panic!("Not iterable") }
fn is_set(&self) -> bool { false }
fn has(&self, _v: &dyn Value<D>) -> bool { false }
fn is_dictionary(&self) -> bool { false }
fn get(&self, _k: &dyn Value<D>) -> Option<&dyn Value<D>> { None }
fn entries(&self) -> Box<dyn Iterator<Item = (&dyn Value<D>, &dyn Value<D>)> + '_> { panic!("Not a dictionary") }
fn is_embedded(&self) -> bool { false }
fn embedded(&self) -> Cow<'_, D> { panic!("Not an embedded value") }
fn annotations(&self) -> Option<&[IOValue]> { None }
}
pub fn value<D: Domain, V: Value<D>>(v: &V) -> &dyn Value<D> {
v
}
pub fn owned<D: Domain, V: Value<D> + 'static>(v: V) -> Box<dyn Value<D>> {
Box::new(v)
}
pub fn iovalue<V: Value<IOValue> + 'static>(v: V) -> IOValue {
IOValue(Arc::new(v))
}
impl<'a, D: Domain, V: Value<D> + ?Sized> Value<D> for &'a V {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { (*self).write(w, enc) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { (*self).value_clone() }
fn value_class(&self) -> ValueClass { (*self).value_class() }
fn as_boolean(&self) -> Option<bool> { (*self).as_boolean() }
fn as_float(&self) -> Option<f32> { (*self).as_float() }
fn as_double(&self) -> Option<f64> { (*self).as_double() }
fn is_signed_integer(&self) -> bool { (*self).is_signed_integer() }
fn as_signed_integer(&self) -> Option<SignedInteger> { (*self).as_signed_integer() }
fn as_string(&self) -> Option<Cow<'_, str>> { (*self).as_string() }
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> { (*self).as_bytestring() }
fn as_symbol(&self) -> Option<Cow<'_, str>> { (*self).as_symbol() }
fn is_record(&self) -> bool { (*self).is_record() }
fn label(&self) -> &dyn Value<D> { (*self).label() }
fn is_sequence(&self) -> bool { (*self).is_sequence() }
fn len(&self) -> usize { (*self).len() }
fn index(&self, i: usize) -> &dyn Value<D> { (*self).index(i) }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> { (*self).iter() }
fn is_set(&self) -> bool { (*self).is_set() }
fn has(&self, v: &dyn Value<D>) -> bool { (*self).has(v) }
fn is_dictionary(&self) -> bool { (*self).is_dictionary() }
fn get<'value>(&'value self, k: &dyn Value<D>) -> Option<&'value dyn Value<D>> { (*self).get(k) }
fn entries(&self) -> Box<dyn Iterator<Item = (&dyn Value<D>, &dyn Value<D>)> + '_> { (*self).entries() }
fn is_embedded(&self) -> bool { (*self).is_embedded() }
fn embedded(&self) -> Cow<'_, D> { (*self).embedded() }
fn annotations(&self) -> Option<&[IOValue]> { (*self).annotations() }
}
impl<D: Domain> Value<D> for Box<dyn Value<D>> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { self.as_ref().write(w, enc) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { self.as_ref().value_clone() }
fn value_class(&self) -> ValueClass { self.as_ref().value_class() }
fn as_boolean(&self) -> Option<bool> { self.as_ref().as_boolean() }
fn as_float(&self) -> Option<f32> { self.as_ref().as_float() }
fn as_double(&self) -> Option<f64> { self.as_ref().as_double() }
fn is_signed_integer(&self) -> bool { self.as_ref().is_signed_integer() }
fn as_signed_integer(&self) -> Option<SignedInteger> { self.as_ref().as_signed_integer() }
fn as_string(&self) -> Option<Cow<'_, str>> { self.as_ref().as_string() }
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> { self.as_ref().as_bytestring() }
fn as_symbol(&self) -> Option<Cow<'_, str>> { self.as_ref().as_symbol() }
fn is_record(&self) -> bool { self.as_ref().is_record() }
fn label(&self) -> &dyn Value<D> { self.as_ref().label() }
fn is_sequence(&self) -> bool { self.as_ref().is_sequence() }
fn len(&self) -> usize { self.as_ref().len() }
fn index(&self, i: usize) -> &dyn Value<D> { self.as_ref().index(i) }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> { self.as_ref().iter() }
fn is_set(&self) -> bool { self.as_ref().is_set() }
fn has(&self, v: &dyn Value<D>) -> bool { self.as_ref().has(v) }
fn is_dictionary(&self) -> bool { self.as_ref().is_dictionary() }
fn get<'value>(&'value self, k: &dyn Value<D>) -> Option<&'value dyn Value<D>> { self.as_ref().get(k) }
fn entries(&self) -> Box<dyn Iterator<Item = (&dyn Value<D>, &dyn Value<D>)> + '_> { self.as_ref().entries() }
fn is_embedded(&self) -> bool { self.as_ref().is_embedded() }
fn embedded(&self) -> Cow<'_, D> { self.as_ref().embedded() }
fn annotations(&self) -> Option<&[IOValue]> { self.as_ref().annotations() }
}
impl<'a, D: Domain> Hash for dyn Value<D> + 'a {
fn hash<H: Hasher>(&self, state: &mut H) {
match self.value_class() {
ValueClass::Atomic(a) => match a {
AtomClass::Boolean => self.as_boolean().unwrap().hash(state),
AtomClass::Float => self.as_float().unwrap().to_bits().hash(state),
AtomClass::Double => self.as_double().unwrap().to_bits().hash(state),
AtomClass::SignedInteger => self.as_signed_integer().unwrap().hash(state),
AtomClass::String => self.as_string().unwrap().hash(state),
AtomClass::ByteString => self.as_bytestring().unwrap().hash(state),
AtomClass::Symbol => self.as_symbol().unwrap().hash(state),
}
ValueClass::Compound(c) => match c {
CompoundClass::Sequence |
CompoundClass::Set => {
state.write_usize(self.len());
for v in self.iter() { v.hash(state) }
}
CompoundClass::Record => {
self.label().hash(state);
state.write_usize(self.len());
for v in self.iter() { v.hash(state) }
}
CompoundClass::Dictionary => {
state.write_usize(self.len());
for (k, v) in self.entries() {
k.hash(state);
v.hash(state);
}
}
}
ValueClass::Embedded => self.embedded().hash(state),
}
}
}
fn iters_eq<'a, D: Domain>(
mut i1: Box<dyn Iterator<Item = &dyn Value<D>> + 'a>,
mut i2: Box<dyn Iterator<Item = &dyn Value<D>> + 'a>,
) -> bool {
loop {
match i1.next() {
None => return i2.next().is_none(),
Some(v1) => match i2.next() {
None => return false,
Some(v2) => if v1 != v2 { return false; },
}
}
}
}
impl<'a, D: Domain> PartialEq for dyn Value<D> + 'a {
fn eq(&self, other: &Self) -> bool {
let cls = self.value_class();
if cls != other.value_class() { return false; }
match cls {
ValueClass::Atomic(a) => match a {
AtomClass::Boolean =>
self.as_boolean().unwrap() == other.as_boolean().unwrap(),
AtomClass::Float =>
eq_f32(self.as_float().unwrap(), other.as_float().unwrap()),
AtomClass::Double =>
eq_f64(self.as_double().unwrap(), other.as_double().unwrap()),
AtomClass::SignedInteger =>
self.as_signed_integer().unwrap() == other.as_signed_integer().unwrap(),
AtomClass::String =>
self.as_string().unwrap() == other.as_string().unwrap(),
AtomClass::ByteString =>
self.as_bytestring().unwrap() == other.as_bytestring().unwrap(),
AtomClass::Symbol =>
self.as_symbol().unwrap() == other.as_symbol().unwrap(),
}
ValueClass::Compound(c) => match c {
CompoundClass::Record => {
if self.label() != other.label() { return false; }
iters_eq(self.iter(), other.iter())
}
CompoundClass::Sequence => {
iters_eq(self.iter(), other.iter())
}
CompoundClass::Set => {
let s1 = self.iter().collect::<Set<_>>();
let s2 = other.iter().collect::<Set<_>>();
s1 == s2
}
CompoundClass::Dictionary => {
let d1 = self.entries().collect::<Map<_, _>>();
let d2 = other.entries().collect::<Map<_, _>>();
d1 == d2
}
}
ValueClass::Embedded => self.embedded() == other.embedded(),
}
}
}
fn iters_cmp<'a, D: Domain>(
mut i1: Box<dyn Iterator<Item = &dyn Value<D>> + 'a>,
mut i2: Box<dyn Iterator<Item = &dyn Value<D>> + 'a>,
) -> Ordering {
loop {
match i1.next() {
None => match i2.next() {
None => return Ordering::Equal,
Some(_) => return Ordering::Less,
}
Some(v1) => match i2.next() {
None => return Ordering::Greater,
Some(v2) => match v1.cmp(v2) {
Ordering::Equal => (),
other => return other,
}
}
}
}
}
impl<'a, D: Domain> Ord for dyn Value<D> + 'a {
fn cmp(&self, other: &Self) -> Ordering {
let cls = self.value_class();
cls.cmp(&other.value_class()).then_with(|| match cls {
ValueClass::Atomic(a) => match a {
AtomClass::Boolean =>
self.as_boolean().cmp(&other.as_boolean()),
AtomClass::Float =>
cmp_f32(self.as_float().unwrap(), other.as_float().unwrap()),
AtomClass::Double =>
cmp_f64(self.as_double().unwrap(), other.as_double().unwrap()),
AtomClass::SignedInteger =>
self.as_signed_integer().cmp(&other.as_signed_integer()),
AtomClass::String =>
self.as_string().cmp(&other.as_string()),
AtomClass::ByteString =>
self.as_bytestring().cmp(&other.as_bytestring()),
AtomClass::Symbol =>
self.as_symbol().cmp(&other.as_symbol()),
},
ValueClass::Compound(c) => match c {
CompoundClass::Record =>
self.label().cmp(other.label()).then_with(
|| iters_cmp(self.iter(), other.iter())),
CompoundClass::Sequence => iters_cmp(self.iter(), other.iter()),
CompoundClass::Set => {
let s1 = self.iter().collect::<Set<_>>();
let s2 = other.iter().collect::<Set<_>>();
s1.cmp(&s2)
}
CompoundClass::Dictionary => {
let d1 = self.entries().collect::<Map<_, _>>();
let d2 = other.entries().collect::<Map<_, _>>();
d1.cmp(&d2)
}
},
ValueClass::Embedded => self.embedded().cmp(&other.embedded()),
})
}
}
impl<'a, D: Domain> Eq for dyn Value<D> + 'a {}
impl<'a, D: Domain> PartialOrd for dyn Value<D> + 'a {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone)]
pub enum Atom<'a> {
Boolean(bool),
Float(f32),
Double(f64),
SignedInteger(SignedInteger),
String(Cow<'a, str>),
ByteString(Cow<'a, [u8]>),
Symbol(Cow<'a, str>),
}
impl<'a> Atom<'a> {
pub fn into_value<D: Domain>(self) -> Box<dyn Value<D>> {
match self {
Atom::Boolean(b) => Box::new(b),
Atom::Float(f) => Box::new(f),
Atom::Double(d) => Box::new(d),
Atom::SignedInteger(i) => Box::new(i),
Atom::String(s) => Box::new(s.into_owned()),
Atom::ByteString(bs) => Box::new(Bytes(bs.into_owned())),
Atom::Symbol(s) => Box::new(Symbol(s.into_owned())),
}
}
}
impl<'a, D: Domain> Value<D> for Atom<'a> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
match self {
Atom::Boolean(b) => w.write_bool(*b),
Atom::Float(f) => w.write_f32(*f),
Atom::Double(d) => w.write_f64(*d),
Atom::SignedInteger(i) => w.write_signed_integer(i),
Atom::String(s) => w.write_string(s),
Atom::ByteString(bs) => w.write_bytes(bs),
Atom::Symbol(s) => w.write_symbol(s),
}
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
self.clone().into_value()
}
fn value_class(&self) -> ValueClass {
ValueClass::Atomic(match self {
Atom::Boolean(_) => AtomClass::Boolean,
Atom::Float(_) => AtomClass::Float,
Atom::Double(_) => AtomClass::Double,
Atom::SignedInteger(_) => AtomClass::SignedInteger,
Atom::String(_) => AtomClass::String,
Atom::ByteString(_) => AtomClass::ByteString,
Atom::Symbol(_) => AtomClass::Symbol,
})
}
fn as_boolean(&self) -> Option<bool> {
if let Atom::Boolean(b) = self { Some(*b) } else { None }
}
fn as_float(&self) -> Option<f32> {
if let Atom::Float(f) = self { Some(*f) } else { None }
}
fn as_double(&self) -> Option<f64> {
if let Atom::Double(d) = self { Some(*d) } else { None }
}
fn is_signed_integer(&self) -> bool { matches!(self, Atom::SignedInteger(_)) }
fn as_signed_integer(&self) -> Option<SignedInteger> {
if let Atom::SignedInteger(i) = self { Some(i.clone()) } else { None }
}
fn as_string(&self) -> Option<Cow<'_, str>> {
if let Atom::String(s) = self { Some(Cow::Borrowed(s)) } else { None }
}
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> {
if let Atom::ByteString(s) = self { Some(Cow::Borrowed(s)) } else { None }
}
fn as_symbol(&self) -> Option<Cow<'_, str>> {
if let Atom::Symbol(s) = self { Some(Cow::Borrowed(s)) } else { None }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum NoValue {}
impl Domain for NoValue {
type Decode = NoEmbeddedDomainCodec;
type Encode = NoEmbeddedDomainCodec;
}
impl<D: Domain> Value<D> for NoValue {
fn write(&self, _w: &mut dyn Writer, _enc: &mut dyn DomainEncode<D>) -> io::Result<()> { unreachable!() }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { unreachable!() }
fn value_class(&self) -> ValueClass { unreachable!() }
}
impl<D: Domain> Value<D> for bool {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_bool(*self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(*self) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::Boolean) }
fn as_boolean(&self) -> Option<bool> { Some(*self) }
}
impl<D: Domain> Value<D> for u64 {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_u64(*self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(*self) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::SignedInteger) }
fn as_signed_integer(&self) -> Option<SignedInteger> {
Some((*self).into())
}
}
impl<D: Domain> Value<D> for SignedInteger {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_signed_integer(self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(self.clone()) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::SignedInteger) }
fn as_signed_integer(&self) -> Option<SignedInteger> {
Some(self.clone())
}
}
impl<D: Domain> Value<D> for f32 {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_f32(*self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(*self) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::Float) }
fn as_float(&self) -> Option<f32> { Some(*self) }
fn as_double(&self) -> Option<f64> { Some(*self as f64) }
}
impl<D: Domain> Value<D> for f64 {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_f64(*self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(*self) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::Float) }
fn as_float(&self) -> Option<f32> { Some(*self as f32) }
fn as_double(&self) -> Option<f64> { Some(*self) }
}
impl<D: Domain> Value<D> for str {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_string(self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(self.to_owned()) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::String) }
fn as_string(&self) -> Option<Cow<'_, str>> { Some(Cow::Borrowed(self)) }
}
impl<D: Domain> Value<D> for String {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_string(self) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(self.clone()) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::String) }
fn as_string(&self) -> Option<Cow<'_, str>> { Some(Cow::Borrowed(self)) }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Bytes<T: AsRef<[u8]>>(T);
impl<T: AsRef<[u8]> + Debug, D: Domain> Value<D> for Bytes<T> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_bytes(self.0.as_ref()) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(Bytes(self.0.as_ref().to_owned())) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::ByteString) }
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> { Some(Cow::Borrowed(self.0.as_ref())) }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Symbol<T: AsRef<str> + Debug>(T);
impl<T: AsRef<str> + Debug> Symbol<T> {
pub fn new(t: T) -> Self {
Symbol(t)
}
}
impl<T: AsRef<str> + Debug, D: Domain> Value<D> for Symbol<T> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> { w.write_symbol(self.0.as_ref()) }
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(Symbol(self.0.as_ref().to_owned())) }
fn value_class(&self) -> ValueClass { ValueClass::Atomic(AtomClass::Symbol) }
fn as_symbol(&self) -> Option<Cow<'_, str>> { Some(Cow::Borrowed(self.0.as_ref())) }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Record<V>(Vec<V> /* at least one element, for the label */);
impl<V> Record<V> {
pub fn new(label: V, mut fields: Vec<V>) -> Self {
fields.insert(0, label);
Record(fields)
}
pub fn _from_vec(v: Vec<V>) -> Self {
if v.is_empty() { panic!("Internal error: empty vec supplied to Record::_from_vec") }
Record(v)
}
}
impl<D: Domain, V: Value<D>> Value<D> for Record<V> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
w.start_record()?;
let mut b = B::start(B::Item::RecordLabel);
w.boundary(&b)?;
self.0[0].write(w, enc)?;
for e in &self.0[1..] {
b.shift(Some(B::Item::RecordField));
w.boundary(&b)?;
e.write(w, enc)?;
}
b.shift(None);
w.boundary(&b)?;
w.end_record()
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
Box::new(Record(self.0.iter().map(|v| v.value_clone()).collect()))
}
fn value_class(&self) -> ValueClass { ValueClass::Compound(CompoundClass::Record) }
fn is_record(&self) -> bool { true }
fn label(&self) -> &dyn Value<D> { &self.0[0] }
fn len(&self) -> usize { self.0.len() - 1 }
fn index(&self, i: usize) -> &dyn Value<D> { &self.0[i + 1] }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> {
Box::new(self.0[1..].iter().map(value))
}
}
impl<D: Domain, V: Value<D>> Value<D> for Vec<V> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
(&self[..]).write(w, enc)
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
(&self[..]).value_clone()
}
fn value_class(&self) -> ValueClass { ValueClass::Compound(CompoundClass::Sequence) }
fn is_sequence(&self) -> bool { true }
fn len(&self) -> usize { self.len() }
fn index(&self, i: usize) -> &dyn Value<D> { &self[i] }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> {
Box::new(self[..].iter().map(value))
}
}
impl<D: Domain, V: Value<D>> Value<D> for [V] {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
w.start_sequence()?;
let mut b = B::Type::default();
for e in self {
b.shift(Some(B::Item::SequenceValue));
w.boundary(&b)?;
e.write(w, enc)?;
}
b.shift(None);
w.boundary(&b)?;
w.end_sequence()
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
Box::new(self.iter().map(|v| v.value_clone()).collect::<Vec<_>>())
}
fn value_class(&self) -> ValueClass { ValueClass::Compound(CompoundClass::Sequence) }
fn is_sequence(&self) -> bool { true }
fn len(&self) -> usize { self.len() }
fn index(&self, i: usize) -> &dyn Value<D> { &self[i] }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> {
Box::new(self[..].iter().map(value))
}
}
impl<'e, D: Domain, E: for<'a> Borrow<Key<'a, D>> + Debug + Ord + 'e> Value<D> for Set<E> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
w.start_set()?;
let mut b = B::Type::default();
for e in self {
b.shift(Some(B::Item::SetValue));
w.boundary(&b)?;
Key::peel_ref(e.borrow()).write(w, enc)?;
}
b.shift(None);
w.boundary(&b)?;
w.end_set()
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
Box::new(self.iter().map(|v| Key::peel_ref(&v.borrow()).value_clone()).collect::<Set<_>>())
}
fn value_class(&self) -> ValueClass { ValueClass::Compound(CompoundClass::Set) }
fn is_set(&self) -> bool { true }
fn len(&self) -> usize { self.len() }
fn has(&self, v: &dyn Value<D>) -> bool { self.contains(&Key::wrap_ref(v)) }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> {
Box::new(self.iter().map(|e| Key::peel_ref(&e.borrow())))
}
}
// Many thanks to SkiFire13 and the other participants in
// https://users.rust-lang.org/t/is-the-lifetime-of-a-btreemap-get-result-attached-to-the-key-as-well-as-the-map/83568/7
// for the idea of using TransparentWrapper here.
//
#[derive(PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Key<'a, D: Domain>(pub dyn Value<D> + 'a);
unsafe impl<'a, D: Domain> TransparentWrapper<dyn Value<D> + 'a> for Key<'a, D> {}
impl<'a, 'b: 'a, D: Domain> Borrow<Key<'a, D>> for Box<dyn Value<D> + 'b> {
fn borrow(&self) -> &Key<'a, D> {
Key::wrap_ref(&**self)
}
}
impl<'a, 'b: 'a, D: Domain> Borrow<Key<'a, D>> for &'b (dyn Value<D> + 'b) {
fn borrow(&self) -> &Key<'a, D> {
Key::wrap_ref(self)
}
}
impl<'k, D: Domain, V: Value<D>, K: for<'a> Borrow<Key<'a, D>> + Debug + Ord + 'k> Value<D>
for Map<K, V>
{
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
w.start_dictionary()?;
let mut b = B::Type::default();
for (k, v) in self {
b.shift(Some(B::Item::DictionaryKey));
w.boundary(&b)?;
Key::peel_ref(k.borrow()).write(w, enc)?;
b.shift(Some(B::Item::DictionaryValue));
w.boundary(&b)?;
v.write(w, enc)?;
}
b.shift(None);
w.boundary(&b)?;
w.end_dictionary()
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
Box::new(Value::entries(self).map(|(k, v)| (k.value_clone(), v.value_clone())).collect::<Map<_, _>>())
}
fn value_class(&self) -> ValueClass { ValueClass::Compound(CompoundClass::Dictionary) }
fn is_dictionary(&self) -> bool { true }
fn len(&self) -> usize { self.len() }
fn has(&self, v: &dyn Value<D>) -> bool { self.contains_key(&Key::wrap_ref(v)) }
fn get(&self, k: &dyn Value<D>) -> Option<&dyn Value<D>> {
match Map::get(self, &Key::wrap_ref(k)) {
Some(v) => Some(v),
None => None,
}
}
fn entries(&self) -> Box<dyn Iterator<Item = (&dyn Value<D>, &dyn Value<D>)> + '_> {
Box::new(self.iter().map(|(k,v)| (Key::peel_ref(&k.borrow()), value(v))))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Embedded<D: Domain>(D);
impl<D: Domain> Embedded<D> {
pub fn new(d: D) -> Self {
Embedded(d)
}
pub fn embedded_value(&self) -> &D {
&self.0
}
pub fn into_embedded_value(self) -> D {
self.0
}
}
impl<D: Domain> Value<D> for Embedded<D> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
w.start_embedded()?;
enc.encode_embedded(w, &self.0)?;
w.end_embedded()
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static { Box::new(self.clone()) }
fn value_class(&self) -> ValueClass { ValueClass::Embedded }
fn is_embedded(&self) -> bool { true }
fn embedded(&self) -> Cow<'_, D> { Cow::Borrowed(&self.0) }
}
#[derive(Debug)]
pub struct Annotations<D: Domain, V: Value<D>>(V, Vec<IOValue>, PhantomData<D>);
impl<D: Domain, V: Value<D>> Annotations<D, V> {
pub fn new(value: V, anns: Vec<IOValue>) -> Self {
Annotations(value, anns, PhantomData)
}
pub fn value(&self) -> &dyn Value<D> {
&self.0
}
}
impl<D: Domain, V: Value<D>> Value<D> for Annotations<D, V> {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<D>) -> io::Result<()> {
if !self.1.is_empty() {
w.start_annotations()?;
let mut b = B::Type::default();
for ann in &self.1 {
b.shift(Some(B::Item::Annotation));
w.boundary(&b)?;
ann.write(w, &mut IOValueDomainCodec)?;
}
b.shift(Some(B::Item::AnnotatedValue));
w.boundary(&b)?;
self.0.write(w, enc)?;
b.shift(None);
w.boundary(&b)?;
w.end_annotations()
} else {
self.0.write(w, enc)
}
}
fn value_clone(&self) -> Box<dyn Value<D>> where D: 'static {
Box::new(Annotations(self.0.value_clone(),
self.1.iter().map(|v| v.value_clone().into()).collect(),
PhantomData))
}
fn value_class(&self) -> ValueClass { self.value().value_class() }
fn as_boolean(&self) -> Option<bool> { self.value().as_boolean() }
fn as_float(&self) -> Option<f32> { self.value().as_float() }
fn as_double(&self) -> Option<f64> { self.value().as_double() }
fn is_signed_integer(&self) -> bool { self.value().is_signed_integer() }
fn as_signed_integer(&self) -> Option<SignedInteger> { self.value().as_signed_integer() }
fn as_string(&self) -> Option<Cow<'_, str>> { self.value().as_string() }
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> { self.value().as_bytestring() }
fn as_symbol(&self) -> Option<Cow<'_, str>> { self.value().as_symbol() }
fn is_record(&self) -> bool { self.value().is_record() }
fn label(&self) -> &dyn Value<D> { self.value().label() }
fn is_sequence(&self) -> bool { self.value().is_sequence() }
fn len(&self) -> usize { self.value().len() }
fn index(&self, i: usize) -> &dyn Value<D> { self.value().index(i) }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<D>> + '_> { self.value().iter() }
fn is_set(&self) -> bool { self.value().is_set() }
fn has(&self, v: &dyn Value<D>) -> bool { self.value().has(v) }
fn is_dictionary(&self) -> bool { self.value().is_dictionary() }
fn get(&self, k: &dyn Value<D>) -> Option<&dyn Value<D>> { self.value().get(k) }
fn entries(&self) -> Box<dyn Iterator<Item = (&dyn Value<D>, &dyn Value<D>)> + '_> { self.value().entries() }
fn is_embedded(&self) -> bool { self.value().is_embedded() }
fn embedded(&self) -> Cow<'_, D> { self.value().embedded() }
fn annotations(&self) -> Option<&[IOValue]> { Some(&self.1) }
}
impl<D: Domain, V: Value<D>> PartialEq for Annotations<D, V> {
fn eq(&self, other: &Self) -> bool {
self.value().eq(&other.value())
}
}
impl<D: Domain, V: Value<D>> Eq for Annotations<D, V> {}
impl<D: Domain, V: Value<D>> Hash for Annotations<D, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value().hash(state);
}
}
impl<D: Domain, V: Value<D>> PartialOrd for Annotations<D, V> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<D: Domain, V: Value<D>> Ord for Annotations<D, V> {
fn cmp(&self, other: &Self) -> Ordering {
self.value().cmp(&other.value())
}
}
#[derive(Debug, Clone, Eq, Hash, PartialOrd, Ord)]
pub struct IOValue(Arc<dyn Value<IOValue>>);
impl PartialEq for IOValue {
fn eq(&self, other: &Self) -> bool {
&self.0 == &other.0
}
}
impl From<Box<dyn Value<IOValue>>> for IOValue {
fn from(b: Box<dyn Value<IOValue>>) -> Self {
IOValue(Arc::from(b))
}
}
impl<'a> Borrow<Key<'a, IOValue>> for IOValue {
fn borrow(&self) -> &Key<'a, IOValue> {
Key::wrap_ref(&*self.0)
}
}
impl Value<IOValue> for IOValue {
fn write(&self, w: &mut dyn Writer, enc: &mut dyn DomainEncode<IOValue>) -> io::Result<()> { self.0.write(w, enc) }
fn value_clone(&self) -> Box<dyn Value<IOValue>> { Box::new(self.clone()) }
fn value_class(&self) -> ValueClass { self.0.value_class() }
fn as_boolean(&self) -> Option<bool> { self.0.as_boolean() }
fn as_float(&self) -> Option<f32> { self.0.as_float() }
fn as_double(&self) -> Option<f64> { self.0.as_double() }
fn is_signed_integer(&self) -> bool { self.0.is_signed_integer() }
fn as_signed_integer(&self) -> Option<SignedInteger> { self.0.as_signed_integer() }
fn as_string(&self) -> Option<Cow<'_, str>> { self.0.as_string() }
fn as_bytestring(&self) -> Option<Cow<'_, [u8]>> { self.0.as_bytestring() }
fn as_symbol(&self) -> Option<Cow<'_, str>> { self.0.as_symbol() }
fn is_record(&self) -> bool { self.0.is_record() }
fn label(&self) -> &dyn Value<IOValue> { self.0.label() }
fn is_sequence(&self) -> bool { self.0.is_sequence() }
fn len(&self) -> usize { self.0.len() }
fn index(&self, i: usize) -> &dyn Value<IOValue> { self.0.index(i) }
fn iter(&self) -> Box<dyn Iterator<Item = &dyn Value<IOValue>> + '_> { self.0.iter() }
fn is_set(&self) -> bool { self.0.is_set() }
fn has(&self, v: &dyn Value<IOValue>) -> bool { self.0.has(v) }
fn is_dictionary(&self) -> bool { self.0.is_dictionary() }
fn get<'value>(&'value self, k: &dyn Value<IOValue>) -> Option<&'value dyn Value<IOValue>> { self.0.get(k) }
fn entries(&self) -> Box<dyn Iterator<Item = (&dyn Value<IOValue>, &dyn Value<IOValue>)> + '_> { self.0.entries() }
fn is_embedded(&self) -> bool { self.0.is_embedded() }
fn embedded(&self) -> Cow<'_, IOValue> { self.0.embedded() }
fn annotations(&self) -> Option<&[IOValue]> { self.0.annotations() }
}