use crate::buffer::{ByteReader, ByteWriter, COUNT_BOUNDARY};
use crate::element::{DataElement, DynElement};
use crate::error::{DecoderError, EncoderError};
use crate::extendable;
fn mismatch(context: &'static str) -> EncoderError {
EncoderError::TypeMismatch { context }
}
fn out_of_range(index: usize, size: usize) -> EncoderError {
EncoderError::IndexOutOfRange { index, size }
}
macro_rules! element_equality {
($($name:ident),+) => {$(
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
let (left, right): (&DynElement, &DynElement) = (self, other);
left == right
}
}
)+};
}
element_equality!(
HLAfixedRecord,
HLAfixedArray,
HLAvariableArray,
HLAvariantRecord,
HLAextendableVariantRecord
);
#[derive(Debug, Clone, Default)]
pub struct HLAfixedRecord {
fields: Vec<Box<DynElement>>,
}
impl HLAfixedRecord {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, element: impl DataElement) -> Self {
self.fields.push(Box::new(element));
self
}
pub fn push(&mut self, element: impl DataElement) -> &mut Self {
self.fields.push(Box::new(element));
self
}
pub fn push_boxed(&mut self, element: Box<DynElement>) -> &mut Self {
self.fields.push(element);
self
}
pub fn len(&self) -> usize {
self.fields.len()
}
pub fn is_empty(&self) -> bool {
self.fields.is_empty()
}
pub fn get(&self, index: usize) -> Option<&DynElement> {
self.fields.get(index).map(|field| &**field)
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
self.fields.get_mut(index).map(|field| &mut **field)
}
pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
self.get(index)?.downcast_ref::<T>()
}
pub fn set(&mut self, index: usize, element: impl DataElement) -> Result<(), EncoderError> {
let size = self.fields.len();
let field = self.fields.get_mut(index).ok_or_else(|| out_of_range(index, size))?;
if !field.is_same_type_as(&element) {
return Err(mismatch("element does not have the datatype of the field it replaces"));
}
*field = Box::new(element);
Ok(())
}
pub fn iter(&self) -> impl Iterator<Item = &DynElement> {
self.fields.iter().map(|field| &**field)
}
}
impl DataElement for HLAfixedRecord {
fn octet_boundary(&self) -> usize {
self.fields.iter().map(|field| field.octet_boundary()).max().unwrap_or(1)
}
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
writer.align(self.octet_boundary());
for field in &self.fields {
field.encode_into(writer)?;
}
writer.status()
}
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
reader.align(self.octet_boundary())?;
for field in &mut self.fields {
field.decode_from(reader)?;
}
Ok(())
}
fn clone_element(&self) -> Box<DynElement> {
Box::new(self.clone())
}
fn is_same_type_as(&self, other: &DynElement) -> bool {
other.downcast_ref::<Self>().is_some_and(|other| {
self.fields.len() == other.fields.len()
&& self.fields.iter().zip(&other.fields).all(|(left, right)| left.is_same_type_as(&**right))
})
}
}
macro_rules! array_accessors {
($name:ident) => {
impl $name {
pub fn prototype(&self) -> &DynElement {
&*self.prototype
}
pub fn len(&self) -> usize {
self.elements.len()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn get(&self, index: usize) -> Option<&DynElement> {
self.elements.get(index).map(|element| &**element)
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
self.elements.get_mut(index).map(|element| &mut **element)
}
pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
self.get(index)?.downcast_ref::<T>()
}
pub fn set(&mut self, index: usize, element: impl DataElement) -> Result<(), EncoderError> {
let size = self.elements.len();
if !self.prototype.is_same_type_as(&element) {
return Err(mismatch("element does not match the prototype of the array"));
}
let slot = self.elements.get_mut(index).ok_or_else(|| out_of_range(index, size))?;
*slot = Box::new(element);
Ok(())
}
pub fn iter(&self) -> impl Iterator<Item = &DynElement> {
self.elements.iter().map(|element| &**element)
}
fn checked<E: DataElement>(
prototype: Box<DynElement>,
elements: impl IntoIterator<Item = E>,
) -> Result<Self, EncoderError> {
let mut array = Self { prototype, elements: Vec::new() };
for element in elements {
if !array.prototype.is_same_type_as(&element) {
return Err(mismatch("element does not match the prototype of the array"));
}
array.elements.push(Box::new(element));
}
Ok(array)
}
}
};
}
#[derive(Debug, Clone)]
pub struct HLAfixedArray {
prototype: Box<DynElement>,
elements: Vec<Box<DynElement>>,
}
array_accessors!(HLAfixedArray);
impl HLAfixedArray {
pub fn new(prototype: impl DataElement, size: usize) -> Self {
let prototype: Box<DynElement> = Box::new(prototype);
let elements = (0..size).map(|_| prototype.clone()).collect();
Self { prototype, elements }
}
pub fn from_elements<E: DataElement>(
prototype: impl DataElement,
elements: impl IntoIterator<Item = E>,
) -> Result<Self, EncoderError> {
Self::checked(Box::new(prototype), elements)
}
}
impl DataElement for HLAfixedArray {
fn octet_boundary(&self) -> usize {
self.prototype.octet_boundary()
}
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
writer.align(self.octet_boundary());
for element in &self.elements {
element.encode_into(writer)?;
}
writer.status()
}
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
reader.align(self.octet_boundary())?;
for element in &mut self.elements {
element.decode_from(reader)?;
}
Ok(())
}
fn clone_element(&self) -> Box<DynElement> {
Box::new(self.clone())
}
fn is_same_type_as(&self, other: &DynElement) -> bool {
other.downcast_ref::<Self>().is_some_and(|other| {
self.elements.len() == other.elements.len() && self.prototype.is_same_type_as(&*other.prototype)
})
}
}
#[derive(Debug, Clone)]
pub struct HLAvariableArray {
prototype: Box<DynElement>,
elements: Vec<Box<DynElement>>,
}
array_accessors!(HLAvariableArray);
impl HLAvariableArray {
pub fn new(prototype: impl DataElement) -> Self {
Self { prototype: Box::new(prototype), elements: Vec::new() }
}
pub fn from_elements<E: DataElement>(
prototype: impl DataElement,
elements: impl IntoIterator<Item = E>,
) -> Result<Self, EncoderError> {
Self::checked(Box::new(prototype), elements)
}
pub fn of<T: DataElement + Default>(elements: impl IntoIterator<Item = T>) -> Self {
let elements = elements.into_iter().map(|element| Box::new(element) as Box<DynElement>).collect();
Self { prototype: Box::new(T::default()), elements }
}
pub fn push(&mut self, element: impl DataElement) -> Result<&mut Self, EncoderError> {
if !self.prototype.is_same_type_as(&element) {
return Err(mismatch("element does not match the prototype of the array"));
}
self.elements.push(Box::new(element));
Ok(self)
}
pub fn resize(&mut self, size: usize) {
let prototype = &self.prototype;
self.elements.resize_with(size, || prototype.clone());
}
pub fn clear(&mut self) {
self.elements.clear();
}
}
impl DataElement for HLAvariableArray {
fn octet_boundary(&self) -> usize {
self.prototype.octet_boundary().max(COUNT_BOUNDARY)
}
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
writer.align(self.octet_boundary());
writer.put_count(self.elements.len());
for element in &self.elements {
element.encode_into(writer)?;
}
writer.status()
}
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
reader.align(self.octet_boundary())?;
let count = reader.read_count()?;
self.elements.clear();
for _ in 0..count {
let mut element = self.prototype.clone();
element.decode_from(reader)?;
self.elements.push(element);
}
Ok(())
}
fn clone_element(&self) -> Box<DynElement> {
Box::new(self.clone())
}
fn is_same_type_as(&self, other: &DynElement) -> bool {
other.downcast_ref::<Self>().is_some_and(|other| self.prototype.is_same_type_as(&*other.prototype))
}
}
#[derive(Debug, Clone)]
struct Variant {
key: Vec<u8>,
value: Option<Box<DynElement>>,
}
#[derive(Debug, Clone)]
struct VariantTable {
prototype: Box<DynElement>,
discriminant: Box<DynElement>,
variants: Vec<Variant>,
}
impl VariantTable {
fn new(prototype: Box<DynElement>) -> Self {
Self { discriminant: prototype.clone(), prototype, variants: Vec::new() }
}
fn key_of(&self, discriminant: &DynElement) -> Result<Vec<u8>, EncoderError> {
if !self.prototype.is_same_type_as(discriminant) {
return Err(mismatch("discriminant does not match the discriminant prototype"));
}
discriminant.to_bytes()
}
fn set(
&mut self,
discriminant: Box<DynElement>,
value: Option<Box<DynElement>>,
) -> Result<(), EncoderError> {
let key = self.key_of(&*discriminant)?;
match self.variants.iter().position(|variant| variant.key == key) {
Some(index) => self.variants[index].value = value,
None => self.variants.push(Variant { key, value }),
}
self.discriminant = discriminant;
Ok(())
}
fn select(&mut self, discriminant: Box<DynElement>) -> Result<(), EncoderError> {
self.key_of(&*discriminant)?;
self.discriminant = discriminant;
Ok(())
}
fn index_of(&self, discriminant: &DynElement) -> Option<usize> {
let key = discriminant.to_bytes().ok()?;
self.variants.iter().position(|variant| variant.key == key)
}
fn active_index(&self) -> Option<usize> {
self.index_of(&*self.discriminant)
}
fn alternative_boundary(&self) -> usize {
self.variants
.iter()
.filter_map(|variant| variant.value.as_deref())
.map(|value| value.octet_boundary())
.max()
.unwrap_or(1)
}
fn same_shape(&self, other: &Self) -> bool {
self.prototype.is_same_type_as(&*other.prototype)
&& self.variants.len() == other.variants.len()
&& self.variants.iter().all(|variant| {
other.variants.iter().find(|candidate| candidate.key == variant.key).is_some_and(
|candidate| same_optional_type(variant.value.as_deref(), candidate.value.as_deref()),
)
})
}
}
fn same_optional_type(left: Option<&DynElement>, right: Option<&DynElement>) -> bool {
match (left, right) {
(Some(left), Some(right)) => left.is_same_type_as(right),
(None, None) => true,
_ => false,
}
}
macro_rules! variant_record_api {
($name:ident) => {
impl $name {
pub fn set_variant(
&mut self,
discriminant: impl DataElement,
value: impl DataElement,
) -> Result<&mut Self, EncoderError> {
self.table.set(Box::new(discriminant), Some(Box::new(value)))?;
self.selection_changed();
Ok(self)
}
pub fn set_empty_variant(
&mut self,
discriminant: impl DataElement,
) -> Result<&mut Self, EncoderError> {
self.table.set(Box::new(discriminant), None)?;
self.selection_changed();
Ok(self)
}
pub fn set_discriminant(
&mut self,
discriminant: impl DataElement,
) -> Result<&mut Self, EncoderError> {
self.table.select(Box::new(discriminant))?;
self.selection_changed();
Ok(self)
}
pub fn discriminant(&self) -> &DynElement {
&*self.table.discriminant
}
pub fn discriminant_as<T: DataElement>(&self) -> Option<&T> {
self.discriminant().downcast_ref::<T>()
}
pub fn value_as<T: DataElement>(&self) -> Option<&T> {
self.value().ok()?.downcast_ref::<T>()
}
pub fn has_variant(&self, discriminant: &DynElement) -> bool {
self.table.index_of(discriminant).is_some()
}
pub fn variant_count(&self) -> usize {
self.table.variants.len()
}
}
};
}
#[derive(Debug, Clone)]
pub struct HLAvariantRecord {
table: VariantTable,
other: Option<Box<DynElement>>,
}
variant_record_api!(HLAvariantRecord);
impl HLAvariantRecord {
pub fn new(discriminant_prototype: impl DataElement) -> Self {
Self { table: VariantTable::new(Box::new(discriminant_prototype)), other: None }
}
pub fn set_other_variant(&mut self, value: impl DataElement) -> &mut Self {
self.other = Some(Box::new(value));
self
}
pub fn value(&self) -> Result<&DynElement, EncoderError> {
self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
}
pub fn value_mut(&mut self) -> Result<&mut DynElement, EncoderError> {
let value = match self.table.active_index() {
Some(index) => self.table.variants[index].value.as_deref_mut(),
None => self.other.as_deref_mut(),
};
value.ok_or(EncoderError::NoVariantForDiscriminant)
}
fn active(&self) -> Result<Option<&DynElement>, EncoderError> {
match self.table.active_index() {
Some(index) => Ok(self.table.variants[index].value.as_deref()),
None => self.other.as_deref().map(Some).ok_or(EncoderError::NoVariantForDiscriminant),
}
}
fn alternative_boundary(&self) -> usize {
let other = self.other.as_deref().map_or(1, |value| value.octet_boundary());
self.table.alternative_boundary().max(other)
}
fn selection_changed(&mut self) {}
}
impl DataElement for HLAvariantRecord {
fn octet_boundary(&self) -> usize {
self.table.prototype.octet_boundary().max(self.alternative_boundary())
}
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
let value = self.active()?;
writer.align(self.octet_boundary());
self.table.discriminant.encode_into(writer)?;
if let Some(value) = value {
writer.align(self.alternative_boundary());
value.encode_into(writer)?;
}
writer.status()
}
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
reader.align(self.octet_boundary())?;
let mut discriminant = self.table.prototype.clone();
discriminant.decode_from(reader)?;
let alternative_boundary = self.alternative_boundary();
let value = match self.table.index_of(&*discriminant) {
Some(index) => self.table.variants[index].value.as_deref_mut(),
None => match self.other.as_deref_mut() {
Some(other) => Some(other),
None => {
return Err(DecoderError::UnknownDiscriminant {
type_name: "HLAvariantRecord",
discriminant: format!("{discriminant:?}"),
});
}
},
};
if let Some(value) = value {
reader.align(alternative_boundary)?;
value.decode_from(reader)?;
}
self.table.discriminant = discriminant;
Ok(())
}
fn clone_element(&self) -> Box<DynElement> {
Box::new(self.clone())
}
fn is_same_type_as(&self, other: &DynElement) -> bool {
other.downcast_ref::<Self>().is_some_and(|other| {
self.table.same_shape(&other.table)
&& same_optional_type(self.other.as_deref(), other.other.as_deref())
})
}
}
#[derive(Debug, Clone)]
pub struct HLAextendableVariantRecord {
table: VariantTable,
unknown: Option<Vec<u8>>,
}
variant_record_api!(HLAextendableVariantRecord);
impl HLAextendableVariantRecord {
pub fn new(discriminant_prototype: impl DataElement) -> Self {
Self { table: VariantTable::new(Box::new(discriminant_prototype)), unknown: None }
}
pub fn value(&self) -> Result<&DynElement, EncoderError> {
self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
}
pub fn value_mut(&mut self) -> Result<&mut DynElement, EncoderError> {
let index = self.table.active_index().ok_or(EncoderError::NoVariantForDiscriminant)?;
self.table.variants[index].value.as_deref_mut().ok_or(EncoderError::NoVariantForDiscriminant)
}
pub fn unknown_alternative(&self) -> Option<&[u8]> {
self.unknown.as_deref()
}
fn active(&self) -> Result<Option<&DynElement>, EncoderError> {
let index = self.table.active_index().ok_or(EncoderError::NoVariantForDiscriminant)?;
Ok(self.table.variants[index].value.as_deref())
}
fn selection_changed(&mut self) {
self.unknown = None;
}
}
impl DataElement for HLAextendableVariantRecord {
fn octet_boundary(&self) -> usize {
extendable::OCTET_BOUNDARY
}
fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
let value = self.active()?;
if value.is_some_and(|value| value.octet_boundary() > extendable::ALTERNATIVE_BOUNDARY) {
return Err(mismatch("an HLAextendableVariantRecord alternative has an octet boundary above 8"));
}
let passed_on = self.unknown.as_deref().filter(|_| value.is_none()).unwrap_or_default();
let length = match value {
Some(value) => value.encoded_length()?,
None => passed_on.len(),
};
extendable::begin_encode(writer);
self.table.discriminant.encode_into(writer)?;
extendable::write_length(writer, length);
match value {
Some(value) => value.encode_into(writer)?,
None => writer.put_slice(passed_on),
}
writer.status()
}
fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
extendable::begin_decode(reader)?;
let mut discriminant = self.table.prototype.clone();
discriminant.decode_from(reader)?;
let mut alternative = extendable::read_alternative(reader)?;
self.unknown = None;
match self.table.index_of(&*discriminant).map(|index| self.table.variants[index].value.as_deref_mut())
{
Some(Some(value)) => {
value.decode_from(alternative.reader())?;
alternative.finish()?;
}
Some(None) if alternative.is_empty() => {}
Some(None) | None => self.unknown = Some(alternative.into_bytes()),
}
self.table.discriminant = discriminant;
Ok(())
}
fn clone_element(&self) -> Box<DynElement> {
Box::new(self.clone())
}
fn is_same_type_as(&self, other: &DynElement) -> bool {
other.downcast_ref::<Self>().is_some_and(|other| self.table.same_shape(&other.table))
}
}