ondas 2.1.0

Read-only, format-independent waveform analysis library
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Source type graph and anonymous composite constraints.
use super::wire::Wire;
use crate::Result;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum Storage {
    B2,
    E8,
    I32,
    I64,
    F64,
    P32,
    P64,
}

impl Storage {
    #[cfg(test)]
    pub(super) fn tag(self) -> u8 {
        match self {
            Self::B2 => 22,
            Self::E8 => 23,
            Self::I32 => 25,
            Self::I64 => 26,
            Self::F64 => 27,
            Self::P32 => 28,
            Self::P64 => 29,
        }
    }

    fn from_tag(tag: u8, wire: &Wire) -> Result<Self> {
        match tag {
            22 => Ok(Self::B2),
            23 => Ok(Self::E8),
            25 => Ok(Self::I32),
            26 => Ok(Self::I64),
            27 => Ok(Self::F64),
            28 => Ok(Self::P32),
            29 => Ok(Self::P64),
            _ => Err(wire.unsupported(format_args!("range/storage tag {tag}"))),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Bound {
    Integer(i64),
    Real(u64),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Range {
    pub(super) storage: Storage,
    pub(super) downto: bool,
    pub(super) left: Bound,
    pub(super) right: Bound,
}

impl Range {
    fn read(wire: &mut Wire) -> Result<Self> {
        let tag = wire.byte()?;
        // These known type tags are not scalar storage; see Types::read's tag guard.
        if matches!(tag & 0x7f, 31 | 32 | 34 | 35 | 37..=39) {
            return Err(wire.malformed(format_args!(
                "type tag {} cannot encode a scalar range",
                tag & 0x7f
            )));
        }
        let storage = Storage::from_tag(tag & 0x7f, wire)?;
        let mut bound = || -> Result<Bound> {
            Ok(match storage {
                Storage::B2 | Storage::E8 => Bound::Integer(i64::from(wire.byte()?)),
                Storage::I32 | Storage::P32 => Bound::Integer(wire.sleb(32)?),
                Storage::I64 | Storage::P64 => Bound::Integer(wire.sleb(64)?),
                Storage::F64 => Bound::Real(wire.real_bits()?),
            })
        };
        Ok(Self {
            storage,
            downto: tag & 0x80 != 0,
            left: bound()?,
            right: bound()?,
        })
    }

    pub(super) fn integer_bounds(&self) -> Option<(i64, i64)> {
        match (self.left, self.right) {
            (Bound::Integer(left), Bound::Integer(right)) => Some((left, right)),
            _ => None,
        }
    }

    fn extent(&self, wire: &Wire) -> Result<u128> {
        let (left, right) = self
            .integer_bounds()
            .ok_or_else(|| wire.malformed("real array index range"))?;
        let distance = if self.downto {
            i128::from(left) - i128::from(right)
        } else {
            i128::from(right) - i128::from(left)
        };
        Ok(if distance < 0 {
            0
        } else {
            distance as u128 + 1
        })
    }
}

#[derive(Clone, Debug)]
pub(super) enum Shape {
    Scalar {
        storage: Storage,
        literals: Vec<usize>,
        _units: Vec<(usize, i64)>,
        wkt: u8,
    },
    Alias {
        base: usize,
        range: Option<Range>,
    },
    Array {
        element: usize,
        indices: Vec<usize>,
        bounds: Option<Vec<Range>>,
    },
    Record {
        fields: Vec<(usize, usize)>,
    },
}

#[derive(Clone, Debug)]
pub(super) struct Type {
    pub(super) name: usize,
    pub(super) base: Option<usize>,
    pub(super) shape: Shape,
    pub(super) scalars: Option<usize>,
}

pub(super) struct Types {
    pub(super) strings: Vec<String>,
    pub(super) nodes: Vec<Type>,
    source_ids: Vec<usize>,
}

fn vec_bytes<T>(capacity: usize) -> usize {
    capacity.saturating_mul(std::mem::size_of::<T>())
}

impl Types {
    pub(super) fn read(wire: &mut Wire, strings: Vec<String>) -> Result<Self> {
        wire.marker(b"TYP\0")?;
        wire.zeros()?;
        let count = wire.count("type")?;
        if count as u64 > wire.len.saturating_sub(wire.offset) / 2 {
            return Err(wire.malformed("type count exceeds remaining input"));
        }
        let mut types = Self {
            strings,
            nodes: Vec::new(),
            source_ids: Vec::new(),
        };
        for _ in 0..count {
            let tag = wire.byte()?;
            if !matches!(tag, 22 | 23 | 25..=29 | 31 | 32 | 34 | 35 | 37..=39) {
                return Err(wire.unsupported(format_args!("type tag {tag}")));
            }
            let name = types.string_id(wire)?;
            let node = match tag {
                22 | 23 | 25..=29 => {
                    let storage = Storage::from_tag(tag, wire)?;
                    let mut literals = Vec::new();
                    let mut units = Vec::new();
                    if matches!(storage, Storage::B2 | Storage::E8) {
                        let n = wire.uleb()?;
                        if n == 0 || n > 256 || (storage == Storage::B2 && n != 2) {
                            return Err(
                                wire.malformed("enum literal count does not fit its storage")
                            );
                        }
                        for _ in 0..n {
                            literals.push(types.string_id(wire)?);
                        }
                    } else if matches!(storage, Storage::P32 | Storage::P64) && wire.version == 1 {
                        let n = types.list_count(wire, "physical unit", 2)?;
                        for _ in 0..n {
                            units.push((types.string_id(wire)?, wire.sleb(64)?));
                        }
                    }
                    types.push(
                        name,
                        None,
                        Shape::Scalar {
                            storage,
                            literals,
                            _units: units,
                            wkt: 0,
                        },
                        wire,
                    )?
                }
                34 => {
                    let base = types.type_id(wire)?;
                    let range = Range::read(wire)?;
                    types.validate_range(base, &range, wire)?;
                    types.push(
                        name,
                        Some(base),
                        Shape::Alias {
                            base,
                            range: Some(range),
                        },
                        wire,
                    )?
                }
                31 => {
                    let element = types.type_id(wire)?;
                    let n = types.list_count(wire, "array dimension", 1)?;
                    if n == 0 {
                        return Err(wire.malformed("array without dimensions"));
                    }
                    let mut indices = Vec::new();
                    for _ in 0..n {
                        let index = types.type_id(wire)?;
                        match types.scalar(index).map(|s| s.0) {
                            Some(Storage::B2 | Storage::E8 | Storage::I32 | Storage::I64) => (),
                            _ => return Err(wire.malformed("non-discrete array index type")),
                        }
                        indices.push(index);
                    }
                    types.push(
                        name,
                        None,
                        Shape::Array {
                            element,
                            indices,
                            bounds: None,
                        },
                        wire,
                    )?
                }
                32 => {
                    let n = types.list_count(wire, "record field", 2)?;
                    let mut fields = Vec::new();
                    for _ in 0..n {
                        fields.push((types.string_id(wire)?, types.type_id(wire)?));
                    }
                    types.push(name, None, Shape::Record { fields }, wire)?
                }
                35 | 38 => {
                    let base = types.type_id(wire)?;
                    let resolved = types.effective(base);
                    let matches = matches!(
                        (&types.nodes[resolved].shape, tag),
                        (Shape::Array { .. }, 35) | (Shape::Record { .. }, 38)
                    );
                    if !matches {
                        return Err(wire.malformed("composite subtype base has wrong shape"));
                    }
                    let node = types.constrain(base, wire)?;
                    types.nodes[node].name = name;
                    node
                }
                37 | 39 => {
                    let base = types.type_id(wire)?;
                    let resolved = types.effective(base);
                    if !matches!(
                        (&types.nodes[resolved].shape, tag),
                        (Shape::Array { .. }, 37) | (Shape::Record { .. }, 39)
                    ) || types.nodes[base].scalars.is_some()
                    {
                        return Err(wire.malformed("unbounded alias base has wrong shape"));
                    }
                    types.push(name, Some(base), Shape::Alias { base, range: None }, wire)?
                }
                _ => return Err(wire.unsupported(format_args!("type tag {tag}"))),
            };
            types.source_ids.push(node);
        }
        if wire.byte()? != 0 {
            return Err(wire.malformed("missing type table terminator"));
        }
        Ok(types)
    }

    fn list_count(&self, wire: &mut Wire, context: &str, min_bytes: u64) -> Result<usize> {
        let count = wire.uleb()? as usize;
        if count as u64 > wire.len.saturating_sub(wire.offset) / min_bytes {
            return Err(wire.malformed(format_args!("{context} count exceeds remaining input")));
        }
        Ok(count)
    }

    pub(super) fn string_id(&self, wire: &mut Wire) -> Result<usize> {
        let id = wire.uleb()? as usize;
        if id >= self.strings.len() {
            return Err(wire.malformed("invalid string reference"));
        }
        Ok(id)
    }

    pub(super) fn type_id(&self, wire: &mut Wire) -> Result<usize> {
        let id = wire.uleb()? as usize;
        self.source_ids
            .get(id.wrapping_sub(1))
            .copied()
            .ok_or_else(|| wire.malformed("invalid or forward type reference"))
    }

    pub(super) fn effective(&self, mut id: usize) -> usize {
        while let Shape::Alias { base, .. } = &self.nodes[id].shape {
            id = *base;
        }
        id
    }

    /// Retained bytes of this table, for cache admission.
    ///
    /// Vector payloads are counted by capacity, because a retained graph keeps
    /// whatever the allocator reserved. Sizes saturate, so an absurd table is
    /// refused by the budget instead of wrapping.
    pub(super) fn retained_bytes(&self) -> usize {
        let mut bytes = std::mem::size_of::<Self>();
        bytes = bytes.saturating_add(vec_bytes::<String>(self.strings.capacity()));
        for string in &self.strings {
            bytes = bytes.saturating_add(string.capacity());
        }
        bytes = bytes.saturating_add(vec_bytes::<Type>(self.nodes.capacity()));
        for node in &self.nodes {
            match &node.shape {
                Shape::Scalar {
                    literals, _units, ..
                } => {
                    bytes = bytes.saturating_add(vec_bytes::<usize>(literals.capacity()));
                    bytes = bytes.saturating_add(vec_bytes::<(usize, i64)>(_units.capacity()));
                }
                Shape::Alias { .. } => {}
                Shape::Array {
                    indices, bounds, ..
                } => {
                    bytes = bytes.saturating_add(vec_bytes::<usize>(indices.capacity()));
                    if let Some(bounds) = bounds {
                        bytes = bytes.saturating_add(vec_bytes::<Range>(bounds.capacity()));
                    }
                }
                Shape::Record { fields } => {
                    bytes = bytes.saturating_add(vec_bytes::<(usize, usize)>(fields.capacity()));
                }
            }
        }
        bytes = bytes.saturating_add(vec_bytes::<usize>(self.source_ids.capacity()));
        bytes
    }

    pub(super) fn scalar(&self, id: usize) -> Option<(Storage, &[usize], u8)> {
        match &self.nodes[self.effective(id)].shape {
            Shape::Scalar {
                storage,
                literals,
                wkt,
                ..
            } => Some((*storage, literals, *wkt)),
            _ => None,
        }
    }

    pub(super) fn name(&self, mut id: usize) -> Option<&str> {
        loop {
            let node = &self.nodes[id];
            if node.name != 0 {
                return Some(&self.strings[node.name]);
            }
            id = node.base?;
        }
    }

    fn validate_range(&self, base: usize, range: &Range, wire: &Wire) -> Result<()> {
        let (storage, literals, _) = self
            .scalar(base)
            .ok_or_else(|| wire.malformed("range base is not scalar"))?;
        if storage != range.storage {
            return Err(wire.malformed("range storage differs from base type"));
        }
        if matches!(storage, Storage::B2 | Storage::E8) {
            let (left, right) = range
                .integer_bounds()
                .ok_or_else(|| wire.malformed("non-integral enum range"))?;
            if left < 0
                || right < 0
                || left as usize >= literals.len()
                || right as usize >= literals.len()
            {
                return Err(wire.malformed("enum range endpoint exceeds base literals"));
            }
        }
        Ok(())
    }

    fn push(
        &mut self,
        name: usize,
        base: Option<usize>,
        shape: Shape,
        wire: &Wire,
    ) -> Result<usize> {
        let scalars = match &shape {
            Shape::Scalar { .. } => Some(1),
            Shape::Alias { base, .. } => self.nodes[*base].scalars,
            Shape::Array { bounds: None, .. } => None,
            Shape::Array {
                element,
                bounds: Some(bounds),
                ..
            } => {
                let extents = bounds
                    .iter()
                    .map(|r| r.extent(wire))
                    .collect::<Result<Vec<_>>>()?;
                if extents.contains(&0) {
                    Some(0)
                } else if let Some(n) = self.nodes[*element].scalars {
                    let total = extents
                        .into_iter()
                        .try_fold(n as u128, |total, extent| total.checked_mul(extent))
                        .and_then(|n| usize::try_from(n).ok())
                        .ok_or_else(|| wire.malformed("array scalar count overflow"))?;
                    Some(total)
                } else {
                    None
                }
            }
            Shape::Record { fields } => {
                let mut count = Some(0usize);
                for (_, field) in fields {
                    count = match (count, self.nodes[*field].scalars) {
                        (Some(a), Some(b)) => Some(
                            a.checked_add(b)
                                .ok_or_else(|| wire.malformed("record scalar count overflow"))?,
                        ),
                        _ => None,
                    };
                }
                count
            }
        };
        let id = self.nodes.len();
        self.nodes.push(Type {
            name,
            base,
            shape,
            scalars,
        });
        Ok(id)
    }

    /// Consume nested constraints with a work stack, rather than Rust recursion.
    fn constrain(&mut self, base: usize, wire: &mut Wire) -> Result<usize> {
        enum Frame {
            Start(usize),
            Array {
                base: usize,
                indices: Vec<usize>,
                bounds: Vec<Range>,
            },
            Record {
                base: usize,
                fields: Vec<(usize, usize)>,
                next: usize,
            },
        }
        let mut work = vec![Frame::Start(base)];
        let mut result = None;
        while let Some(frame) = work.pop() {
            match frame {
                Frame::Start(base) => match self.nodes[self.effective(base)].shape.clone() {
                    Shape::Array {
                        element, indices, ..
                    } => {
                        let mut bounds = Vec::new();
                        for &index in &indices {
                            let range = Range::read(wire)?;
                            self.validate_range(index, &range, wire)?;
                            bounds.push(range);
                        }
                        if self.nodes[element].scalars.is_some() {
                            result = Some(self.push(
                                0,
                                Some(base),
                                Shape::Array {
                                    element,
                                    indices,
                                    bounds: Some(bounds),
                                },
                                wire,
                            )?);
                        } else {
                            work.push(Frame::Array {
                                base,
                                indices,
                                bounds,
                            });
                            work.push(Frame::Start(element));
                        }
                    }
                    Shape::Record { fields } => work.push(Frame::Record {
                        base,
                        fields,
                        next: 0,
                    }),
                    _ => return Err(wire.malformed("composite bounds have non-composite base")),
                },
                Frame::Array {
                    base,
                    indices,
                    bounds,
                } => {
                    let element = result
                        .take()
                        .ok_or_else(|| wire.malformed("missing nested array constraints"))?;
                    result = Some(self.push(
                        0,
                        Some(base),
                        Shape::Array {
                            element,
                            indices,
                            bounds: Some(bounds),
                        },
                        wire,
                    )?);
                }
                Frame::Record {
                    base,
                    mut fields,
                    mut next,
                } => {
                    if next != 0
                        && let Some(child) = result.take()
                    {
                        fields[next - 1].1 = child;
                    }
                    while next < fields.len() && self.nodes[fields[next].1].scalars.is_some() {
                        next += 1;
                    }
                    if next == fields.len() {
                        result = Some(self.push(0, Some(base), Shape::Record { fields }, wire)?);
                    } else {
                        let child = fields[next].1;
                        work.push(Frame::Record {
                            base,
                            fields,
                            next: next + 1,
                        });
                        work.push(Frame::Start(child));
                    }
                }
            }
        }
        result.ok_or_else(|| wire.malformed("missing composite constraints"))
    }

    pub(super) fn wkt(&mut self, wire: &mut Wire) -> Result<()> {
        wire.zeros()?;
        loop {
            let marker = wire.byte()?;
            if marker == 0 {
                return Ok(());
            }
            if marker > 3 {
                return Err(wire.unsupported(format_args!("well-known type marker {marker}")));
            }
            let id = self.type_id(wire)?;
            let node = &mut self.nodes[id];
            let Shape::Scalar {
                storage,
                literals,
                wkt,
                ..
            } = &mut node.shape
            else {
                return Err(wire.malformed("well-known marker on non-enum type"));
            };
            let expected: &[&str] = match marker {
                1 => &["false", "true"],
                2 => &["'0'", "'1'"],
                3 => &[
                    "'U'", "'X'", "'0'", "'1'", "'Z'", "'W'", "'L'", "'H'", "'-'",
                ],
                _ => return Err(wire.unsupported(format_args!("well-known type marker {marker}"))),
            };
            if *storage
                != if marker == 3 {
                    Storage::E8
                } else {
                    Storage::B2
                }
                || literals
                    .iter()
                    .map(|&i| self.strings[i].as_str())
                    .ne(expected.iter().copied())
                || (*wkt != 0 && *wkt != marker)
            {
                return Err(wire.malformed("well-known marker contradicts enum storage/literals"));
            }
            *wkt = marker;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufReader, Cursor};

    fn parse(entries: &[u8], count: u32) -> (Wire, Types) {
        let mut bytes = b"TYP\0\0\0\0\0".to_vec();
        bytes.extend(count.to_le_bytes());
        bytes.extend(entries);
        bytes.push(0);
        let mut wire =
            Wire::new(Box::new(BufReader::with_capacity(1, Cursor::new(bytes)))).unwrap();
        let types = Types::read(
            &mut wire,
            vec!["".into(), "integer".into(), "vector".into(), "field".into()],
        )
        .unwrap();
        (wire, types)
    }

    #[test]
    fn nested_array_constraints_and_following_entry() {
        // integer, unconstrained vector, unbounded alias, outer array of alias,
        // outer(0 to 0)(0 downto 0), then an unrelated physical32 type.
        let entries = [
            25, 1, 31, 2, 1, 1, 1, 37, 2, 2, 31, 2, 3, 1, 1, 35, 0, 4, 25, 0, 0, 153, 0, 0, 28, 1,
        ];
        let (_, types) = parse(&entries, 6);
        let node = &types.nodes[types.source_ids[4]];
        assert_eq!(node.scalars, Some(1));
        assert_eq!(types.name(types.source_ids[4]), Some("vector"));
        assert_eq!(types.scalar(types.source_ids[5]).unwrap().0, Storage::P32);
        let Shape::Array { element, .. } = node.shape else {
            panic!("array");
        };
        assert_eq!(types.nodes[element].scalars, Some(1));
    }

    #[test]
    fn unbounded_record_alias_and_named_bounded_record() {
        let entries = [
            25, 1, 31, 2, 1, 1, 1, 32, 3, 1, 3, 2, 39, 3, 3, 38, 3, 4, 153, 2, 0, 38, 0, 5,
        ];
        let (_, types) = parse(&entries, 6);
        assert_eq!(types.nodes[types.source_ids[2]].scalars, None);
        assert_eq!(types.nodes[types.source_ids[4]].scalars, Some(3));
        assert_eq!(types.nodes[types.source_ids[5]].scalars, Some(3));
        assert_eq!(types.name(types.source_ids[5]), Some("field"));
    }

    #[test]
    fn multidimensional_null_range_does_not_become_absolute_width() {
        let entries = [25, 1, 31, 2, 1, 2, 1, 1, 35, 0, 2, 25, 0, 2, 153, 0, 1];
        let (_, types) = parse(&entries, 3);
        assert_eq!(types.nodes[types.source_ids[2]].scalars, Some(0));
        assert_eq!(Storage::I64.tag(), 26);
    }

    #[test]
    fn physical_versions_and_real_constraints() {
        let (_, types) = parse(&[28, 1, 29, 1, 27, 1], 3);
        assert!(
            matches!(&types.nodes[0].shape, Shape::Scalar { _units: units, .. } if units.is_empty())
        );
        let mut bytes = b"TYP\0\0\0\0\0\x01\0\0\0\x1c\x01\x01\x03\x7e\0".to_vec();
        let mut wire = Wire::new(Box::new(Cursor::new(bytes.clone()))).unwrap();
        wire.version = 1;
        let types = Types::read(
            &mut wire,
            vec!["".into(), "physical".into(), "".into(), "unit".into()],
        )
        .unwrap();
        assert!(
            matches!(&types.nodes[0].shape, Shape::Scalar { _units: units, .. } if units == &[(3, -2)])
        );
        bytes = vec![27];
        bytes.extend(0x8000000000000000u64.to_le_bytes());
        bytes.extend(0x3ff0000000000000u64.to_le_bytes());
        let mut wire = Wire::new(Box::new(Cursor::new(bytes))).unwrap();
        let range = Range::read(&mut wire).unwrap();
        assert_eq!(range.left, Bound::Real(0x8000000000000000));
        assert_eq!(range.integer_bounds(), None);
    }

    #[test]
    fn enum_constraints_preserve_base_ordinals_and_markers() {
        let (_, mut types) = parse(&[23, 2, 3, 1, 2, 3, 34, 0, 1, 23, 1, 2], 2);
        assert_eq!(types.scalar(types.source_ids[1]).unwrap().1, [1, 2, 3]);
        assert!(matches!(
            &types.nodes[1].shape,
            Shape::Alias {
                range: Some(Range {
                    left: Bound::Integer(1),
                    ..
                }),
                ..
            }
        ));
        let mut wire = Wire::new(Box::new(Cursor::new(vec![0, 0, 0, 0, 3, 1, 0]))).unwrap();
        assert!(types.wkt(&mut wire).is_err());
    }

    #[test]
    fn known_type_entries_are_invalid_ranges_and_unknown_storage_stays_unsupported() {
        for tag in [31, 32, 34, 35, 37, 38, 39] {
            let mut wire = Wire::new(Box::new(Cursor::new(vec![tag]))).unwrap();
            assert!(matches!(
                Range::read(&mut wire),
                Err(crate::Error::Malformed { .. })
            ));
            assert_eq!(wire.offset, 1);
        }
        let mut wire = Wire::new(Box::new(Cursor::new(vec![63]))).unwrap();
        assert!(matches!(
            Range::read(&mut wire),
            Err(crate::Error::UnsupportedFeature { .. })
        ));
    }

    #[test]
    fn invalid_and_unknown_type_forms_do_not_panic() {
        for entries in [
            &[31, 0, 0, 1, 1][..],
            &[34, 0, 1, 25, 0, 0],
            &[25, 1, 34, 0, 1, 23, 0, 1],
        ] {
            let mut bytes = b"TYP\0\0\0\0\0\x02\0\0\0".to_vec();
            bytes.extend(entries);
            bytes.push(0);
            let mut wire = Wire::new(Box::new(Cursor::new(bytes))).unwrap();
            assert!(Types::read(&mut wire, vec!["".into(), "name".into()]).is_err());
        }
    }

    #[test]
    fn deep_composite_constraints_use_an_explicit_stack() {
        fn unsigned(mut value: u32, bytes: &mut Vec<u8>) {
            loop {
                let mut digit = (value & 127) as u8;
                value >>= 7;
                if value != 0 {
                    digit |= 128;
                }
                bytes.push(digit);
                if value == 0 {
                    break;
                }
            }
        }
        let depth = 2048;
        let mut bytes = b"TYP\0\0\0\0\0".to_vec();
        bytes.extend((depth + 2u32).to_le_bytes());
        bytes.extend([25, 1]);
        for index in 0..depth {
            bytes.extend([31, 0]);
            unsigned(index + 1, &mut bytes);
            bytes.extend([1, 1]);
        }
        bytes.extend([35, 0]);
        unsigned(depth + 1, &mut bytes);
        for _ in 0..depth {
            bytes.extend([25, 0, 0]);
        }
        bytes.push(0);
        let mut wire =
            Wire::new(Box::new(BufReader::with_capacity(2, Cursor::new(bytes)))).unwrap();
        let types = Types::read(&mut wire, vec!["".into(), "integer".into()]).unwrap();
        let last = *types.source_ids.last().unwrap();
        assert_eq!(types.nodes[last].scalars, Some(1));
        assert_eq!(types.nodes.len(), depth as usize * 2 + 1);
    }

    #[test]
    #[ignore = "requires the independently installed GHW diagnostic fixtures"]
    fn source_headers_match_the_supported_grammar() {
        use std::fs::File;
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/ghw");
        let names = [
            "ghw0000-bcd-counter-debug",
            "ghw0001-wellen-ghw-bug",
            "ghw0003-wellen-issue-32",
            "ghw0004-wellen-issue-34",
            "ghw0005-wellen-issue-35",
            "ghw0006-wellen-issue-6",
            "ghw0093-wellen-issue-90",
            "ghw0094-surfer-issue-547",
        ];
        for name in names {
            let mut wire = Wire::new(Box::new(BufReader::new(
                File::open(root.join(name).join("waveform.ghw")).unwrap(),
            )))
            .unwrap();
            wire.header().unwrap();
            let strings = wire.strings().unwrap();
            let mut types =
                Types::read(&mut wire, strings).unwrap_or_else(|e| panic!("{name}: {e}"));
            let mut section = wire.fixed::<4>().unwrap();
            if &section == b"WKT\0" {
                types.wkt(&mut wire).unwrap();
                section = wire.fixed().unwrap();
            }
            assert_eq!(&section, b"HIE\0", "{name}");
            assert!(!types.source_ids.is_empty());
            eprintln!(
                "{name}: {} source types, {} layouts",
                types.source_ids.len(),
                types.nodes.len()
            );
        }
    }
}