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)]
40pub struct HLAfixedRecord {
41 fields: Vec<Box<DynElement>>,
42}
43
44impl HLAfixedRecord {
45 pub fn new() -> Self {
47 Self::default()
48 }
49
50 pub fn with(mut self, element: impl DataElement) -> Self {
52 self.fields.push(Box::new(element));
53 self
54 }
55
56 pub fn push(&mut self, element: impl DataElement) -> &mut Self {
58 self.fields.push(Box::new(element));
59 self
60 }
61
62 pub fn push_boxed(&mut self, element: Box<DynElement>) -> &mut Self {
64 self.fields.push(element);
65 self
66 }
67
68 pub fn len(&self) -> usize {
70 self.fields.len()
71 }
72
73 pub fn is_empty(&self) -> bool {
75 self.fields.is_empty()
76 }
77
78 pub fn get(&self, index: usize) -> Option<&DynElement> {
80 self.fields.get(index).map(|field| &**field)
81 }
82
83 pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
85 self.fields.get_mut(index).map(|field| &mut **field)
86 }
87
88 pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
90 self.get(index)?.downcast_ref::<T>()
91 }
92
93 pub fn set(&mut self, index: usize, element: impl DataElement) -> Result<(), EncoderError> {
95 let size = self.fields.len();
96 let field = self.fields.get_mut(index).ok_or_else(|| out_of_range(index, size))?;
97 if !field.is_same_type_as(&element) {
98 return Err(mismatch("element does not have the datatype of the field it replaces"));
99 }
100 *field = Box::new(element);
101 Ok(())
102 }
103
104 pub fn iter(&self) -> impl Iterator<Item = &DynElement> {
106 self.fields.iter().map(|field| &**field)
107 }
108}
109
110impl DataElement for HLAfixedRecord {
111 fn octet_boundary(&self) -> usize {
112 self.fields.iter().map(|field| field.octet_boundary()).max().unwrap_or(1)
113 }
114
115 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
116 writer.align(self.octet_boundary());
117 for field in &self.fields {
118 field.encode_into(writer)?;
119 }
120 writer.status()
121 }
122
123 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
124 reader.align(self.octet_boundary())?;
125 for field in &mut self.fields {
126 field.decode_from(reader)?;
127 }
128 Ok(())
129 }
130
131 fn clone_element(&self) -> Box<DynElement> {
132 Box::new(self.clone())
133 }
134
135 fn is_same_type_as(&self, other: &DynElement) -> bool {
136 other.downcast_ref::<Self>().is_some_and(|other| {
137 self.fields.len() == other.fields.len()
138 && self.fields.iter().zip(&other.fields).all(|(left, right)| left.is_same_type_as(&**right))
139 })
140 }
141}
142
143macro_rules! array_accessors {
145 ($name:ident) => {
146 impl $name {
147 pub fn prototype(&self) -> &DynElement {
149 &*self.prototype
150 }
151
152 pub fn len(&self) -> usize {
154 self.elements.len()
155 }
156
157 pub fn is_empty(&self) -> bool {
159 self.elements.is_empty()
160 }
161
162 pub fn get(&self, index: usize) -> Option<&DynElement> {
164 self.elements.get(index).map(|element| &**element)
165 }
166
167 pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
169 self.elements.get_mut(index).map(|element| &mut **element)
170 }
171
172 pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
174 self.get(index)?.downcast_ref::<T>()
175 }
176
177 pub fn set(&mut self, index: usize, element: impl DataElement) -> Result<(), EncoderError> {
179 let size = self.elements.len();
180 if !self.prototype.is_same_type_as(&element) {
181 return Err(mismatch("element does not match the prototype of the array"));
182 }
183 let slot = self.elements.get_mut(index).ok_or_else(|| out_of_range(index, size))?;
184 *slot = Box::new(element);
185 Ok(())
186 }
187
188 pub fn iter(&self) -> impl Iterator<Item = &DynElement> {
190 self.elements.iter().map(|element| &**element)
191 }
192
193 fn checked<E: DataElement>(
194 prototype: Box<DynElement>,
195 elements: impl IntoIterator<Item = E>,
196 ) -> Result<Self, EncoderError> {
197 let mut array = Self { prototype, elements: Vec::new() };
198 for element in elements {
199 if !array.prototype.is_same_type_as(&element) {
200 return Err(mismatch("element does not match the prototype of the array"));
201 }
202 array.elements.push(Box::new(element));
203 }
204 Ok(array)
205 }
206 }
207 };
208}
209
210#[derive(Debug, Clone)]
213pub struct HLAfixedArray {
214 prototype: Box<DynElement>,
215 elements: Vec<Box<DynElement>>,
216}
217
218array_accessors!(HLAfixedArray);
219
220impl HLAfixedArray {
221 pub fn new(prototype: impl DataElement, size: usize) -> Self {
223 let prototype: Box<DynElement> = Box::new(prototype);
224 let elements = (0..size).map(|_| prototype.clone()).collect();
225 Self { prototype, elements }
226 }
227
228 pub fn from_elements<E: DataElement>(
230 prototype: impl DataElement,
231 elements: impl IntoIterator<Item = E>,
232 ) -> Result<Self, EncoderError> {
233 Self::checked(Box::new(prototype), elements)
234 }
235}
236
237impl DataElement for HLAfixedArray {
238 fn octet_boundary(&self) -> usize {
239 self.prototype.octet_boundary()
240 }
241
242 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
243 writer.align(self.octet_boundary());
244 for element in &self.elements {
245 element.encode_into(writer)?;
246 }
247 writer.status()
248 }
249
250 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
251 reader.align(self.octet_boundary())?;
252 for element in &mut self.elements {
253 element.decode_from(reader)?;
254 }
255 Ok(())
256 }
257
258 fn clone_element(&self) -> Box<DynElement> {
259 Box::new(self.clone())
260 }
261
262 fn is_same_type_as(&self, other: &DynElement) -> bool {
263 other.downcast_ref::<Self>().is_some_and(|other| {
264 self.elements.len() == other.elements.len() && self.prototype.is_same_type_as(&*other.prototype)
265 })
266 }
267}
268
269#[derive(Debug, Clone)]
273pub struct HLAvariableArray {
274 prototype: Box<DynElement>,
275 elements: Vec<Box<DynElement>>,
276}
277
278array_accessors!(HLAvariableArray);
279
280impl HLAvariableArray {
281 pub fn new(prototype: impl DataElement) -> Self {
283 Self { prototype: Box::new(prototype), elements: Vec::new() }
284 }
285
286 pub fn from_elements<E: DataElement>(
288 prototype: impl DataElement,
289 elements: impl IntoIterator<Item = E>,
290 ) -> Result<Self, EncoderError> {
291 Self::checked(Box::new(prototype), elements)
292 }
293
294 pub fn of<T: DataElement + Default>(elements: impl IntoIterator<Item = T>) -> Self {
296 let elements = elements.into_iter().map(|element| Box::new(element) as Box<DynElement>).collect();
297 Self { prototype: Box::new(T::default()), elements }
298 }
299
300 pub fn push(&mut self, element: impl DataElement) -> Result<&mut Self, EncoderError> {
302 if !self.prototype.is_same_type_as(&element) {
303 return Err(mismatch("element does not match the prototype of the array"));
304 }
305 self.elements.push(Box::new(element));
306 Ok(self)
307 }
308
309 pub fn resize(&mut self, size: usize) {
311 let prototype = &self.prototype;
312 self.elements.resize_with(size, || prototype.clone());
313 }
314
315 pub fn clear(&mut self) {
317 self.elements.clear();
318 }
319}
320
321impl DataElement for HLAvariableArray {
322 fn octet_boundary(&self) -> usize {
323 self.prototype.octet_boundary().max(COUNT_BOUNDARY)
324 }
325
326 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
327 writer.align(self.octet_boundary());
328 writer.put_count(self.elements.len());
329 for element in &self.elements {
330 element.encode_into(writer)?;
331 }
332 writer.status()
333 }
334
335 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
336 reader.align(self.octet_boundary())?;
337 let count = reader.read_count()?;
338 self.elements.clear();
339 for _ in 0..count {
340 let mut element = self.prototype.clone();
341 element.decode_from(reader)?;
342 self.elements.push(element);
343 }
344 Ok(())
345 }
346
347 fn clone_element(&self) -> Box<DynElement> {
348 Box::new(self.clone())
349 }
350
351 fn is_same_type_as(&self, other: &DynElement) -> bool {
352 other.downcast_ref::<Self>().is_some_and(|other| self.prototype.is_same_type_as(&*other.prototype))
353 }
354}
355
356#[derive(Debug, Clone)]
357struct Variant {
358 key: Vec<u8>,
360 value: Option<Box<DynElement>>,
362}
363
364#[derive(Debug, Clone)]
366struct VariantTable {
367 prototype: Box<DynElement>,
368 discriminant: Box<DynElement>,
369 variants: Vec<Variant>,
370}
371
372impl VariantTable {
373 fn new(prototype: Box<DynElement>) -> Self {
374 Self { discriminant: prototype.clone(), prototype, variants: Vec::new() }
375 }
376
377 fn key_of(&self, discriminant: &DynElement) -> Result<Vec<u8>, EncoderError> {
378 if !self.prototype.is_same_type_as(discriminant) {
379 return Err(mismatch("discriminant does not match the discriminant prototype"));
380 }
381 discriminant.to_bytes()
382 }
383
384 fn set(
385 &mut self,
386 discriminant: Box<DynElement>,
387 value: Option<Box<DynElement>>,
388 ) -> Result<(), EncoderError> {
389 let key = self.key_of(&*discriminant)?;
390 match self.variants.iter().position(|variant| variant.key == key) {
391 Some(index) => self.variants[index].value = value,
392 None => self.variants.push(Variant { key, value }),
393 }
394 self.discriminant = discriminant;
395 Ok(())
396 }
397
398 fn select(&mut self, discriminant: Box<DynElement>) -> Result<(), EncoderError> {
399 self.key_of(&*discriminant)?;
400 self.discriminant = discriminant;
401 Ok(())
402 }
403
404 fn index_of(&self, discriminant: &DynElement) -> Option<usize> {
405 let key = discriminant.to_bytes().ok()?;
406 self.variants.iter().position(|variant| variant.key == key)
407 }
408
409 fn active_index(&self) -> Option<usize> {
410 self.index_of(&*self.discriminant)
411 }
412
413 fn alternative_boundary(&self) -> usize {
414 self.variants
415 .iter()
416 .filter_map(|variant| variant.value.as_deref())
417 .map(|value| value.octet_boundary())
418 .max()
419 .unwrap_or(1)
420 }
421
422 fn same_shape(&self, other: &Self) -> bool {
423 self.prototype.is_same_type_as(&*other.prototype)
424 && self.variants.len() == other.variants.len()
425 && self.variants.iter().all(|variant| {
426 other.variants.iter().find(|candidate| candidate.key == variant.key).is_some_and(
427 |candidate| same_optional_type(variant.value.as_deref(), candidate.value.as_deref()),
428 )
429 })
430 }
431}
432
433fn same_optional_type(left: Option<&DynElement>, right: Option<&DynElement>) -> bool {
434 match (left, right) {
435 (Some(left), Some(right)) => left.is_same_type_as(right),
436 (None, None) => true,
437 _ => false,
438 }
439}
440
441macro_rules! variant_record_api {
443 ($name:ident) => {
444 impl $name {
445 pub fn set_variant(
450 &mut self,
451 discriminant: impl DataElement,
452 value: impl DataElement,
453 ) -> Result<&mut Self, EncoderError> {
454 self.table.set(Box::new(discriminant), Some(Box::new(value)))?;
455 self.selection_changed();
456 Ok(self)
457 }
458
459 pub fn set_empty_variant(
462 &mut self,
463 discriminant: impl DataElement,
464 ) -> Result<&mut Self, EncoderError> {
465 self.table.set(Box::new(discriminant), None)?;
466 self.selection_changed();
467 Ok(self)
468 }
469
470 pub fn set_discriminant(
473 &mut self,
474 discriminant: impl DataElement,
475 ) -> Result<&mut Self, EncoderError> {
476 self.table.select(Box::new(discriminant))?;
477 self.selection_changed();
478 Ok(self)
479 }
480
481 pub fn discriminant(&self) -> &DynElement {
483 &*self.table.discriminant
484 }
485
486 pub fn discriminant_as<T: DataElement>(&self) -> Option<&T> {
488 self.discriminant().downcast_ref::<T>()
489 }
490
491 pub fn value_as<T: DataElement>(&self) -> Option<&T> {
493 self.value().ok()?.downcast_ref::<T>()
494 }
495
496 pub fn has_variant(&self, discriminant: &DynElement) -> bool {
499 self.table.index_of(discriminant).is_some()
500 }
501
502 pub fn variant_count(&self) -> usize {
504 self.table.variants.len()
505 }
506 }
507 };
508}
509
510#[derive(Debug, Clone)]
516pub struct HLAvariantRecord {
517 table: VariantTable,
518 other: Option<Box<DynElement>>,
519}
520
521variant_record_api!(HLAvariantRecord);
522
523impl HLAvariantRecord {
524 pub fn new(discriminant_prototype: impl DataElement) -> Self {
527 Self { table: VariantTable::new(Box::new(discriminant_prototype)), other: None }
528 }
529
530 pub fn set_other_variant(&mut self, value: impl DataElement) -> &mut Self {
533 self.other = Some(Box::new(value));
534 self
535 }
536
537 pub fn value(&self) -> Result<&DynElement, EncoderError> {
542 self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
543 }
544
545 pub fn value_mut(&mut self) -> Result<&mut DynElement, EncoderError> {
547 let value = match self.table.active_index() {
548 Some(index) => self.table.variants[index].value.as_deref_mut(),
549 None => self.other.as_deref_mut(),
550 };
551 value.ok_or(EncoderError::NoVariantForDiscriminant)
552 }
553
554 fn active(&self) -> Result<Option<&DynElement>, EncoderError> {
556 match self.table.active_index() {
557 Some(index) => Ok(self.table.variants[index].value.as_deref()),
558 None => self.other.as_deref().map(Some).ok_or(EncoderError::NoVariantForDiscriminant),
559 }
560 }
561
562 fn alternative_boundary(&self) -> usize {
563 let other = self.other.as_deref().map_or(1, |value| value.octet_boundary());
564 self.table.alternative_boundary().max(other)
565 }
566
567 fn selection_changed(&mut self) {}
568}
569
570impl DataElement for HLAvariantRecord {
571 fn octet_boundary(&self) -> usize {
572 self.table.prototype.octet_boundary().max(self.alternative_boundary())
573 }
574
575 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
576 let value = self.active()?;
577 writer.align(self.octet_boundary());
578 self.table.discriminant.encode_into(writer)?;
579 if let Some(value) = value {
580 writer.align(self.alternative_boundary());
581 value.encode_into(writer)?;
582 }
583 writer.status()
584 }
585
586 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
587 reader.align(self.octet_boundary())?;
588 let mut discriminant = self.table.prototype.clone();
589 discriminant.decode_from(reader)?;
590 let alternative_boundary = self.alternative_boundary();
591 let value = match self.table.index_of(&*discriminant) {
592 Some(index) => self.table.variants[index].value.as_deref_mut(),
593 None => match self.other.as_deref_mut() {
594 Some(other) => Some(other),
595 None => {
596 return Err(DecoderError::UnknownDiscriminant {
597 type_name: "HLAvariantRecord",
598 discriminant: format!("{discriminant:?}"),
599 });
600 }
601 },
602 };
603 if let Some(value) = value {
604 reader.align(alternative_boundary)?;
605 value.decode_from(reader)?;
606 }
607 self.table.discriminant = discriminant;
608 Ok(())
609 }
610
611 fn clone_element(&self) -> Box<DynElement> {
612 Box::new(self.clone())
613 }
614
615 fn is_same_type_as(&self, other: &DynElement) -> bool {
616 other.downcast_ref::<Self>().is_some_and(|other| {
617 self.table.same_shape(&other.table)
618 && same_optional_type(self.other.as_deref(), other.other.as_deref())
619 })
620 }
621}
622
623#[derive(Debug, Clone)]
632pub struct HLAextendableVariantRecord {
633 table: VariantTable,
634 unknown: Option<Vec<u8>>,
635}
636
637variant_record_api!(HLAextendableVariantRecord);
638
639impl HLAextendableVariantRecord {
640 pub fn new(discriminant_prototype: impl DataElement) -> Self {
643 Self { table: VariantTable::new(Box::new(discriminant_prototype)), unknown: None }
644 }
645
646 pub fn value(&self) -> Result<&DynElement, EncoderError> {
651 self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
652 }
653
654 pub fn value_mut(&mut self) -> Result<&mut DynElement, EncoderError> {
656 let index = self.table.active_index().ok_or(EncoderError::NoVariantForDiscriminant)?;
657 self.table.variants[index].value.as_deref_mut().ok_or(EncoderError::NoVariantForDiscriminant)
658 }
659
660 pub fn unknown_alternative(&self) -> Option<&[u8]> {
663 self.unknown.as_deref()
664 }
665
666 fn active(&self) -> Result<Option<&DynElement>, EncoderError> {
668 let index = self.table.active_index().ok_or(EncoderError::NoVariantForDiscriminant)?;
669 Ok(self.table.variants[index].value.as_deref())
670 }
671
672 fn selection_changed(&mut self) {
673 self.unknown = None;
674 }
675}
676
677impl DataElement for HLAextendableVariantRecord {
678 fn octet_boundary(&self) -> usize {
679 extendable::OCTET_BOUNDARY
680 }
681
682 fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
683 let value = self.active()?;
684 let length = match value {
685 Some(value) => value.encoded_length()?,
686 None => 0,
687 };
688 extendable::begin_encode(writer);
689 self.table.discriminant.encode_into(writer)?;
690 extendable::write_length(writer, length);
691 if let Some(value) = value {
692 value.encode_into(writer)?;
693 }
694 writer.status()
695 }
696
697 fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
698 extendable::begin_decode(reader)?;
699 let mut discriminant = self.table.prototype.clone();
700 discriminant.decode_from(reader)?;
701 let mut alternative = extendable::read_alternative(reader)?;
702 self.unknown = None;
703 match self.table.index_of(&*discriminant) {
704 Some(index) => {
705 if let Some(value) = self.table.variants[index].value.as_deref_mut() {
706 value.decode_from(alternative.reader())?;
707 }
708 alternative.finish()?;
709 }
710 None => self.unknown = Some(alternative.into_bytes()),
711 }
712 self.table.discriminant = discriminant;
713 Ok(())
714 }
715
716 fn clone_element(&self) -> Box<DynElement> {
717 Box::new(self.clone())
718 }
719
720 fn is_same_type_as(&self, other: &DynElement) -> bool {
721 other.downcast_ref::<Self>().is_some_and(|other| self.table.same_shape(&other.table))
722 }
723}