microrti-encoding 0.1.1

HLA data encoding helpers of IEEE 1516-2025: basic types, strings, handles, arrays, records and variant records.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! The dynamic containers: constructed datatypes assembled at run time from boxed data elements, like
//! the complex encoding helpers of the Java and C++ APIs (12.11.4.2, 12.12.4.2).

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 }
}

/// Implements `PartialEq` through element equality: same datatype and same encoding.
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
);

/// `HLAfixedRecord`: fields of any datatypes, encoded in order, each at its own octet boundary. Nothing
/// follows the last field. The octet boundary of the record is the largest boundary of its fields.
#[derive(Debug, Clone, Default)]
pub struct HLAfixedRecord {
    fields: Vec<Box<DynElement>>,
}

impl HLAfixedRecord {
    /// A record without fields.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a field, builder style.
    pub fn with(mut self, element: impl DataElement) -> Self {
        self.fields.push(Box::new(element));
        self
    }

    /// Appends a field.
    pub fn push(&mut self, element: impl DataElement) -> &mut Self {
        self.fields.push(Box::new(element));
        self
    }

    /// Appends an already boxed field.
    pub fn push_boxed(&mut self, element: Box<DynElement>) -> &mut Self {
        self.fields.push(element);
        self
    }

    /// Number of fields.
    pub fn len(&self) -> usize {
        self.fields.len()
    }

    /// True for a record without fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    /// The field at `index`.
    pub fn get(&self, index: usize) -> Option<&DynElement> {
        self.fields.get(index).map(|field| &**field)
    }

    /// The field at `index`, mutable. Its value may change, its datatype stays.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
        self.fields.get_mut(index).map(|field| &mut **field)
    }

    /// The field at `index` as a `T`, if it is one.
    pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
        self.get(index)?.downcast_ref::<T>()
    }

    /// Replaces the field at `index` by an element of the same datatype.
    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(())
    }

    /// The fields in order.
    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))
        })
    }
}

/// Accessors shared by the two array containers.
macro_rules! array_accessors {
    ($name:ident) => {
        impl $name {
            /// The element every member of the array must match.
            pub fn prototype(&self) -> &DynElement {
                &*self.prototype
            }

            /// Number of elements.
            pub fn len(&self) -> usize {
                self.elements.len()
            }

            /// True for an array without elements.
            pub fn is_empty(&self) -> bool {
                self.elements.is_empty()
            }

            /// The element at `index`.
            pub fn get(&self, index: usize) -> Option<&DynElement> {
                self.elements.get(index).map(|element| &**element)
            }

            /// The element at `index`, mutable. Its value may change, its datatype stays.
            pub fn get_mut(&mut self, index: usize) -> Option<&mut DynElement> {
                self.elements.get_mut(index).map(|element| &mut **element)
            }

            /// The element at `index` as a `T`, if it is one.
            pub fn get_as<T: DataElement>(&self, index: usize) -> Option<&T> {
                self.get(index)?.downcast_ref::<T>()
            }

            /// Replaces the element at `index` by an element matching the prototype.
            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(())
            }

            /// The elements in order.
            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)
            }
        }
    };
}

/// `HLAfixedArray`: a fixed number of elements of one datatype, encoded in order without a count.
/// The octet boundary is the boundary of the element datatype.
#[derive(Debug, Clone)]
pub struct HLAfixedArray {
    prototype: Box<DynElement>,
    elements: Vec<Box<DynElement>>,
}

array_accessors!(HLAfixedArray);

impl HLAfixedArray {
    /// An array of `size` copies of `prototype`.
    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 }
    }

    /// An array holding `elements`, each of which must match `prototype`.
    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)
        })
    }
}

/// `HLAvariableArray`: the element count as `HLAinteger32BE`, then the elements of one datatype, each at
/// its own octet boundary. An empty array is the count alone. The octet boundary is the larger of 4 and
/// the boundary of the element datatype.
#[derive(Debug, Clone)]
pub struct HLAvariableArray {
    prototype: Box<DynElement>,
    elements: Vec<Box<DynElement>>,
}

array_accessors!(HLAvariableArray);

impl HLAvariableArray {
    /// An empty array whose elements will match `prototype`.
    pub fn new(prototype: impl DataElement) -> Self {
        Self { prototype: Box::new(prototype), elements: Vec::new() }
    }

    /// An array holding `elements`, each of which must match `prototype`.
    pub fn from_elements<E: DataElement>(
        prototype: impl DataElement,
        elements: impl IntoIterator<Item = E>,
    ) -> Result<Self, EncoderError> {
        Self::checked(Box::new(prototype), elements)
    }

    /// An array of statically typed elements; the prototype is `T::default()`.
    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 }
    }

    /// Appends an element, which must match the prototype.
    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)
    }

    /// Shrinks the array, or grows it with copies of the prototype.
    pub fn resize(&mut self, size: usize) {
        let prototype = &self.prototype;
        self.elements.resize_with(size, || prototype.clone());
    }

    /// Removes every element.
    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 {
    /// Encoded discriminant: discriminants are compared by their encoding.
    key: Vec<u8>,
    /// The alternative; `None` for a discriminant that carries no data.
    value: Option<Box<DynElement>>,
}

/// Discriminant bookkeeping shared by the two variant record containers.
#[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,
    }
}

/// Methods the two variant record containers have in common.
macro_rules! variant_record_api {
    ($name:ident) => {
        impl $name {
            /// Associates `value` with `discriminant` and makes that discriminant the active one.
            /// A previous association of the same discriminant is replaced.
            ///
            /// The discriminant must have the datatype of the discriminant prototype.
            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)
            }

            /// Registers `discriminant` as an enumerator without alternative data and makes it the
            /// active one.
            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)
            }

            /// Makes `discriminant` the active one. It needs no association yet, but encoding fails
            /// until it has one.
            pub fn set_discriminant(
                &mut self,
                discriminant: impl DataElement,
            ) -> Result<&mut Self, EncoderError> {
                self.table.select(Box::new(discriminant))?;
                self.selection_changed();
                Ok(self)
            }

            /// The active discriminant.
            pub fn discriminant(&self) -> &DynElement {
                &*self.table.discriminant
            }

            /// The active discriminant as a `T`, if it is one.
            pub fn discriminant_as<T: DataElement>(&self) -> Option<&T> {
                self.discriminant().downcast_ref::<T>()
            }

            /// The active alternative as a `T`, if there is one and it is a `T`.
            pub fn value_as<T: DataElement>(&self) -> Option<&T> {
                self.value().ok()?.downcast_ref::<T>()
            }

            /// True if `discriminant` has been registered with [`Self::set_variant`] or
            /// [`Self::set_empty_variant`].
            pub fn has_variant(&self, discriminant: &DynElement) -> bool {
                self.table.index_of(discriminant).is_some()
            }

            /// Number of registered discriminants.
            pub fn variant_count(&self) -> usize {
                self.table.variants.len()
            }
        }
    };
}

/// `HLAvariantRecord`: the discriminant, padding to the largest octet boundary of all alternatives, then
/// the alternative selected by the discriminant. A discriminant without alternative data is encoded
/// alone. The octet boundary is the largest boundary of the discriminant and of all alternatives.
///
/// The layout depends on every alternative, so sender and receiver must register the same ones.
#[derive(Debug, Clone)]
pub struct HLAvariantRecord {
    table: VariantTable,
    other: Option<Box<DynElement>>,
}

variant_record_api!(HLAvariantRecord);

impl HLAvariantRecord {
    /// A record whose discriminants have the datatype of `discriminant_prototype`, which is also the
    /// initial active discriminant.
    pub fn new(discriminant_prototype: impl DataElement) -> Self {
        Self { table: VariantTable::new(Box::new(discriminant_prototype)), other: None }
    }

    /// Sets the alternative used by every discriminant that has no association of its own (the
    /// `HLAother` enumerator of the OMT variant record table).
    pub fn set_other_variant(&mut self, value: impl DataElement) -> &mut Self {
        self.other = Some(Box::new(value));
        self
    }

    /// The alternative of the active discriminant.
    ///
    /// Fails with [`EncoderError::NoVariantForDiscriminant`] when the active discriminant has no
    /// alternative data.
    pub fn value(&self) -> Result<&DynElement, EncoderError> {
        self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
    }

    /// The alternative of the active discriminant, mutable.
    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)
    }

    /// `Ok(None)` for a registered discriminant without data, `Err` for an unmapped discriminant.
    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())
        })
    }
}

/// `HLAextendableVariantRecord`: a variant record whose encoding states the length of the alternative,
/// so that a receiver skips alternatives it does not know and other FOM modules can add alternatives.
///
/// Decoding a discriminant without association is therefore not an error: the discriminant becomes the
/// active one, the octets of its alternative are kept in [`Self::unknown_alternative`], and
/// [`Self::value`] fails as the standard APIs prescribe.
///
/// The exact layout is described, with its caveat, in the [`extendable`] module.
#[derive(Debug, Clone)]
pub struct HLAextendableVariantRecord {
    table: VariantTable,
    unknown: Option<Vec<u8>>,
}

variant_record_api!(HLAextendableVariantRecord);

impl HLAextendableVariantRecord {
    /// A record whose discriminants have the datatype of `discriminant_prototype`, which is also the
    /// initial active discriminant.
    pub fn new(discriminant_prototype: impl DataElement) -> Self {
        Self { table: VariantTable::new(Box::new(discriminant_prototype)), unknown: None }
    }

    /// The alternative of the active discriminant.
    ///
    /// Fails with [`EncoderError::NoVariantForDiscriminant`] when the active discriminant has no
    /// association or no alternative data.
    pub fn value(&self) -> Result<&DynElement, EncoderError> {
        self.active()?.ok_or(EncoderError::NoVariantForDiscriminant)
    }

    /// The alternative of the active discriminant, mutable.
    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)
    }

    /// The octets of the alternative that the last decoding skipped because its discriminant has no
    /// association; `None` when the last decoded discriminant was a registered one.
    pub fn unknown_alternative(&self) -> Option<&[u8]> {
        self.unknown.as_deref()
    }

    /// `Ok(None)` for a registered discriminant without data, `Err` for an unmapped discriminant.
    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()?;
        let length = match value {
            Some(value) => value.encoded_length()?,
            None => 0,
        };
        extendable::begin_encode(writer);
        self.table.discriminant.encode_into(writer)?;
        extendable::write_length(writer, length);
        if let Some(value) = value {
            value.encode_into(writer)?;
        }
        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) {
            Some(index) => {
                if let Some(value) = self.table.variants[index].value.as_deref_mut() {
                    value.decode_from(alternative.reader())?;
                }
                alternative.finish()?;
            }
            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))
    }
}