Skip to main content

microrti_encoding/
dynamic.rs

1//! The dynamic containers: constructed datatypes assembled at run time from boxed data elements, like
2//! the complex encoding helpers of the Java and C++ APIs (12.11.4.2, 12.12.4.2).
3
4use 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
17/// Implements `PartialEq` through element equality: same datatype and same encoding.
18macro_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/// `HLAfixedRecord` (IEEE 1516.2 4.14.10.1): fields of any datatypes, encoded in order, each at its own
38/// octet boundary. Nothing follows the last field. The octet boundary of the record is the largest
39/// boundary of its fields.
40#[derive(Debug, Clone, Default)]
41pub struct HLAfixedRecord {
42    fields: Vec<Box<DynElement>>,
43}
44
45impl HLAfixedRecord {
46    /// A record without fields.
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// Appends a field, builder style.
52    pub fn with(mut self, element: impl DataElement) -> Self {
53        self.fields.push(Box::new(element));
54        self
55    }
56
57    /// Appends a field.
58    pub fn push(&mut self, element: impl DataElement) -> &mut Self {
59        self.fields.push(Box::new(element));
60        self
61    }
62
63    /// Appends an already boxed field.
64    pub fn push_boxed(&mut self, element: Box<DynElement>) -> &mut Self {
65        self.fields.push(element);
66        self
67    }
68
69    /// Number of fields.
70    pub fn len(&self) -> usize {
71        self.fields.len()
72    }
73
74    /// True for a record without fields.
75    pub fn is_empty(&self) -> bool {
76        self.fields.is_empty()
77    }
78
79    /// The field at `index`.
80    pub fn get(&self, index: usize) -> Option<&DynElement> {
81        self.fields.get(index).map(|field| &**field)
82    }
83
84    /// The field at `index`, mutable. Its value may change, its datatype stays.
85    pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
86        self.fields.get_mut(index).map(|field| &mut **field)
87    }
88
89    /// The field at `index` as a `T`, if it is one.
90    pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
91        self.get(index)?.downcast_ref::<T>()
92    }
93
94    /// Replaces the field at `index` by an element of the same datatype.
95    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    /// The fields in order.
106    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
144/// Accessors shared by the two array containers.
145macro_rules! array_accessors {
146    ($name:ident) => {
147        impl $name {
148            /// The element every member of the array must match.
149            pub fn prototype(&self) -> &DynElement {
150                &*self.prototype
151            }
152
153            /// Number of elements.
154            pub fn len(&self) -> usize {
155                self.elements.len()
156            }
157
158            /// True for an array without elements.
159            pub fn is_empty(&self) -> bool {
160                self.elements.is_empty()
161            }
162
163            /// The element at `index`.
164            pub fn get(&self, index: usize) -> Option<&DynElement> {
165                self.elements.get(index).map(|element| &**element)
166            }
167
168            /// The element at `index`, mutable. Its value may change, its datatype stays.
169            pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
170                self.elements.get_mut(index).map(|element| &mut **element)
171            }
172
173            /// The element at `index` as a `T`, if it is one.
174            pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
175                self.get(index)?.downcast_ref::<T>()
176            }
177
178            /// Replaces the element at `index` by an element matching the prototype.
179            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            /// The elements in order.
190            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/// `HLAfixedArray` (IEEE 1516.2 4.14.10.4): a fixed number of elements of one datatype, encoded in order
212/// without a count. The octet boundary is the boundary of the element datatype.
213#[derive(Debug, Clone)]
214pub struct HLAfixedArray {
215    prototype: Box<DynElement>,
216    elements: Vec<Box<DynElement>>,
217}
218
219array_accessors!(HLAfixedArray);
220
221impl HLAfixedArray {
222    /// An array of `size` copies of `prototype`.
223    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    /// An array holding `elements`, each of which must match `prototype`.
230    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/// `HLAvariableArray` (IEEE 1516.2 4.14.10.5): the element count as `HLAinteger32BE`, then the elements
271/// of one datatype, each at its own octet boundary. An empty array is the count alone. The octet boundary
272/// is the larger of 4 and the boundary of the element datatype.
273#[derive(Debug, Clone)]
274pub struct HLAvariableArray {
275    prototype: Box<DynElement>,
276    elements: Vec<Box<DynElement>>,
277}
278
279array_accessors!(HLAvariableArray);
280
281impl HLAvariableArray {
282    /// An empty array whose elements will match `prototype`.
283    pub fn new(prototype: impl DataElement) -> Self {
284        Self { prototype: Box::new(prototype), elements: Vec::new() }
285    }
286
287    /// An array holding `elements`, each of which must match `prototype`.
288    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    /// An array of statically typed elements; the prototype is `T::default()`.
296    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    /// Appends an element, which must match the prototype.
302    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    /// Shrinks the array, or grows it with copies of the prototype.
311    pub fn resize(&mut self, size: usize) {
312        let prototype = &self.prototype;
313        self.elements.resize_with(size, || prototype.clone());
314    }
315
316    /// Removes every element.
317    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    /// Encoded discriminant: discriminants are compared by their encoding.
360    key: Vec<u8>,
361    /// The alternative; `None` for a discriminant that carries no data.
362    value: Option<Box<DynElement>>,
363}
364
365/// Discriminant bookkeeping shared by the two variant record containers.
366#[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
442/// Methods the two variant record containers have in common.
443macro_rules! variant_record_api {
444    ($name:ident) => {
445        impl $name {
446            /// Associates `value` with `discriminant` and makes that discriminant the active one.
447            /// A previous association of the same discriminant is replaced.
448            ///
449            /// The discriminant must have the datatype of the discriminant prototype.
450            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            /// Registers `discriminant` as an enumerator without alternative data and makes it the
461            /// active one.
462            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            /// Makes `discriminant` the active one. It needs no association yet, but encoding fails
472            /// until it has one.
473            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            /// The active discriminant.
483            pub fn discriminant(&self) -> &DynElement {
484                &*self.table.discriminant
485            }
486
487            /// The active discriminant as a `T`, if it is one.
488            pub fn discriminant_as<T: DataElement>(&self) -> Option<&T> {
489                self.discriminant().downcast_ref::<T>()
490            }
491
492            /// The active alternative as a `T`, if there is one and it is a `T`.
493            pub fn value_as<T: DataElement>(&self) -> Option<&T> {
494                self.value().ok()?.downcast_ref::<T>()
495            }
496
497            /// True if `discriminant` has been registered with [`Self::set_variant`] or
498            /// [`Self::set_empty_variant`].
499            pub fn has_variant(&self, discriminant: &DynElement) -> bool {
500                self.table.index_of(discriminant).is_some()
501            }
502
503            /// Number of registered discriminants.
504            pub fn variant_count(&self) -> usize {
505                self.table.variants.len()
506            }
507        }
508    };
509}
510
511/// `HLAvariantRecord` (IEEE 1516.2 4.14.10.2): the discriminant, padding to the largest octet boundary of
512/// all alternatives, then the alternative selected by the discriminant. A discriminant without alternative
513/// data is encoded alone. The octet boundary is the largest boundary of the discriminant and of all
514/// alternatives.
515///
516/// The layout depends on every alternative, so sender and receiver must register the same ones. The
517/// datatype is what is registered: an enumerator that has no alternative must be registered with
518/// [`Self::set_empty_variant`], otherwise encoding fails, as the standard APIs require, and so does
519/// decoding ([`DecoderError::UnknownDiscriminant`]).
520#[derive(Debug, Clone)]
521pub struct HLAvariantRecord {
522    table: VariantTable,
523    other: Option<Box<DynElement>>,
524}
525
526variant_record_api!(HLAvariantRecord);
527
528impl HLAvariantRecord {
529    /// A record whose discriminants have the datatype of `discriminant_prototype`, which is also the
530    /// initial active discriminant.
531    pub fn new(discriminant_prototype: impl DataElement) -> Self {
532        Self { table: VariantTable::new(Box::new(discriminant_prototype)), other: None }
533    }
534
535    /// Sets the alternative used by every discriminant that has no association of its own (the
536    /// `HLAother` enumerator of the OMT variant record table).
537    pub fn set_other_variant(&mut self, value: impl DataElement) -> &mut Self {
538        self.other = Some(Box::new(value));
539        self
540    }
541
542    /// The alternative of the active discriminant.
543    ///
544    /// Fails with [`EncoderError::NoVariantForDiscriminant`] when the active discriminant has no
545    /// alternative data.
546    pub fn value(&self) -> Result<&DynElement, EncoderError> {
547        self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
548    }
549
550    /// The alternative of the active discriminant, mutable.
551    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    /// `Ok(None)` for a registered discriminant without data, `Err` for an unmapped discriminant.
560    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/// `HLAextendableVariantRecord` (IEEE 1516.2 4.14.10.3): a variant record whose encoding states the length
629/// of the alternative, so that a receiver skips alternatives it does not know and other FOM modules can
630/// add alternatives (4.14.8, annex C).
631///
632/// Decoding a discriminant without association is therefore not an error: the discriminant becomes the
633/// active one, the octets of its alternative are kept in [`Self::unknown_alternative`], and
634/// [`Self::value`] fails as the standard APIs prescribe. The same holds for data received for a
635/// discriminant registered without data; encoding passes those octets on.
636///
637/// The layout is described in the [`extendable`] module.
638#[derive(Debug, Clone)]
639pub struct HLAextendableVariantRecord {
640    table: VariantTable,
641    unknown: Option<Vec<u8>>,
642}
643
644variant_record_api!(HLAextendableVariantRecord);
645
646impl HLAextendableVariantRecord {
647    /// A record whose discriminants have the datatype of `discriminant_prototype`, which is also the
648    /// initial active discriminant.
649    pub fn new(discriminant_prototype: impl DataElement) -> Self {
650        Self { table: VariantTable::new(Box::new(discriminant_prototype)), unknown: None }
651    }
652
653    /// The alternative of the active discriminant.
654    ///
655    /// Fails with [`EncoderError::NoVariantForDiscriminant`] when the active discriminant has no
656    /// association or no alternative data.
657    pub fn value(&self) -> Result<&DynElement, EncoderError> {
658        self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
659    }
660
661    /// The alternative of the active discriminant, mutable.
662    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    /// The octets of the alternative that the last decoding skipped because its discriminant has no
668    /// association, or one without data; `None` when the last decoding used the registered alternative.
669    /// For a discriminant registered without data, encoding passes these octets on.
670    pub fn unknown_alternative(&self) -> Option<&[u8]> {
671        self.unknown.as_deref()
672    }
673
674    /// `Ok(None)` for a registered discriminant without data, `Err` for an unmapped discriminant.
675    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        // A discriminant registered without data passes on the octets another module's alternative
696        // brought along when it was decoded.
697        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            // Without an association, or associated without data while another FOM module gives this
725            // enumerator an alternative (annex C merges alternatives): the octets are kept.
726            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}