use std::io; use super::BinarySource; use super::BytesBinarySource; use super::Embeddable; use super::IOValue; use super::Reader; use super::Writer; use super::packed; pub trait DomainParse { fn parse_embedded( &mut self, v: &IOValue, ) -> io::Result; } pub trait DomainUnparse { fn unparse_embedded( &mut self, d: &D, ) -> io::Result; } pub trait DomainDecode { fn decode_embedded<'de, 'src, S: BinarySource<'de>>( &mut self, src: &'src mut S, read_annotations: bool, ) -> io::Result; } pub trait DomainEncode { fn encode_embedded( &mut self, w: &mut W, d: &D, ) -> io::Result<()>; } impl<'a, D: Embeddable, T: DomainParse> DomainParse for &'a mut T { fn parse_embedded( &mut self, v: &IOValue, ) -> io::Result { (**self).parse_embedded(v) } } impl<'a, D: Embeddable, T: DomainDecode> DomainDecode for &'a mut T { fn decode_embedded<'de, 'src, S: BinarySource<'de>>( &mut self, src: &'src mut S, read_annotations: bool, ) -> io::Result { (**self).decode_embedded(src, read_annotations) } } pub struct IOValueDomainCodec; impl DomainDecode for IOValueDomainCodec { fn decode_embedded<'de, 'src, S: BinarySource<'de>>( &mut self, src: &'src mut S, read_annotations: bool, ) -> io::Result { packed::PackedReader::new(src, IOValueDomainCodec).demand_next(read_annotations) } } impl DomainEncode for IOValueDomainCodec { fn encode_embedded( &mut self, w: &mut W, d: &IOValue, ) -> io::Result<()> { w.write(self, d) } } pub struct NoEmbeddedDomainCodec; impl DomainDecode for NoEmbeddedDomainCodec { fn decode_embedded<'de, 'src, S: BinarySource<'de>>( &mut self, _src: &'src mut S, _read_annotations: bool, ) -> io::Result { Err(io::Error::new(io::ErrorKind::Unsupported, "Embedded values not supported here")) } } impl DomainEncode for NoEmbeddedDomainCodec { fn encode_embedded( &mut self, _w: &mut W, _d: &D, ) -> io::Result<()> { Err(io::Error::new(io::ErrorKind::Unsupported, "Embedded values not supported here")) } } pub struct ViaCodec(C); impl ViaCodec { pub fn new(c: C) -> Self { ViaCodec(c) } } impl> DomainParse for ViaCodec { fn parse_embedded( &mut self, v: &IOValue, ) -> io::Result { let bs = packed::PackedWriter::encode_iovalue(v)?; self.0.decode_embedded(&mut BytesBinarySource::new(&bs), true) } } impl> DomainUnparse for ViaCodec { fn unparse_embedded( &mut self, d: &D, ) -> io::Result { let mut bs = Vec::new(); let w = &mut packed::PackedWriter::new(&mut bs); self.0.encode_embedded(w, d)?; packed::annotated_iovalue_from_bytes(&bs) } } impl> DomainDecode for ViaCodec { fn decode_embedded<'de, 'src, S: BinarySource<'de>>( &mut self, src: &'src mut S, read_annotations: bool, ) -> io::Result { let v = src.packed(IOValueDomainCodec).demand_next(read_annotations)?; self.0.parse_embedded(&v) } } impl> DomainEncode for ViaCodec { fn encode_embedded( &mut self, w: &mut W, d: &D, ) -> io::Result<()> { let v = self.0.unparse_embedded(d)?; w.write(&mut IOValueDomainCodec, &v) } }