use std::any::{Any, TypeId};
use std::fmt;
use crate::buffer::{ByteReader, ByteWriter};
use crate::error::{DecoderError, EncoderError};
use crate::typed::{Decode, Encode};
pub type DynElement = dyn DataElement;
pub trait DataElement: Any + fmt::Debug + Send + Sync {
fn octet_boundary(&self) -> usize;
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError>;
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError>;
fn clone_element(&self) -> Box<DynElement>;
fn encoded_length(&self) -> Result<usize, EncoderError> {
let mut counter = ByteWriter::counter();
self.encode_into(&mut counter)?;
counter.status()?;
Ok(counter.position())
}
fn is_same_type_as(&self, other: &DynElement) -> bool {
self.element_type_id() == other.element_type_id()
}
#[doc(hidden)]
fn element_type_id(&self) -> TypeId {
TypeId::of::<Self>()
}
fn to_bytes(&self) -> Result<Vec<u8>, EncoderError> {
let mut buffer = Vec::new();
self.append_to(&mut buffer)?;
Ok(buffer)
}
fn append_to(&self, buffer: &mut Vec<u8>) -> Result<(), EncoderError> {
let start = buffer.len();
let mut writer = ByteWriter::new(buffer);
let result = self.encode_into(&mut writer).and_then(|()| writer.status());
if result.is_err() {
buffer.truncate(start);
}
result
}
fn decode_slice(&mut self, bytes: &[u8]) -> Result<(), DecoderError> {
self.decode_from(&mut ByteReader::new(bytes))
}
fn decode_slice_strict(&mut self, bytes: &[u8]) -> Result<(), DecoderError> {
let mut reader = ByteReader::new(bytes);
self.decode_from(&mut reader)?;
reader.expect_end()
}
}
impl<T> DataElement for T
where
T: Decode + Clone + fmt::Debug + Send + Sync + 'static,
{
fn octet_boundary(&self) -> usize {
<T as Encode>::OCTET_BOUNDARY
}
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
Encode::encode(self, writer);
writer.status()
}
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
*self = T::decode(reader)?;
Ok(())
}
fn clone_element(&self) -> Box<DynElement> {
Box::new(self.clone())
}
}
impl dyn DataElement {
pub fn is<T: DataElement>(&self) -> bool {
let any: &dyn Any = self;
any.is::<T>()
}
pub fn downcast_ref<T: DataElement>(&self) -> Option<&T> {
let any: &dyn Any = self;
any.downcast_ref::<T>()
}
pub fn downcast_mut<T: DataElement>(&mut self) -> Option<&mut T> {
let any: &mut dyn Any = self;
any.downcast_mut::<T>()
}
}
impl Clone for Box<DynElement> {
fn clone(&self) -> Self {
(**self).clone_element()
}
}
impl PartialEq for dyn DataElement {
fn eq(&self, other: &Self) -> bool {
self.is_same_type_as(other)
&& matches!((self.to_bytes(), other.to_bytes()), (Ok(left), Ok(right)) if left == right)
}
}