layline_core/segment.rs
1//! Segment tables for messages.
2use crate::field::FieldDef;
3use crate::row::row;
4
5/// Where a segment starts.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7#[non_exhaustive]
8pub enum Start<'a> {
9 /// At this bit of the body, known before decoding.
10 At(u64),
11 /// A fixed number of bits after a segment whose size is read from the wire.
12 After {
13 /// The closest earlier segment whose size is read from the wire.
14 segment: &'a str,
15 /// Bits between the end of `segment` and this segment.
16 bits: u64,
17 },
18 /// At a byte offset read from an earlier field, counted from the start of the body.
19 Seek {
20 /// The field holding the offset.
21 by: &'a str,
22 },
23}
24
25impl Start<'_> {
26 /// The bit position, if the start is [`Start::At`].
27 #[must_use]
28 pub const fn bit(self) -> Option<u64> {
29 match self {
30 Start::At(bit) => Some(bit),
31 _ => None,
32 }
33 }
34}
35
36/// A field a size is read from, with a scale and offset applied.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct By<'a> {
39 /// The field holding the number.
40 pub field: &'a str,
41 /// Multiplier.
42 pub scale: u32,
43 /// Added after scaling.
44 pub offset: i32,
45}
46
47impl<'a> By<'a> {
48 /// The field's value, unscaled.
49 #[must_use]
50 pub const fn field(field: &'a str) -> Self {
51 Self { field, scale: 1, offset: 0 }
52 }
53}
54
55/// What selects a switch arm.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57#[non_exhaustive]
58pub enum Discriminant<'a> {
59 /// An earlier field's value.
60 Field(&'a str),
61 /// The number of bytes given to the switch.
62 BodyLength,
63}
64
65/// How wide a segment is.
66///
67/// Whether it is present at all is [`SegmentDef::when`].
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum Span<'a> {
71 /// Elements up to and including the first whose first byte has `mask` set.
72 ///
73 /// Encode sets `mask` on the last element.
74 Terminated {
75 /// The bits set on the last element and clear on the others.
76 mask: u8,
77 },
78 /// Exactly this many bits, known before decoding.
79 Fixed(u64),
80 /// As many elements as a field's value.
81 Counted {
82 /// The count field.
83 by: By<'a>,
84 /// One element's width in bits, or `None` if elements are self-delimiting.
85 each: Option<u64>,
86 },
87 /// A field's value squared, as for a square matrix.
88 Squared {
89 /// The matrix order, squared after scaling.
90 by: By<'a>,
91 /// One element's width in bits, or `None` if elements are self-delimiting.
92 each: Option<u64>,
93 },
94 /// Element count from one field, and bytes per element from another.
95 Strided {
96 /// The count field.
97 by: By<'a>,
98 /// Bytes per element.
99 stride: By<'a>,
100 },
101 /// As many whole elements as fit in a byte length.
102 Window {
103 /// The length, in bytes.
104 by: By<'a>,
105 },
106 /// The value reports its own width, as a `VarCodec` or nested message does.
107 SelfDelimiting,
108 /// Bytes up to and including the first byte equal to `terminator`.
109 Until {
110 /// The end byte.
111 terminator: u8,
112 },
113 /// As many whole elements as the body has left. An element wider than `cap` bits is refused.
114 Fill {
115 /// The cap, if one was declared.
116 cap: Option<u64>,
117 },
118 /// The selected arm sets both the content and the size.
119 Chosen {
120 /// What selects the arm.
121 on: Discriminant<'a>,
122 },
123 /// A C-style union: the arm sets the content, and the size is fixed.
124 ///
125 /// Each arm gets exactly `bits` bits and may not read past them.
126 ChosenIn {
127 /// What selects the arm.
128 on: Discriminant<'a>,
129 /// The size, in bits.
130 bits: u64,
131 },
132 /// Zero bytes after the row before, up to the next multiple of `align` bytes counted from
133 /// that row's start: padding that its length does not count.
134 ///
135 /// The row is named after the padded row, with `.pad` appended. Decode skips the bytes
136 /// without reading them, and encode writes zeros.
137 Pad {
138 /// The multiple, in bytes.
139 align: u64,
140 },
141 /// Tag-length-value: the arm sets the content, and an earlier field sets the size.
142 ///
143 /// The arm must fill the size. Decode advances by the size whichever arm is chosen.
144 ChosenWithin {
145 /// What selects the arm.
146 on: Discriminant<'a>,
147 /// The size, in bytes.
148 by: By<'a>,
149 },
150}
151
152impl Span<'_> {
153 /// The width in bits, if the table fixes it.
154 #[must_use]
155 pub const fn bits(self) -> Option<u64> {
156 match self {
157 Span::Fixed(bits) | Span::ChosenIn { bits, .. } => Some(bits),
158 _ => None,
159 }
160 }
161}
162
163/// Whether a segment is present on the wire.
164///
165/// A row whose `when` is `None` is always present.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
167#[non_exhaustive]
168pub enum Presence<'a> {
169 /// Present when `field & mask != 0`.
170 Flag {
171 /// The flag field.
172 field: &'a str,
173 /// The bits that mark presence.
174 mask: u64,
175 },
176 /// Present when `field & mask == 0`: the bits mark absence.
177 Clear {
178 /// The flag field.
179 field: &'a str,
180 /// The bits that mark absence.
181 mask: u64,
182 },
183 /// Present when this row's [offset](Start::Seek) is non-zero.
184 Offset,
185 /// Present when the bit just before it is set.
186 ///
187 /// That bit belongs to no field. Encode writes it from `is_some`.
188 Bit,
189 /// Present when the body has bytes left. Must be the last row.
190 Remaining,
191 /// Present when its byte length is non-zero.
192 Length {
193 /// The byte length field.
194 by: &'a str,
195 },
196}
197
198row! {
199 /// One row of a message's segment table.
200 SegmentDef<'a> {
201 /// The field's name, or the name of a generated block of fields.
202 name: &'a str,
203 /// Where it starts.
204 start: Start<'a>,
205 /// How wide it is when present.
206 span: Span<'a>,
207 /// What makes it present, or `None` if it always is.
208 when: Option<Presence<'a>>,
209 /// The type that decodes this row. A type may name itself.
210 decoded_by: Option<&'a str>,
211 /// A block's fields, with offsets relative to [`start`](Self::start).
212 fields: &'a [FieldDef<'a>],
213 }
214}
215
216impl SegmentDef<'_> {
217 /// The bits this row occupies, if the table alone decides it.
218 ///
219 /// `None` for a row with a [`when`](Self::when).
220 #[must_use]
221 pub const fn extent(&self) -> Option<u64> {
222 if self.when.is_some() { None } else { self.span.bits() }
223 }
224
225 /// Whether this row's position and width are both known before decoding.
226 #[must_use]
227 pub const fn is_fixed(&self) -> bool {
228 matches!(self.start, Start::At(_)) && self.extent().is_some()
229 }
230}
231
232/// One end of a checksum's byte range.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
234#[non_exhaustive]
235pub enum CoverEdge<'a> {
236 /// The start of the body. Inside a [`Choice`], the start of the arm's body.
237 Start,
238 /// The first bit of the named row.
239 Before(&'a str),
240 /// The bit after the named row.
241 After(&'a str),
242}
243
244row! {
245 /// The bytes one checksum field covers.
246 CoverDef<'a> {
247 /// The checksum field's name.
248 field: &'a str,
249 /// Where the range starts.
250 from: CoverEdge<'a>,
251 /// Where it ends.
252 to: CoverEdge<'a>,
253 /// Whether the checksum field's own bytes are left out. True when the range includes them.
254 excludes_self: bool,
255 }
256}
257
258row! {
259 /// One arm of a catalogue: a discriminant value and the body it selects.
260 ArmDef<'a> {
261 /// The variant's name.
262 name: &'a str,
263 /// The discriminant value, or `None` for the `#[other]` arm.
264 value: Option<i64>,
265 /// The arm's segment table, counted from the arm's first bit.
266 segments: &'a [SegmentDef<'a>],
267 }
268}
269
270/// The bit up to which every row's position is known before decoding.
271///
272/// Zero if the first row's width is read from the wire. The full width if no row's is.
273///
274/// ```
275/// use layline_core::table::fixed_bits;
276/// use layline_core::table::{By, SegmentDef, Span, Start};
277///
278/// const T: &[SegmentDef<'_>] = &[
279/// SegmentDef::new("__PacketBlock0", Start::At(0), Span::Fixed(64), None, None, &[]),
280/// SegmentDef::new(
281/// "items",
282/// Start::At(64),
283/// Span::Counted { by: By::field("count"), each: Some(32) },
284/// None,
285/// Some("Item"),
286/// &[],
287/// ),
288/// ];
289/// const _: () = assert!(fixed_bits(T) == 64);
290/// ```
291#[must_use]
292pub const fn fixed_bits(segments: &[SegmentDef<'_>]) -> u64 {
293 let mut at = 0;
294 let mut i = 0;
295 while i < segments.len() {
296 match (segments[i].start, segments[i].extent()) {
297 (Start::At(start), Some(bits)) => at = start + bits,
298 (Start::At(start), None) => return start,
299 _ => return at,
300 }
301 i += 1;
302 }
303 at
304}
305
306/// Whether every arm is exactly `bits` wide, as [`Span::ChosenIn`] requires.
307///
308/// Only arms whose width the table fixes are checked. A [`Fill`](Span::Fill) arm passes if it
309/// fits. An arm whose width is read from the wire is checked during decode.
310#[must_use]
311pub const fn arms_fit(arms: &[ArmDef<'_>], bits: u64) -> bool {
312 let mut i = 0;
313 while i < arms.len() {
314 if !arm_fits(arms[i].segments, bits) {
315 return false;
316 }
317 i += 1;
318 }
319 true
320}
321
322const fn arm_fits(rows: &[SegmentDef<'_>], bits: u64) -> bool {
323 let mut at = 0;
324 let mut i = 0;
325 while i < rows.len() {
326 let start = match rows[i].start {
327 Start::At(start) => start,
328 _ => return true,
329 };
330 if rows[i].when.is_some() {
331 // An optional row: the table cannot fix the arm's width.
332 return true;
333 }
334 if matches!(rows[i].span, Span::Fill { .. }) {
335 return start <= bits;
336 }
337 match rows[i].span.bits() {
338 Some(width) => at = start + width,
339 None => return true,
340 }
341 i += 1;
342 }
343 at == bits
344}
345
346/// A variable-length type, described by a segment table.
347///
348/// `decode` and `encode` are trait methods, so `use layline::Message;` imports them with the derive.
349/// [`decode`](Self::decode) and [`encode`](Self::encode) need `Ctx = ()`. A
350/// `#[message(needs(..))]` type uses the `_with` methods.
351#[diagnostic::on_unimplemented(
352 message = "`{Self}` is not a message",
353 label = "not a `#[derive(Message)]` type",
354 note = "`#[message]` fields and enum variants without `#[bytes(N)]` need a `#[derive(Message)]` type. \
355 Use `#[bytes(N)]` for a `Layout`, and `#[with(..)]` for a `#[message(needs(..))]` type"
356)]
357pub trait Message: Sized {
358 /// The type's name, as printed in the audit.
359 const NAME: &'static str;
360
361 /// Values the containing message passes in, or `()` if there are none.
362 ///
363 /// The derive generates a `<Name>Ctx` struct with one field per `#[message(needs(..))]` parameter.
364 type Ctx;
365
366 /// The segment table, in wire order.
367 const SEGMENTS: &'static [crate::table::SegmentDef<'static>];
368
369 /// The parameters, in declaration order.
370 const PARAMS: &'static [crate::table::ParamDef<'static>] = &[];
371
372 /// The bytes each `#[checksum]` field covers, in wire order.
373 const COVERED: &'static [crate::table::CoverDef<'static>] = &[];
374
375 /// Whether decode consumes all the bytes it is given. Read by the parent, since a derive cannot see it.
376 #[doc(hidden)]
377 const OPEN_ENDED: bool = false;
378
379 /// Decode from the start of `bytes`. Returns the value and the bytes consumed.
380 ///
381 /// # Errors
382 ///
383 /// A short body, a malformed count, a wrong checksum, a missing magic, or nesting past
384 /// [`MAX_NESTING_DEPTH`](crate::MAX_NESTING_DEPTH).
385 fn decode_with(bytes: &[u8], ctx: Self::Ctx) -> Result<(Self, usize), crate::ParseError> {
386 Self::decode_with_nested(bytes, 0, ctx)
387 }
388
389 /// [`decode_with`](Self::decode_with) at nesting depth `depth`.
390 ///
391 /// # Errors
392 ///
393 /// As [`decode_with`](Self::decode_with), plus [`TooDeep`](crate::ParseError::TooDeep).
394 #[doc(hidden)]
395 fn decode_with_nested(
396 bytes: &[u8],
397 depth: u32,
398 ctx: Self::Ctx,
399 ) -> Result<(Self, usize), crate::ParseError>;
400
401 /// Append the wire bytes to `out`.
402 ///
403 /// Encode computes counts, lengths, offsets, flags and discriminants from the value.
404 /// Parameters belong to the containing message and are not written.
405 ///
406 /// # Errors
407 ///
408 /// [`Overflow`](crate::Overflow), leaving the bytes already written in place.
409 fn encode_into_with<B: crate::Buffer>(
410 &self,
411 out: &mut B,
412 ctx: Self::Ctx,
413 ) -> Result<(), crate::Overflow>;
414
415 /// [`encode_into_with`](Self::encode_into_with) for a message with no parameters.
416 ///
417 /// # Errors
418 ///
419 /// As [`encode_into_with`](Self::encode_into_with).
420 fn encode_into<B: crate::Buffer>(&self, out: &mut B) -> Result<(), crate::Overflow>
421 where
422 Self: Message<Ctx = ()>,
423 {
424 self.encode_into_with(out, ())
425 }
426
427 /// [`encode_into_with`](Self::encode_into_with) into a new vector.
428 #[cfg(feature = "alloc")]
429 #[must_use]
430 fn encode_with(&self, ctx: Self::Ctx) -> crate::__private::Vec<u8> {
431 crate::buffer::to_vec(|out| self.encode_into_with(out, ctx))
432 }
433
434 /// [`decode_with`](Self::decode_with) for a message with no parameters.
435 ///
436 /// # Errors
437 ///
438 /// As [`decode_with`](Self::decode_with).
439 fn decode(bytes: &[u8]) -> Result<(Self, usize), crate::ParseError>
440 where
441 Self: Message<Ctx = ()>,
442 {
443 Self::decode_with(bytes, ())
444 }
445
446 /// [`encode_with`](Self::encode_with) for a message with no parameters.
447 #[cfg(feature = "alloc")]
448 #[must_use]
449 fn encode(&self) -> crate::__private::Vec<u8>
450 where
451 Self: Message<Ctx = ()>,
452 {
453 self.encode_with(())
454 }
455
456 /// The audit records for this message.
457 fn audit() -> crate::audit::MessageRecords<'static> {
458 crate::audit::message(Self::NAME, Self::SEGMENTS)
459 .covering(Self::COVERED)
460 .params(Self::PARAMS)
461 }
462}
463
464/// A variable-length type whose fields borrow the bytes it decodes from.
465///
466/// `#[derive(Message)]` implements it, instead of [`Message`], on a struct with a lifetime:
467/// `&'a [u8]` and `&'a [u8; N]` fields are views of the input, so decode needs no allocator. It
468/// has no parameters, and no other message can hold it, since [`Message`] decodes from bytes it
469/// does not keep.
470#[diagnostic::on_unimplemented(
471 message = "`{Self}` is not a borrowing message",
472 label = "not a `#[derive(Message)]` struct with a lifetime"
473)]
474pub trait MessageRef<'a>: Sized {
475 /// The type's name, as printed in the audit.
476 const NAME: &'static str;
477
478 /// The segment table, in wire order.
479 const SEGMENTS: &'static [crate::table::SegmentDef<'static>];
480
481 /// The bytes each `#[checksum]` field covers, in wire order.
482 const COVERED: &'static [crate::table::CoverDef<'static>] = &[];
483
484 /// Decode from the start of `bytes`, borrowing from them. Returns the value and the bytes
485 /// consumed.
486 ///
487 /// # Errors
488 ///
489 /// As [`Message::decode_with`].
490 fn decode(bytes: &'a [u8]) -> Result<(Self, usize), crate::ParseError>;
491
492 /// Append the wire bytes to `out`.
493 ///
494 /// # Errors
495 ///
496 /// [`Overflow`](crate::Overflow), leaving the bytes already written in place.
497 fn encode_into<B: crate::Buffer>(&self, out: &mut B) -> Result<(), crate::Overflow>;
498
499 /// [`encode_into`](Self::encode_into) into a new vector.
500 #[cfg(feature = "alloc")]
501 #[must_use]
502 fn encode(&self) -> crate::__private::Vec<u8> {
503 crate::buffer::to_vec(|out| self.encode_into(out))
504 }
505
506 /// The audit records for this message.
507 fn audit() -> crate::audit::MessageRecords<'static> {
508 crate::audit::message(Self::NAME, Self::SEGMENTS).covering(Self::COVERED)
509 }
510}
511
512/// The arms of a `#[switch]` field. `#[derive(Message)]` on an enum implements it.
513#[diagnostic::on_unimplemented(
514 message = "`{Self}` is not a catalogue",
515 label = "not a `#[derive(Message)]` enum",
516 note = "`#[switch(..)]` needs a `#[derive(Message)]` enum. \
517 Give each variant `#[value(N)]`, or `#[other]` for the last"
518)]
519pub trait Choice: Sized {
520 /// The type's name, as printed in the audit.
521 const NAME: &'static str;
522
523 /// The arms, in declaration order, with the `#[other]` arm last.
524 const ARMS: &'static [crate::table::ArmDef<'static>];
525
526 /// The bytes each arm's `#[checksum]` fields cover.
527 const COVERED: &'static [crate::table::ArmCover<'static>] = &[];
528
529 /// Whether the chosen arm can consume all the bytes it is given.
530 #[doc(hidden)]
531 const OPEN_ENDED: bool = false;
532
533 /// Decode the arm `discriminant` selects. Returns the value and the bytes consumed.
534 ///
535 /// # Errors
536 ///
537 /// Any error from the arm, or [`Malformed`](crate::ParseError::Malformed) for an unlisted
538 /// discriminant when there is no `#[other]` arm.
539 fn decode_with(discriminant: i64, bytes: &[u8]) -> Result<(Self, usize), crate::ParseError> {
540 Self::decode_with_nested(discriminant, bytes, 0)
541 }
542
543 /// [`decode_with`](Self::decode_with) at nesting depth `depth`.
544 ///
545 /// # Errors
546 ///
547 /// As [`decode_with`](Self::decode_with).
548 #[doc(hidden)]
549 fn decode_with_nested(
550 discriminant: i64,
551 bytes: &[u8],
552 depth: u32,
553 ) -> Result<(Self, usize), crate::ParseError>;
554
555 /// This arm's discriminant, or `None` for the `#[other]` arm. Encode writes it into the parent.
556 #[doc(hidden)]
557 fn discriminant(&self) -> Option<i64>;
558
559 /// Whether a listed arm has `discriminant`.
560 #[doc(hidden)]
561 #[must_use]
562 fn defines(discriminant: i64) -> bool {
563 Self::ARMS.iter().any(|arm| arm.value == Some(discriminant))
564 }
565
566 /// Append the arm's body to `out`.
567 ///
568 /// # Errors
569 ///
570 /// [`Overflow`](crate::Overflow), leaving the bytes already written in place.
571 fn encode_into<B: crate::Buffer>(&self, out: &mut B) -> Result<(), crate::Overflow>;
572
573 /// [`encode_into`](Self::encode_into) into a new vector.
574 #[cfg(feature = "alloc")]
575 #[must_use]
576 fn encode(&self) -> crate::__private::Vec<u8> {
577 crate::buffer::to_vec(|out| self.encode_into(out))
578 }
579
580 /// The audit records for every arm.
581 fn audit() -> crate::audit::ChoiceRecords<'static> {
582 crate::audit::choice(Self::NAME, Self::ARMS).covering(Self::COVERED)
583 }
584}
585
586row! {
587 /// The [`CoverDef`] rows of one arm.
588 ArmCover<'a> {
589 /// The variant's name, as in [`ArmDef::name`].
590 arm: &'a str,
591 /// The bytes the arm's checksums cover.
592 covered: &'a [CoverDef<'a>],
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use crate::Extent;
600
601 const FIELDS: &[FieldDef<'_>] =
602 &[FieldDef::new("magic", Extent::new(0, 32)), FieldDef::new("count", Extent::new(32, 16))];
603
604 const BLOCK: SegmentDef<'_> =
605 SegmentDef::new("__PacketBlock0", Start::At(0), Span::Fixed(48), None, None, FIELDS);
606
607 #[test]
608 fn a_table_of_solved_runs_is_solved_throughout() {
609 const T: &[SegmentDef<'_>] = &[BLOCK];
610 assert_eq!(fixed_bits(T), 48);
611 assert!(T[0].is_fixed());
612 }
613
614 #[test]
615 fn solving_stops_at_the_first_joint_and_reports_its_position() {
616 const T: &[SegmentDef<'_>] = &[
617 BLOCK,
618 SegmentDef::new(
619 "items",
620 Start::At(48),
621 Span::Counted { by: By::field("count"), each: Some(32) },
622 None,
623 Some("Item"),
624 &[],
625 ),
626 SegmentDef::new(
627 "crc",
628 Start::After { segment: "items", bits: 0 },
629 Span::Fixed(16),
630 None,
631 None,
632 &[],
633 ),
634 ];
635 assert_eq!(fixed_bits(T), 48);
636 assert!(!T[1].is_fixed());
637 assert!(!T[2].is_fixed(), "a row after a variable one has no known position");
638 assert_eq!(T[2].start.bit(), None);
639 }
640
641 #[test]
642 fn a_table_that_begins_with_a_joint_is_solved_to_nothing() {
643 const T: &[SegmentDef<'_>] = &[
644 SegmentDef::new("tag", Start::At(0), Span::SelfDelimiting, None, Some("Uleb128"), &[]),
645 SegmentDef::new(
646 "value",
647 Start::After { segment: "tag", bits: 0 },
648 Span::Fill { cap: None },
649 None,
650 None,
651 &[],
652 ),
653 ];
654 assert_eq!(fixed_bits(T), 0);
655 assert!(!T[0].is_fixed());
656 }
657
658 #[test]
659 fn a_directed_row_stops_solving_where_the_walk_last_knew() {
660 const T: &[SegmentDef<'_>] = &[
661 BLOCK,
662 SegmentDef::new(
663 "table",
664 Start::Seek { by: "offset" },
665 Span::Counted { by: By::field("count"), each: Some(32) },
666 None,
667 Some("Entry"),
668 &[],
669 ),
670 ];
671 assert_eq!(fixed_bits(T), 48);
672 assert_eq!(T[1].start.bit(), None);
673 }
674
675 #[test]
676 fn a_fixed_byte_window_keeps_solving() {
677 const T: &[SegmentDef<'_>] = &[
678 BLOCK,
679 SegmentDef::new("children", Start::At(48), Span::Fixed(64), None, Some("Element"), &[]),
680 SegmentDef::new("crc", Start::At(112), Span::Fixed(16), None, None, &[]),
681 ];
682 assert_eq!(fixed_bits(T), 128);
683 }
684
685 #[test]
686 fn an_empty_body_is_solved_to_nothing() {
687 assert_eq!(fixed_bits(&[]), 0);
688 }
689
690 #[test]
691 fn a_strided_run_names_both_the_count_and_the_step() {
692 const T: &[SegmentDef<'_>] = &[
693 BLOCK,
694 SegmentDef::new(
695 "sub_blocks",
696 Start::At(48),
697 Span::Strided { by: By::field("n"), stride: By::field("sb_length") },
698 None,
699 Some("SubBlock"),
700 &[],
701 ),
702 ];
703 assert_eq!(fixed_bits(T), 48);
704 assert!(!T[1].is_fixed());
705 assert_eq!(T[1].span.bits(), None, "both numbers come from the wire");
706 }
707
708 #[test]
709 fn a_fixed_footprint_union_keeps_solving() {
710 const T: &[SegmentDef<'_>] = &[
711 BLOCK,
712 SegmentDef::new(
713 "args",
714 Start::At(48),
715 Span::ChosenIn { on: Discriminant::Field("cmd"), bits: 64 },
716 None,
717 Some("Args"),
718 &[],
719 ),
720 SegmentDef::new("payload", Start::At(112), Span::Fixed(32), None, None, &[]),
721 ];
722 assert_eq!(fixed_bits(T), 144);
723 assert!(T[1].is_fixed(), "a union's size is fixed");
724 assert_eq!(T[1].span.bits(), Some(64));
725 assert_eq!(T[2].start.bit(), Some(112), "so the next row's position is known");
726 }
727
728 #[test]
729 fn an_arm_that_decides_its_own_extent_is_still_a_joint() {
730 const T: &[SegmentDef<'_>] = &[
731 BLOCK,
732 SegmentDef::new(
733 "body",
734 Start::At(48),
735 Span::Chosen { on: Discriminant::Field("kind") },
736 None,
737 Some("Body"),
738 &[],
739 ),
740 ];
741 assert_eq!(fixed_bits(T), 48);
742 assert!(!T[1].is_fixed());
743 assert_eq!(T[1].span.bits(), None);
744 }
745
746 #[test]
747 fn a_catalogue_tiles_a_footprint_or_it_does_not() {
748 const EXACT: &[SegmentDef<'_>] =
749 &[SegmentDef::new("__ArgsBlock0", Start::At(0), Span::Fixed(64), None, None, &[])];
750 const SHORT: &[SegmentDef<'_>] =
751 &[SegmentDef::new("__ArgsBlock1", Start::At(0), Span::Fixed(32), None, None, &[])];
752 const OPEN: &[SegmentDef<'_>] =
753 &[SegmentDef::new("Unknown", Start::At(0), Span::Fill { cap: None }, None, None, &[])];
754 const WIRE: &[SegmentDef<'_>] = &[
755 SegmentDef::new("__ArgsBlock2", Start::At(0), Span::Fixed(8), None, None, &[]),
756 SegmentDef::new(
757 "items",
758 Start::At(8),
759 Span::Counted { by: By::field("n"), each: Some(8) },
760 None,
761 Some("Item"),
762 &[],
763 ),
764 ];
765
766 let exact = ArmDef::new("Exact", Some(0), EXACT);
767 let short = ArmDef::new("Short", Some(1), SHORT);
768 let open = ArmDef::new("Unknown", None, OPEN);
769 let wire = ArmDef::new("Wire", Some(2), WIRE);
770
771 assert!(arms_fit(&[exact], 64));
772 assert!(!arms_fit(&[exact, short], 64), "a short arm fails");
773 assert!(arms_fit(&[exact, open], 64), "a fill arm passes");
774 assert!(arms_fit(&[exact, wire], 64), "a wire-sized arm is checked during decode");
775 assert!(!arms_fit(&[short], 64));
776
777 let empty = ArmDef::new("Nop", Some(3), &[]);
778 assert!(!arms_fit(&[empty], 64));
779 assert!(arms_fit(&[empty], 0), "an empty arm is zero bits wide");
780 }
781}