microrti-encoding 0.2.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! The resolved type table: every data type of an FDD reduced to what the encoding rules need.

use std::collections::BTreeMap;
use std::fmt;

use microrti_fom::{
    ArrayData, BasicData, DataType, EXTENDABLE_VARIANT_RECORD, Endian, EnumeratedData, Fdd, FixedRecordData,
    VariantRecordData,
};

use super::error::CodecError;
use crate::buffer::COUNT_BOUNDARY;
use crate::extendable;

/// Deepest nesting of data types the codec accepts; it bounds the recursion of encoding and decoding.
pub(crate) const MAX_NESTING: usize = 64;

/// Size in octets of the length field of an `HLAextendableVariantRecord`.
const LENGTH_SIZE: usize = 4;

/// The MIM arrays of `HLAbyte` that hold the encoded form of a handle (12.2).
const HANDLE_TYPES: [&str; 10] = [
    "HLAfederateHandle",
    "HLAobjectClassHandle",
    "HLAattributeHandle",
    "HLAobjectInstanceHandle",
    "HLAinteractionClassHandle",
    "HLAparameterHandle",
    "HLAdimensionHandle",
    "HLAregionHandle",
    "HLAmessageRetractionHandle",
    "HLAtransportationTypeHandle",
];

/// How the octets of a scalar are interpreted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ScalarKind {
    Signed,
    Unsigned,
    Float,
    Octet,
    AsciiChar,
    UnicodeChar,
    /// More than 64 bits: the octets as they travel, as `Value::Bytes`.
    Opaque,
}

/// Largest basic representation the codec resolves, in bits. Larger ones are raw: their octet boundary
/// would make a single value pad by megabytes.
pub(crate) const MAX_BASIC_BITS: u32 = 1024;

/// A basic representation (4.14.3) of any size up to [`MAX_BASIC_BITS`].
///
/// A size that is not a multiple of 8 bits is padded with bits up to the next multiple of 8 (4.14.10),
/// zeros when encoding, ignored when decoding. Where the padding bits go is not said; here they are the
/// most significant bits of the field in the byte order of the representation, so the value is the field
/// read as an integer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Scalar {
    pub kind: ScalarKind,
    /// Size in bits, as the basic data representation table gives it.
    pub bits: u32,
    /// Size in octets: the bits rounded up to a multiple of 8.
    pub size: usize,
    /// Octet boundary: the smallest power of two `b` with `8 * b` at least the size in bits (4.14.10).
    pub boundary: usize,
    pub little: bool,
}

impl Scalar {
    /// A representation of `bits` bits, `None` for 0 or more than [`MAX_BASIC_BITS`].
    pub(crate) fn new(kind: ScalarKind, bits: u32, little: bool) -> Option<Self> {
        if bits == 0 || bits > MAX_BASIC_BITS {
            return None;
        }
        let size = usize::try_from(bits.div_ceil(8)).ok()?;
        Some(Scalar { kind, bits, size, boundary: size.next_power_of_two(), little })
    }

    pub(crate) fn is_integer(self) -> bool {
        matches!(self.kind, ScalarKind::Signed | ScalarKind::Unsigned | ScalarKind::Octet)
    }

    /// Smallest and largest integer the representation carries (at most 64 bits wide).
    pub(crate) fn integer_range(self) -> (i128, i128) {
        let bits = self.bits.min(64);
        match self.kind {
            ScalarKind::Signed => (-(1i128 << (bits - 1)), (1i128 << (bits - 1)) - 1),
            _ => (0, (1i128 << bits) - 1),
        }
    }

    /// Number of padding bits in the most significant octet of the field.
    pub(crate) fn padding_bits(self) -> u32 {
        8 * self.size as u32 - self.bits
    }
}

/// One enumerator with the values the representation can carry.
#[derive(Debug, Clone)]
pub(crate) struct EnumEntry {
    pub name: String,
    pub values: Vec<i128>,
}

#[derive(Debug, Clone)]
pub(crate) struct EnumInfo {
    pub repr: Scalar,
    pub entries: Vec<EnumEntry>,
    pub by_name: BTreeMap<String, usize>,
    pub by_value: BTreeMap<i128, usize>,
    /// The values of `HLAfalse` and `HLAtrue` when this is `HLAboolean`.
    pub boolean: Option<(i128, i128)>,
}

/// Character encoding of a string array.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TextUnit {
    Ascii,
    Utf16 { little: bool },
}

/// Element count of an array: fixed by the data type, or encoded in front of the elements.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Length {
    Fixed(usize),
    Variable { min: usize, max: Option<usize> },
}

impl Length {
    pub(crate) fn accepts(self, count: usize) -> bool {
        match self {
            Length::Fixed(expected) => count == expected,
            Length::Variable { min, max } => count >= min && max.is_none_or(|max| count <= max),
        }
    }
}

impl fmt::Display for Length {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Length::Fixed(count) => write!(f, "{count}"),
            Length::Variable { min: 0, max: None } => f.write_str("Dynamic"),
            Length::Variable { min, max: None } => write!(f, "[{min}..]"),
            Length::Variable { min, max: Some(max) } => write!(f, "[{min}..{max}]"),
        }
    }
}

/// One alternative of a variant record.
#[derive(Debug, Clone)]
pub(crate) struct AltInfo {
    pub name: Option<String>,
    /// Data type of the alternative; `None` when it carries no data.
    pub node: Option<usize>,
}

impl AltInfo {
    /// Path segment of the alternative in error messages.
    pub(crate) fn segment(&self) -> String {
        match &self.name {
            Some(name) => format!(".{name}"),
            None => ".<alternative>".to_owned(),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct VariantInfo {
    /// Name of the discriminant, for error paths.
    pub discriminant_name: String,
    /// Node of the enumerated data type of the discriminant.
    pub discriminant: usize,
    pub alternatives: Vec<AltInfo>,
    /// Alternative selected by each enumerator of the discriminant data type, by enumerator index.
    pub by_entry: Vec<Option<usize>>,
    /// Alternative of `HLAother`: every discriminant without an alternative of its own.
    pub other: Option<usize>,
    /// Largest octet boundary of the alternatives.
    pub alternative_boundary: usize,
    /// Encoding `HLAextendableVariantRecord` instead of `HLAvariantRecord`.
    pub extendable: bool,
}

#[derive(Debug, Clone)]
pub(crate) enum Kind {
    Scalar(Scalar),
    Enumerated(EnumInfo),
    /// An array of characters.
    Text {
        unit: TextUnit,
        length: Length,
    },
    /// An array of octets.
    Octets {
        handle: bool,
        length: Length,
    },
    Array {
        element: usize,
        length: Length,
    },
    Record {
        fields: Vec<(String, usize)>,
    },
    Variant(VariantInfo),
    /// A data type the codec cannot resolve; `reason` says why.
    Raw {
        reason: String,
    },
}

#[derive(Debug, Clone)]
pub(crate) struct Node {
    /// Name of the data type, for messages.
    pub name: String,
    /// Octet boundary.
    pub boundary: usize,
    /// Lower bound of the encoded length in octets.
    pub min_size: usize,
    /// Levels of data types below and including this one.
    pub depth: usize,
    /// The encoding has no end of its own: it ends with raw data, which takes every octet left.
    pub greedy: bool,
    pub kind: Kind,
}

impl Node {
    /// What a value must be to fit this data type, for type mismatch messages.
    pub(crate) fn expected(&self) -> String {
        let what = match &self.kind {
            Kind::Scalar(scalar) => match scalar.kind {
                ScalarKind::Signed | ScalarKind::Unsigned => "an integer",
                ScalarKind::Float => "a number",
                ScalarKind::Octet => "an octet",
                ScalarKind::AsciiChar | ScalarKind::UnicodeChar => "a character",
                ScalarKind::Opaque => "bytes",
            },
            Kind::Enumerated(_) => "an enumerator",
            Kind::Text { .. } => "a string",
            Kind::Octets { .. } => "bytes",
            Kind::Array { .. } => "an array",
            Kind::Record { .. } => "a record",
            Kind::Variant(_) => "a variant record",
            Kind::Raw { .. } => "raw bytes",
        };
        format!("{what} ({})", self.name)
    }
}

#[derive(Debug, Clone)]
pub(crate) struct TypeTable {
    pub nodes: Vec<Node>,
    /// Data type name to node. Simple and reference data types share the node of their representation.
    pub by_name: BTreeMap<String, usize>,
    /// Node of attributes and parameters without a usable data type.
    pub untyped: usize,
}

/// Resolves the data type tables of `fdd`.
pub(crate) fn build(fdd: &Fdd) -> Result<TypeTable, CodecError> {
    let defs = fdd.data_types();
    let mut index: BTreeMap<&str, usize> = BTreeMap::new();
    for (position, def) in defs.iter().enumerate() {
        index.entry(def.name()).or_insert(position);
    }
    let mut builder = Builder { index, resolved: vec![None; defs.len()], nodes: Vec::new() };
    for position in order(defs, &builder.index)? {
        let node = builder.build(&defs[position])?;
        builder.resolved[position] = Some(node);
    }
    let untyped = builder.raw("NA", "no data type is given".to_owned());
    let by_name = builder
        .index
        .iter()
        .filter_map(|(name, &position)| Some(((*name).to_owned(), builder.resolved[position]?)))
        .collect();
    Ok(TypeTable { nodes: builder.nodes, by_name, untyped })
}

/// Names of the data types a definition is made of.
fn dependencies(def: &DataType) -> Vec<&str> {
    let mut names: Vec<&str> = Vec::new();
    match def {
        DataType::Basic(_) => {}
        DataType::Simple(data) => names.extend(data.representation.as_deref()),
        DataType::Reference(data) => names.push(&data.representation),
        DataType::Enumerated(data) => names.extend(data.representation.as_deref()),
        DataType::Array(data) => names.extend(data.data_type.as_deref()),
        DataType::FixedRecord(data) => {
            names.extend(data.fields.iter().filter_map(|field| field.data_type.as_deref()));
        }
        DataType::VariantRecord(data) => {
            names.extend(data.data_type.as_deref());
            names.extend(data.alternatives.iter().filter_map(|alternative| alternative.data_type.as_deref()));
        }
    }
    names
}

/// The definitions in an order that puts every data type after the data types it is made of, found
/// without recursion so that long chains of definitions cannot exhaust the stack. A definition that
/// contains itself is an error.
fn order(defs: &[DataType], index: &BTreeMap<&str, usize>) -> Result<Vec<usize>, CodecError> {
    const NEW: u8 = 0;
    const OPEN: u8 = 1;
    const DONE: u8 = 2;

    let children: Vec<Vec<usize>> = defs
        .iter()
        .map(|def| dependencies(def).into_iter().filter_map(|name| index.get(name).copied()).collect())
        .collect();
    let mut state = vec![NEW; defs.len()];
    let mut order = Vec::with_capacity(defs.len());
    let mut stack: Vec<(usize, usize)> = Vec::new();
    for root in 0..defs.len() {
        if state[root] != NEW {
            continue;
        }
        state[root] = OPEN;
        stack.push((root, 0));
        while let Some(top) = stack.last_mut() {
            let (current, position) = *top;
            top.1 += 1;
            match children[current].get(position).copied() {
                Some(child) if state[child] == NEW => {
                    state[child] = OPEN;
                    stack.push((child, 0));
                }
                Some(child) if state[child] == OPEN => {
                    let start = stack.iter().position(|&(open, _)| open == child).unwrap_or(0);
                    let mut names: Vec<&str> =
                        stack[start..].iter().map(|&(open, _)| defs[open].name()).collect();
                    names.push(defs[child].name());
                    return Err(CodecError::RecursiveDataType { cycle: names.join(" -> ") });
                }
                Some(_) => {}
                None => {
                    state[current] = DONE;
                    order.push(current);
                    stack.pop();
                }
            }
        }
    }
    Ok(order)
}

/// The predefined basic representations of the MIM (11.6).
fn standard_scalar(name: &str) -> Option<Scalar> {
    use ScalarKind::{Float, Octet, Signed, Unsigned};
    let (kind, size, little) = match name {
        "HLAinteger16BE" => (Signed, 2, false),
        "HLAinteger16LE" => (Signed, 2, true),
        "HLAinteger32BE" => (Signed, 4, false),
        "HLAinteger32LE" => (Signed, 4, true),
        "HLAinteger64BE" => (Signed, 8, false),
        "HLAinteger64LE" => (Signed, 8, true),
        "HLAunsignedInteger8" => (Unsigned, 1, false),
        "HLAunsignedInteger16BE" => (Unsigned, 2, false),
        "HLAunsignedInteger16LE" => (Unsigned, 2, true),
        "HLAunsignedInteger32BE" => (Unsigned, 4, false),
        "HLAunsignedInteger32LE" => (Unsigned, 4, true),
        "HLAunsignedInteger64BE" => (Unsigned, 8, false),
        "HLAunsignedInteger64LE" => (Unsigned, 8, true),
        "HLAfloat32BE" => (Float, 4, false),
        "HLAfloat32LE" => (Float, 4, true),
        "HLAfloat64BE" => (Float, 8, false),
        "HLAfloat64LE" => (Float, 8, true),
        "HLAoctet" => (Octet, 1, false),
        "HLAoctetPairBE" => (Unsigned, 2, false),
        "HLAoctetPairLE" => (Unsigned, 2, true),
        _ => return None,
    };
    Scalar::new(kind, 8 * size, little)
}

/// A basic representation: the predefined ones by name, any other by its size, its endianness and the
/// words of its name, interpretation and encoding. Floats are 32 or 64 bits; above 64 bits the octets are
/// opaque.
fn scalar_of(data: &BasicData) -> Option<Scalar> {
    if let Some(scalar) = standard_scalar(&data.name) {
        return Some(scalar);
    }
    let bits = data.size?;
    let little = matches!(data.endian, Some(Endian::Little));
    let hints = format!(
        "{} {} {}",
        data.name,
        data.interpretation.as_deref().unwrap_or(""),
        data.encoding.as_deref().unwrap_or("")
    )
    .to_ascii_lowercase();
    let has = |word: &str| hints.contains(word);
    let kind = if bits > 64 {
        ScalarKind::Opaque
    } else if matches!(bits, 32 | 64) && (has("float") || has("ieee") || has("-precision")) {
        ScalarKind::Float
    } else if has("unsigned") || has("[0,") || has("[0 ,") || has("non-negative") {
        ScalarKind::Unsigned
    } else if has("signed") || has("integer") || has("complement") {
        ScalarKind::Signed
    } else if bits == 8 {
        ScalarKind::Octet
    } else {
        ScalarKind::Unsigned
    };
    Scalar::new(kind, bits, little)
}

/// An integer as the FOM writes enumerator values: decimal, or hexadecimal with `0x`.
fn parse_integer(text: &str) -> Option<i128> {
    let text = text.trim();
    let (negative, digits) = match text.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, text.strip_prefix('+').unwrap_or(text)),
    };
    let magnitude = match digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0X")) {
        Some(hex) => i128::from(u64::from_str_radix(hex, 16).ok()?),
        None => i128::from(digits.parse::<u64>().ok()?),
    };
    Some(if negative { -magnitude } else { magnitude })
}

/// One dimension of a cardinality as inclusive bounds: `Dynamic`, `n` or `[a..b]`.
fn parse_cardinality(text: &str) -> Option<(usize, Option<usize>)> {
    if text.eq_ignore_ascii_case("Dynamic") {
        return Some((0, None));
    }
    if let Some(range) = text.strip_prefix('[').and_then(|rest| rest.strip_suffix(']')) {
        let (low, high) = range.split_once("..")?;
        let low: usize = low.trim().parse().ok()?;
        let high: usize = high.trim().parse().ok()?;
        return (low <= high).then_some((low, Some(high)));
    }
    text.parse().ok().map(|count| (count, Some(count)))
}

/// The element counts of an array, outermost dimension first, or why the array cannot be resolved.
fn array_lengths(encoding: Option<&str>, cardinality: Option<&str>) -> Result<Vec<Length>, String> {
    let fixed = match encoding {
        Some("HLAfixedArray") => true,
        Some("HLAvariableArray") => false,
        Some(other) => return Err(format!("the encoding '{other}' is user-defined")),
        None => return Err("no encoding is given".to_owned()),
    };
    cardinality
        .unwrap_or("Dynamic")
        .split(',')
        .map(|part| {
            let part = part.trim();
            let bounds = parse_cardinality(part)
                .ok_or_else(|| format!("the cardinality '{part}' is not understood"))?;
            match (fixed, bounds) {
                (true, (min, Some(max))) if min == max => Ok(Length::Fixed(min)),
                (true, _) => Err(format!("HLAfixedArray needs a fixed cardinality, not '{part}'")),
                (false, (min, max)) => Ok(Length::Variable { min, max }),
            }
        })
        .collect()
}

struct Builder<'a> {
    /// Data type name to position in the FDD table.
    index: BTreeMap<&'a str, usize>,
    /// Node of each definition, once built.
    resolved: Vec<Option<usize>>,
    nodes: Vec<Node>,
}

impl Builder<'_> {
    fn push(
        &mut self,
        name: &str,
        kind: Kind,
        (boundary, min_size): (usize, usize),
        depth: usize,
        greedy: bool,
    ) -> Result<usize, CodecError> {
        if depth > MAX_NESTING {
            return Err(CodecError::NestingTooDeep { data_type: name.to_owned(), limit: MAX_NESTING });
        }
        self.nodes.push(Node { name: name.to_owned(), boundary, min_size, depth, greedy, kind });
        Ok(self.nodes.len() - 1)
    }

    /// A node for a data type that cannot be resolved.
    fn raw(&mut self, name: &str, reason: String) -> usize {
        self.nodes.push(Node {
            name: name.to_owned(),
            boundary: 1,
            min_size: 0,
            depth: 1,
            greedy: true,
            kind: Kind::Raw { reason },
        });
        self.nodes.len() - 1
    }

    /// The node of the data type called `name`, or why there is none.
    fn lookup(&self, name: Option<&str>) -> Result<usize, String> {
        let name = match name {
            None | Some("NA") => return Err("no data type is given".to_owned()),
            Some(name) => name,
        };
        self.index
            .get(name)
            .and_then(|&position| self.resolved[position])
            .ok_or_else(|| format!("the data type '{name}' is not defined"))
    }

    /// Like [`Self::lookup`], with a raw node for a data type that does not resolve.
    fn lookup_or_raw(&mut self, name: Option<&str>) -> usize {
        match self.lookup(name) {
            Ok(node) => node,
            Err(reason) => self.raw(name.unwrap_or("NA"), reason),
        }
    }

    fn build(&mut self, def: &DataType) -> Result<usize, CodecError> {
        match def {
            DataType::Basic(data) => self.basic(data),
            DataType::Simple(data) => self.simple(&data.name, data.representation.as_deref()),
            DataType::Reference(data) => match self.lookup(Some(&data.representation)) {
                Ok(node) => Ok(node),
                Err(reason) => Ok(self.raw(&data.name, reason)),
            },
            DataType::Enumerated(data) => self.enumerated(data),
            DataType::Array(data) => self.array(data),
            DataType::FixedRecord(data) => self.record(data),
            DataType::VariantRecord(data) => self.variant(data),
        }
    }

    fn basic(&mut self, data: &BasicData) -> Result<usize, CodecError> {
        match scalar_of(data) {
            Some(scalar) => {
                self.push(&data.name, Kind::Scalar(scalar), (scalar.boundary, scalar.size), 1, false)
            }
            None => {
                let reason = match data.size {
                    Some(bits) => format!(
                        "a basic representation of {bits} bits is not supported (1 to {MAX_BASIC_BITS} bits are)"
                    ),
                    None => "the basic representation has no size".to_owned(),
                };
                Ok(self.raw(&data.name, reason))
            }
        }
    }

    /// A simple data type is its representation, except for the two character types.
    fn simple(&mut self, name: &str, representation: Option<&str>) -> Result<usize, CodecError> {
        let target = match self.lookup(representation) {
            Ok(target) => target,
            Err(reason) => return Ok(self.raw(name, reason)),
        };
        let character = match (name, &self.nodes[target].kind) {
            ("HLAASCIIchar", Kind::Scalar(scalar)) if scalar.bits == 8 => {
                Some(Scalar { kind: ScalarKind::AsciiChar, ..*scalar })
            }
            ("HLAunicodeChar", Kind::Scalar(scalar)) if scalar.bits == 16 => {
                Some(Scalar { kind: ScalarKind::UnicodeChar, ..*scalar })
            }
            _ => None,
        };
        match character {
            Some(scalar) => self.push(name, Kind::Scalar(scalar), (scalar.boundary, scalar.size), 1, false),
            None => Ok(target),
        }
    }

    fn enumerated(&mut self, data: &EnumeratedData) -> Result<usize, CodecError> {
        let representation = match self.lookup(data.representation.as_deref()) {
            Ok(node) => match &self.nodes[node].kind {
                Kind::Scalar(scalar) if scalar.is_integer() => Ok(*scalar),
                _ => Err("the representation is not an integer data type".to_owned()),
            },
            Err(reason) => Err(reason),
        };
        let repr = match representation {
            Ok(repr) => repr,
            Err(reason) => return Ok(self.raw(&data.name, reason)),
        };
        let (low, high) = repr.integer_range();
        let mut entries: Vec<EnumEntry> = Vec::with_capacity(data.enumerators.len());
        let mut by_name = BTreeMap::new();
        let mut by_value = BTreeMap::new();
        for enumerator in &data.enumerators {
            let values: Vec<i128> = enumerator
                .values
                .iter()
                .filter_map(|text| parse_integer(text))
                .filter(|value| (low..=high).contains(value))
                .collect();
            let position = entries.len();
            by_name.entry(enumerator.name.clone()).or_insert(position);
            for value in &values {
                by_value.entry(*value).or_insert(position);
            }
            entries.push(EnumEntry { name: enumerator.name.clone(), values });
        }
        let single = |name: &str| {
            by_name.get(name).and_then(|&position: &usize| entries[position].values.first().copied())
        };
        let boolean =
            if data.name == "HLAboolean" { single("HLAfalse").zip(single("HLAtrue")) } else { None };
        let info = EnumInfo { repr, entries, by_name, by_value, boolean };
        self.push(&data.name, Kind::Enumerated(info), (repr.boundary, repr.size), 1, false)
    }

    /// One node per dimension, the outermost one carrying the name. The innermost dimension of
    /// characters or octets is a string or an octet sequence.
    fn array(&mut self, data: &ArrayData) -> Result<usize, CodecError> {
        let name = data.name.as_str();
        let lengths = match array_lengths(data.encoding.as_deref(), data.cardinality.as_deref()) {
            Ok(lengths) => lengths,
            Err(reason) => return Ok(self.raw(name, reason)),
        };
        let mut element = match self.lookup(data.data_type.as_deref()) {
            Ok(element) => element,
            Err(reason) => {
                return Ok(self.raw(name, format!("the element data type does not resolve: {reason}")));
            }
        };
        if self.nodes[element].greedy {
            let reason = format!("the element data type '{}' has no known length", self.nodes[element].name);
            return Ok(self.raw(name, reason));
        }
        let handle = lengths.len() == 1 && HANDLE_TYPES.contains(&name);
        for (level, length) in lengths.into_iter().rev().enumerate() {
            let inner = &self.nodes[element];
            let layout = match length {
                Length::Fixed(count) => (inner.boundary, count.saturating_mul(inner.min_size)),
                Length::Variable { .. } => (inner.boundary.max(COUNT_BOUNDARY), COUNT_BOUNDARY),
            };
            let depth = inner.depth + 1;
            let kind = match &inner.kind {
                Kind::Scalar(scalar) if level == 0 => match scalar.kind {
                    ScalarKind::AsciiChar => Kind::Text { unit: TextUnit::Ascii, length },
                    ScalarKind::UnicodeChar => {
                        Kind::Text { unit: TextUnit::Utf16 { little: scalar.little }, length }
                    }
                    ScalarKind::Octet => Kind::Octets { handle, length },
                    _ => Kind::Array { element, length },
                },
                _ => Kind::Array { element, length },
            };
            element = self.push(name, kind, layout, depth, false)?;
        }
        Ok(element)
    }

    fn record(&mut self, data: &FixedRecordData) -> Result<usize, CodecError> {
        let name = data.name.as_str();
        match data.encoding.as_deref() {
            Some("HLAfixedRecord") => {}
            Some(other) => return Ok(self.raw(name, format!("the encoding '{other}' is user-defined"))),
            None => return Ok(self.raw(name, "no encoding is given".to_owned())),
        }
        let mut fields = Vec::with_capacity(data.fields.len());
        let (mut boundary, mut min_size, mut depth, mut greedy) = (1usize, 0usize, 0usize, false);
        for field in &data.fields {
            if greedy {
                let reason = format!("a field of unknown length is followed by the field '{}'", field.name);
                return Ok(self.raw(name, reason));
            }
            let node = self.lookup_or_raw(field.data_type.as_deref());
            let inner = &self.nodes[node];
            boundary = boundary.max(inner.boundary);
            min_size = min_size.saturating_add(inner.min_size);
            depth = depth.max(inner.depth);
            greedy = inner.greedy;
            fields.push((field.name.clone(), node));
        }
        self.push(name, Kind::Record { fields }, (boundary, min_size), depth + 1, greedy)
    }

    fn variant(&mut self, data: &VariantRecordData) -> Result<usize, CodecError> {
        let name = data.name.as_str();
        let extendable = match data.encoding.as_deref() {
            Some("HLAvariantRecord") => false,
            Some(EXTENDABLE_VARIANT_RECORD) => true,
            Some(other) => return Ok(self.raw(name, format!("the encoding '{other}' is user-defined"))),
            None => return Ok(self.raw(name, "no encoding is given".to_owned())),
        };
        let enumeration = match self.lookup(data.data_type.as_deref()) {
            Ok(node) => match &self.nodes[node].kind {
                Kind::Enumerated(info) => Ok((node, info.repr, info.entries.len(), info.by_name.clone())),
                _ => Err("the discriminant data type is not an enumerated data type".to_owned()),
            },
            Err(reason) => Err(format!("the discriminant data type does not resolve: {reason}")),
        };
        let (discriminant, discriminant_repr, entry_count, by_name) = match enumeration {
            Ok(enumeration) => enumeration,
            Err(reason) => return Ok(self.raw(name, reason)),
        };

        let mut alternatives = Vec::with_capacity(data.alternatives.len());
        let (mut alternative_boundary, mut depth, mut greedy) = (1usize, 1usize, false);
        for alternative in &data.alternatives {
            let node = match alternative.data_type.as_deref() {
                None | Some("NA") => None,
                type_name => Some(self.lookup_or_raw(type_name)),
            };
            if let Some(node) = node {
                let inner = &self.nodes[node];
                alternative_boundary = alternative_boundary.max(inner.boundary);
                depth = depth.max(inner.depth);
                greedy |= inner.greedy;
            }
            let alternative_name = alternative.name.clone().filter(|name| name != "NA");
            alternatives.push(AltInfo { name: alternative_name, node });
        }

        // The enumerator column: a name, a list of names, a range `[first .. last]` in the order of the
        // enumerated data type, or HLAother.
        let mut by_entry: Vec<Option<usize>> = vec![None; entry_count];
        let mut other = None;
        for (position, alternative) in data.alternatives.iter().enumerate() {
            for item in alternative.enumerator.as_deref().unwrap_or("").split(',') {
                let item = item.trim();
                if item == "HLAother" {
                    other.get_or_insert(position);
                    continue;
                }
                let range = item.strip_prefix('[').and_then(|rest| rest.strip_suffix(']'));
                let (first, last) = match range.and_then(|range| range.split_once("..")) {
                    Some((first, last)) => (by_name.get(first.trim()), by_name.get(last.trim())),
                    None => (by_name.get(item), by_name.get(item)),
                };
                if let (Some(&first), Some(&last)) = (first, last) {
                    for slot in by_entry.get_mut(first..=last).into_iter().flatten() {
                        slot.get_or_insert(position);
                    }
                }
            }
        }

        if extendable && alternative_boundary > extendable::ALTERNATIVE_BOUNDARY {
            let reason = format!(
                "an alternative has the octet boundary {alternative_boundary}, more than the {} \
                 HLAextendableVariantRecord allows",
                extendable::ALTERNATIVE_BOUNDARY
            );
            return Ok(self.raw(name, reason));
        }
        let (layout, greedy) = if extendable {
            ((extendable::OCTET_BOUNDARY, discriminant_repr.size + LENGTH_SIZE), false)
        } else {
            ((discriminant_repr.boundary.max(alternative_boundary), discriminant_repr.size), greedy)
        };
        let info = VariantInfo {
            discriminant_name: data.discriminant.clone().unwrap_or_else(|| "discriminant".to_owned()),
            discriminant,
            alternatives,
            by_entry,
            other,
            alternative_boundary,
            extendable,
        };
        self.push(name, Kind::Variant(info), layout, depth + 1, greedy)
    }
}