1use crate::buffer::{ByteReader, ByteWriter, COUNT_BOUNDARY};
5use crate::element::{DataElement, DynElement};
6use crate::error::{DecoderError, EncoderError};
7use crate::extendable;
8
9fn mismatch(context: &'static str) -> EncoderError {
10 EncoderError::TypeMismatch { context }
11}
12
13fn out_of_range(index: usize, size: usize) -> EncoderError {
14 EncoderError::IndexOutOfRange { index, size }
15}
16
17macro_rules! element_equality {
19 ($($name:ident),+) => {$(
20 impl PartialEq for $name {
21 fn eq(&self, other: &Self) -> bool {
22 let (left, right): (&DynElement, &DynElement) = (self, other);
23 left == right
24 }
25 }
26 )+};
27}
28
29element_equality!(
30 HLAfixedRecord,
31 HLAfixedArray,
32 HLAvariableArray,
33 HLAvariantRecord,
34 HLAextendableVariantRecord
35);
36
37#[derive(Debug, Clone, Default)]
41pub struct HLAfixedRecord {
42 fields: Vec<Box<DynElement>>,
43}
44
45impl HLAfixedRecord {
46 pub fn new() -> Self {
48 Self::default()
49 }
50
51 pub fn with(mut self, element: impl DataElement) -> Self {
53 self.fields.push(Box::new(element));
54 self
55 }
56
57 pub fn push(&mut self, element: impl DataElement) -> &mut Self {
59 self.fields.push(Box::new(element));
60 self
61 }
62
63 pub fn push_boxed(&mut self, element: Box<DynElement>) -> &mut Self {
65 self.fields.push(element);
66 self
67 }
68
69 pub fn len(&self) -> usize {
71 self.fields.len()
72 }
73
74 pub fn is_empty(&self) -> bool {
76 self.fields.is_empty()
77 }
78
79 pub fn get(&self, index: usize) -> Option<&DynElement> {
81 self.fields.get(index).map(|field| &**field)
82 }
83
84 pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
86 self.fields.get_mut(index).map(|field| &mut **field)
87 }
88
89 pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
91 self.get(index)?.downcast_ref::<T>()
92 }
93
94 pub fn set(&mut self, index: usize, element: impl DataElement) -> Result<(), EncoderError> {
96 let size = self.fields.len();
97 let field = self.fields.get_mut(index).ok_or_else(|| out_of_range(index, size))?;
98 if !field.is_same_type_as(&element) {
99 return Err(mismatch("element does not have the datatype of the field it replaces"));
100 }
101 *field = Box::new(element);
102 Ok(())
103 }
104
105 pub fn iter(&self) -> impl Iterator<Item = &DynElement> {
107 self.fields.iter().map(|field| &**field)
108 }
109}
110
111impl DataElement for HLAfixedRecord {
112 fn octet_boundary(&self) -> usize {
113 self.fields.iter().map(|field| field.octet_boundary()).max().unwrap_or(1)
114 }
115
116 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
117 writer.align(self.octet_boundary());
118 for field in &self.fields {
119 field.encode_into(writer)?;
120 }
121 writer.status()
122 }
123
124 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
125 reader.align(self.octet_boundary())?;
126 for field in &mut self.fields {
127 field.decode_from(reader)?;
128 }
129 Ok(())
130 }
131
132 fn clone_element(&self) -> Box<DynElement> {
133 Box::new(self.clone())
134 }
135
136 fn is_same_type_as(&self, other: &DynElement) -> bool {
137 other.downcast_ref::<Self>().is_some_and(|other| {
138 self.fields.len() == other.fields.len()
139 && self.fields.iter().zip(&other.fields).all(|(left, right)| left.is_same_type_as(&**right))
140 })
141 }
142}
143
144macro_rules! array_accessors {
146 ($name:ident) => {
147 impl $name {
148 pub fn prototype(&self) -> &DynElement {
150 &*self.prototype
151 }
152
153 pub fn len(&self) -> usize {
155 self.elements.len()
156 }
157
158 pub fn is_empty(&self) -> bool {
160 self.elements.is_empty()
161 }
162
163 pub fn get(&self, index: usize) -> Option<&DynElement> {
165 self.elements.get(index).map(|element| &**element)
166 }
167
168 pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
170 self.elements.get_mut(index).map(|element| &mut **element)
171 }
172
173 pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
175 self.get(index)?.downcast_ref::<T>()
176 }
177
178 pub fn set(&mut self, index: usize, element: impl DataElement) -> Result<(), EncoderError> {
180 let size = self.elements.len();
181 if !self.prototype.is_same_type_as(&element) {
182 return Err(mismatch("element does not match the prototype of the array"));
183 }
184 let slot = self.elements.get_mut(index).ok_or_else(|| out_of_range(index, size))?;
185 *slot = Box::new(element);
186 Ok(())
187 }
188
189 pub fn iter(&self) -> impl Iterator<Item = &DynElement> {
191 self.elements.iter().map(|element| &**element)
192 }
193
194 fn checked<E: DataElement>(
195 prototype: Box<DynElement>,
196 elements: impl IntoIterator<Item = E>,
197 ) -> Result<Self, EncoderError> {
198 let mut array = Self { prototype, elements: Vec::new() };
199 for element in elements {
200 if !array.prototype.is_same_type_as(&element) {
201 return Err(mismatch("element does not match the prototype of the array"));
202 }
203 array.elements.push(Box::new(element));
204 }
205 Ok(array)
206 }
207 }
208 };
209}
210
211#[derive(Debug, Clone)]
214pub struct HLAfixedArray {
215 prototype: Box<DynElement>,
216 elements: Vec<Box<DynElement>>,
217}
218
219array_accessors!(HLAfixedArray);
220
221impl HLAfixedArray {
222 pub fn new(prototype: impl DataElement, size: usize) -> Self {
224 let prototype: Box<DynElement> = Box::new(prototype);
225 let elements = (0..size).map(|_| prototype.clone()).collect();
226 Self { prototype, elements }
227 }
228
229 pub fn from_elements<E: DataElement>(
231 prototype: impl DataElement,
232 elements: impl IntoIterator<Item = E>,
233 ) -> Result<Self, EncoderError> {
234 Self::checked(Box::new(prototype), elements)
235 }
236}
237
238impl DataElement for HLAfixedArray {
239 fn octet_boundary(&self) -> usize {
240 self.prototype.octet_boundary()
241 }
242
243 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
244 writer.align(self.octet_boundary());
245 for element in &self.elements {
246 element.encode_into(writer)?;
247 }
248 writer.status()
249 }
250
251 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
252 reader.align(self.octet_boundary())?;
253 for element in &mut self.elements {
254 element.decode_from(reader)?;
255 }
256 Ok(())
257 }
258
259 fn clone_element(&self) -> Box<DynElement> {
260 Box::new(self.clone())
261 }
262
263 fn is_same_type_as(&self, other: &DynElement) -> bool {
264 other.downcast_ref::<Self>().is_some_and(|other| {
265 self.elements.len() == other.elements.len() && self.prototype.is_same_type_as(&*other.prototype)
266 })
267 }
268}
269
270#[derive(Debug, Clone)]
274pub struct HLAvariableArray {
275 prototype: Box<DynElement>,
276 elements: Vec<Box<DynElement>>,
277}
278
279array_accessors!(HLAvariableArray);
280
281impl HLAvariableArray {
282 pub fn new(prototype: impl DataElement) -> Self {
284 Self { prototype: Box::new(prototype), elements: Vec::new() }
285 }
286
287 pub fn from_elements<E: DataElement>(
289 prototype: impl DataElement,
290 elements: impl IntoIterator<Item = E>,
291 ) -> Result<Self, EncoderError> {
292 Self::checked(Box::new(prototype), elements)
293 }
294
295 pub fn of<T: DataElement + Default>(elements: impl IntoIterator<Item = T>) -> Self {
297 let elements = elements.into_iter().map(|element| Box::new(element) as Box<DynElement>).collect();
298 Self { prototype: Box::new(T::default()), elements }
299 }
300
301 pub fn push(&mut self, element: impl DataElement) -> Result<&mut Self, EncoderError> {
303 if !self.prototype.is_same_type_as(&element) {
304 return Err(mismatch("element does not match the prototype of the array"));
305 }
306 self.elements.push(Box::new(element));
307 Ok(self)
308 }
309
310 pub fn resize(&mut self, size: usize) {
312 let prototype = &self.prototype;
313 self.elements.resize_with(size, || prototype.clone());
314 }
315
316 pub fn clear(&mut self) {
318 self.elements.clear();
319 }
320}
321
322impl DataElement for HLAvariableArray {
323 fn octet_boundary(&self) -> usize {
324 self.prototype.octet_boundary().max(COUNT_BOUNDARY)
325 }
326
327 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
328 writer.align(self.octet_boundary());
329 writer.put_count(self.elements.len());
330 for element in &self.elements {
331 element.encode_into(writer)?;
332 }
333 writer.status()
334 }
335
336 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
337 reader.align(self.octet_boundary())?;
338 let count = reader.read_count()?;
339 self.elements.clear();
340 for _ in 0..count {
341 let mut element = self.prototype.clone();
342 element.decode_from(reader)?;
343 self.elements.push(element);
344 }
345 Ok(())
346 }
347
348 fn clone_element(&self) -> Box<DynElement> {
349 Box::new(self.clone())
350 }
351
352 fn is_same_type_as(&self, other: &DynElement) -> bool {
353 other.downcast_ref::<Self>().is_some_and(|other| self.prototype.is_same_type_as(&*other.prototype))
354 }
355}
356
357#[derive(Debug, Clone)]
358struct Variant {
359 key: Vec<u8>,
361 value: Option<Box<DynElement>>,
363}
364
365#[derive(Debug, Clone)]
367struct VariantTable {
368 prototype: Box<DynElement>,
369 discriminant: Box<DynElement>,
370 variants: Vec<Variant>,
371}
372
373impl VariantTable {
374 fn new(prototype: Box<DynElement>) -> Self {
375 Self { discriminant: prototype.clone(), prototype, variants: Vec::new() }
376 }
377
378 fn key_of(&self, discriminant: &DynElement) -> Result<Vec<u8>, EncoderError> {
379 if !self.prototype.is_same_type_as(discriminant) {
380 return Err(mismatch("discriminant does not match the discriminant prototype"));
381 }
382 discriminant.to_bytes()
383 }
384
385 fn set(
386 &mut self,
387 discriminant: Box<DynElement>,
388 value: Option<Box<DynElement>>,
389 ) -> Result<(), EncoderError> {
390 let key = self.key_of(&*discriminant)?;
391 match self.variants.iter().position(|variant| variant.key == key) {
392 Some(index) => self.variants[index].value = value,
393 None => self.variants.push(Variant { key, value }),
394 }
395 self.discriminant = discriminant;
396 Ok(())
397 }
398
399 fn select(&mut self, discriminant: Box<DynElement>) -> Result<(), EncoderError> {
400 self.key_of(&*discriminant)?;
401 self.discriminant = discriminant;
402 Ok(())
403 }
404
405 fn index_of(&self, discriminant: &DynElement) -> Option<usize> {
406 let key = discriminant.to_bytes().ok()?;
407 self.variants.iter().position(|variant| variant.key == key)
408 }
409
410 fn active_index(&self) -> Option<usize> {
411 self.index_of(&*self.discriminant)
412 }
413
414 fn alternative_boundary(&self) -> usize {
415 self.variants
416 .iter()
417 .filter_map(|variant| variant.value.as_deref())
418 .map(|value| value.octet_boundary())
419 .max()
420 .unwrap_or(1)
421 }
422
423 fn same_shape(&self, other: &Self) -> bool {
424 self.prototype.is_same_type_as(&*other.prototype)
425 && self.variants.len() == other.variants.len()
426 && self.variants.iter().all(|variant| {
427 other.variants.iter().find(|candidate| candidate.key == variant.key).is_some_and(
428 |candidate| same_optional_type(variant.value.as_deref(), candidate.value.as_deref()),
429 )
430 })
431 }
432}
433
434fn same_optional_type(left: Option<&DynElement>, right: Option<&DynElement>) -> bool {
435 match (left, right) {
436 (Some(left), Some(right)) => left.is_same_type_as(right),
437 (None, None) => true,
438 _ => false,
439 }
440}
441
442macro_rules! variant_record_api {
444 ($name:ident) => {
445 impl $name {
446 pub fn set_variant(
451 &mut self,
452 discriminant: impl DataElement,
453 value: impl DataElement,
454 ) -> Result<&mut Self, EncoderError> {
455 self.table.set(Box::new(discriminant), Some(Box::new(value)))?;
456 self.selection_changed();
457 Ok(self)
458 }
459
460 pub fn set_empty_variant(
463 &mut self,
464 discriminant: impl DataElement,
465 ) -> Result<&mut Self, EncoderError> {
466 self.table.set(Box::new(discriminant), None)?;
467 self.selection_changed();
468 Ok(self)
469 }
470
471 pub fn set_discriminant(
474 &mut self,
475 discriminant: impl DataElement,
476 ) -> Result<&mut Self, EncoderError> {
477 self.table.select(Box::new(discriminant))?;
478 self.selection_changed();
479 Ok(self)
480 }
481
482 pub fn discriminant(&self) -> &DynElement {
484 &*self.table.discriminant
485 }
486
487 pub fn discriminant_as<T: DataElement>(&self) -> Option<&T> {
489 self.discriminant().downcast_ref::<T>()
490 }
491
492 pub fn value_as<T: DataElement>(&self) -> Option<&T> {
494 self.value().ok()?.downcast_ref::<T>()
495 }
496
497 pub fn has_variant(&self, discriminant: &DynElement) -> bool {
500 self.table.index_of(discriminant).is_some()
501 }
502
503 pub fn variant_count(&self) -> usize {
505 self.table.variants.len()
506 }
507 }
508 };
509}
510
511#[derive(Debug, Clone)]
521pub struct HLAvariantRecord {
522 table: VariantTable,
523 other: Option<Box<DynElement>>,
524}
525
526variant_record_api!(HLAvariantRecord);
527
528impl HLAvariantRecord {
529 pub fn new(discriminant_prototype: impl DataElement) -> Self {
532 Self { table: VariantTable::new(Box::new(discriminant_prototype)), other: None }
533 }
534
535 pub fn set_other_variant(&mut self, value: impl DataElement) -> &mut Self {
538 self.other = Some(Box::new(value));
539 self
540 }
541
542 pub fn value(&self) -> Result<&DynElement, EncoderError> {
547 self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
548 }
549
550 pub fn value_mut(&mut self) -> Result<&mut DynElement, EncoderError> {
552 let value = match self.table.active_index() {
553 Some(index) => self.table.variants[index].value.as_deref_mut(),
554 None => self.other.as_deref_mut(),
555 };
556 value.ok_or(EncoderError::NoVariantForDiscriminant)
557 }
558
559 fn active(&self) -> Result<Option<&DynElement>, EncoderError> {
561 match self.table.active_index() {
562 Some(index) => Ok(self.table.variants[index].value.as_deref()),
563 None => self.other.as_deref().map(Some).ok_or(EncoderError::NoVariantForDiscriminant),
564 }
565 }
566
567 fn alternative_boundary(&self) -> usize {
568 let other = self.other.as_deref().map_or(1, |value| value.octet_boundary());
569 self.table.alternative_boundary().max(other)
570 }
571
572 fn selection_changed(&mut self) {}
573}
574
575impl DataElement for HLAvariantRecord {
576 fn octet_boundary(&self) -> usize {
577 self.table.prototype.octet_boundary().max(self.alternative_boundary())
578 }
579
580 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
581 let value = self.active()?;
582 writer.align(self.octet_boundary());
583 self.table.discriminant.encode_into(writer)?;
584 if let Some(value) = value {
585 writer.align(self.alternative_boundary());
586 value.encode_into(writer)?;
587 }
588 writer.status()
589 }
590
591 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
592 reader.align(self.octet_boundary())?;
593 let mut discriminant = self.table.prototype.clone();
594 discriminant.decode_from(reader)?;
595 let alternative_boundary = self.alternative_boundary();
596 let value = match self.table.index_of(&*discriminant) {
597 Some(index) => self.table.variants[index].value.as_deref_mut(),
598 None => match self.other.as_deref_mut() {
599 Some(other) => Some(other),
600 None => {
601 return Err(DecoderError::UnknownDiscriminant {
602 type_name: "HLAvariantRecord",
603 discriminant: format!("{discriminant:?}"),
604 });
605 }
606 },
607 };
608 if let Some(value) = value {
609 reader.align(alternative_boundary)?;
610 value.decode_from(reader)?;
611 }
612 self.table.discriminant = discriminant;
613 Ok(())
614 }
615
616 fn clone_element(&self) -> Box<DynElement> {
617 Box::new(self.clone())
618 }
619
620 fn is_same_type_as(&self, other: &DynElement) -> bool {
621 other.downcast_ref::<Self>().is_some_and(|other| {
622 self.table.same_shape(&other.table)
623 && same_optional_type(self.other.as_deref(), other.other.as_deref())
624 })
625 }
626}
627
628#[derive(Debug, Clone)]
639pub struct HLAextendableVariantRecord {
640 table: VariantTable,
641 unknown: Option<Vec<u8>>,
642}
643
644variant_record_api!(HLAextendableVariantRecord);
645
646impl HLAextendableVariantRecord {
647 pub fn new(discriminant_prototype: impl DataElement) -> Self {
650 Self { table: VariantTable::new(Box::new(discriminant_prototype)), unknown: None }
651 }
652
653 pub fn value(&self) -> Result<&DynElement, EncoderError> {
658 self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
659 }
660
661 pub fn value_mut(&mut self) -> Result<&mut DynElement, EncoderError> {
663 let index = self.table.active_index().ok_or(EncoderError::NoVariantForDiscriminant)?;
664 self.table.variants[index].value.as_deref_mut().ok_or(EncoderError::NoVariantForDiscriminant)
665 }
666
667 pub fn unknown_alternative(&self) -> Option<&[u8]> {
671 self.unknown.as_deref()
672 }
673
674 fn active(&self) -> Result<Option<&DynElement>, EncoderError> {
676 let index = self.table.active_index().ok_or(EncoderError::NoVariantForDiscriminant)?;
677 Ok(self.table.variants[index].value.as_deref())
678 }
679
680 fn selection_changed(&mut self) {
681 self.unknown = None;
682 }
683}
684
685impl DataElement for HLAextendableVariantRecord {
686 fn octet_boundary(&self) -> usize {
687 extendable::OCTET_BOUNDARY
688 }
689
690 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
691 let value = self.active()?;
692 if value.is_some_and(|value| value.octet_boundary() > extendable::ALTERNATIVE_BOUNDARY) {
693 return Err(mismatch("an HLAextendableVariantRecord alternative has an octet boundary above 8"));
694 }
695 let passed_on = self.unknown.as_deref().filter(|_| value.is_none()).unwrap_or_default();
698 let length = match value {
699 Some(value) => value.encoded_length()?,
700 None => passed_on.len(),
701 };
702 extendable::begin_encode(writer);
703 self.table.discriminant.encode_into(writer)?;
704 extendable::write_length(writer, length);
705 match value {
706 Some(value) => value.encode_into(writer)?,
707 None => writer.put_slice(passed_on),
708 }
709 writer.status()
710 }
711
712 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
713 extendable::begin_decode(reader)?;
714 let mut discriminant = self.table.prototype.clone();
715 discriminant.decode_from(reader)?;
716 let mut alternative = extendable::read_alternative(reader)?;
717 self.unknown = None;
718 match self.table.index_of(&*discriminant).map(|index| self.table.variants[index].value.as_deref_mut())
719 {
720 Some(Some(value)) => {
721 value.decode_from(alternative.reader())?;
722 alternative.finish()?;
723 }
724 Some(None) if alternative.is_empty() => {}
727 Some(None) | None => self.unknown = Some(alternative.into_bytes()),
728 }
729 self.table.discriminant = discriminant;
730 Ok(())
731 }
732
733 fn clone_element(&self) -> Box<DynElement> {
734 Box::new(self.clone())
735 }
736
737 fn is_same_type_as(&self, other: &DynElement) -> bool {
738 other.downcast_ref::<Self>().is_some_and(|other| self.table.same_shape(&other.table))
739 }
740}