refix-message 0.4.3

Framing, tokenisation and raw message representation for the ReFIX engine
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
mod error;

use crate::message::{Scope, Slot};
use crate::{InvalidValue, RawMessage, Tag};
pub use error::GroupTableError;
use layout::Layout;
use std::fmt;
use std::marker::PhantomData;

/// CheckSum(10) closes every frame, so it always ends a group.
const CHECK_SUM: Tag = Tag(10);

/// The structure of a repeating group.
///
/// Codegen emits these as `const` items. Tables built at runtime are
/// [`OwnedGroupTable`]s.
#[derive(Clone, Copy, Debug)]
pub struct GroupTable<'a> {
    count_tag: Tag,
    delimiter: Tag,
    members: &'a [Tag],
    nested: &'a [GroupTable<'a>],
}

impl<'a> GroupTable<'a> {
    /// A group counted by `count_tag`, whose instances start with
    /// `delimiter` and directly contain `members`.
    ///
    /// # Panics
    ///
    /// If `members` is not sorted and free of duplicates, or does not
    /// include the delimiter and every nested count tag. In a `const`,
    /// this is a compile error.
    pub const fn new(
        count_tag: Tag,
        delimiter: Tag,
        members: &'a [Tag],
        nested: &'a [GroupTable<'a>],
    ) -> Self {
        assert!(
            is_sorted_set(members),
            "group members must be sorted and unique"
        );
        assert!(
            contains(members, delimiter),
            "group members must include the delimiter"
        );
        let mut index = 0;
        while index < nested.len() {
            assert!(
                contains(members, nested[index].count_tag),
                "group members must include every nested count tag"
            );
            index += 1;
        }
        Self {
            count_tag,
            delimiter,
            members,
            nested,
        }
    }
}

/// A group table the walker can follow, a [`GroupTable`] or an
/// [`OwnedGroupTable`].
///
/// Sealed: only this crate implements it.
pub trait GroupLayout: Layout {}

mod layout {
    use crate::Tag;

    /// What the walker asks of a group table.
    pub trait Layout {
        fn count_tag(&self) -> Tag;
        fn delimiter(&self) -> Tag;
        fn is_member(&self, tag: Tag) -> bool;
        fn nested_counted_by(&self, tag: Tag) -> Option<&Self>;
    }
}

/// A [`GroupTable`] that owns its tags, built at runtime.
#[derive(Clone, Debug)]
pub struct OwnedGroupTable {
    count_tag: Tag,
    delimiter: Tag,
    members: Vec<Tag>,
    nested: Vec<OwnedGroupTable>,
}

impl OwnedGroupTable {
    /// A group counted by `count_tag`, whose instances start with
    /// `delimiter` and directly contain `members`.
    ///
    /// Fails where [`GroupTable::new`] panics.
    pub fn new(
        count_tag: Tag,
        delimiter: Tag,
        members: Vec<Tag>,
        nested: Vec<OwnedGroupTable>,
    ) -> Result<Self, GroupTableError> {
        if !is_sorted_set(&members) {
            return Err(GroupTableError::UnsortedMembers);
        }
        if !contains(&members, delimiter) {
            return Err(GroupTableError::DelimiterNotMember { delimiter });
        }
        if let Some(nested) = nested
            .iter()
            .find(|nested| !contains(&members, nested.count_tag))
        {
            return Err(GroupTableError::NestedCountNotMember {
                count_tag: nested.count_tag,
            });
        }
        Ok(Self {
            count_tag,
            delimiter,
            members,
            nested,
        })
    }
}

impl GroupLayout for GroupTable<'_> {}

impl GroupLayout for OwnedGroupTable {}

impl Layout for GroupTable<'_> {
    fn count_tag(&self) -> Tag {
        self.count_tag
    }

    fn delimiter(&self) -> Tag {
        self.delimiter
    }

    fn is_member(&self, tag: Tag) -> bool {
        self.members.binary_search(&tag).is_ok()
    }

    fn nested_counted_by(&self, tag: Tag) -> Option<&Self> {
        self.nested.iter().find(|nested| nested.count_tag == tag)
    }
}

impl Layout for OwnedGroupTable {
    fn count_tag(&self) -> Tag {
        self.count_tag
    }

    fn delimiter(&self) -> Tag {
        self.delimiter
    }

    fn is_member(&self, tag: Tag) -> bool {
        self.members.binary_search(&tag).is_ok()
    }

    fn nested_counted_by(&self, tag: Tag) -> Option<&Self> {
        self.nested.iter().find(|nested| nested.count_tag == tag)
    }
}

/// Every tag the walked scope (a message or a group instance) can contain, at any depth.
#[derive(Clone, Copy, Debug)]
pub struct KnownTags<'a>(&'a [Tag]);

impl<'a> KnownTags<'a> {
    /// # Panics
    ///
    /// If `tags` is not sorted and free of duplicates. In a `const`, this
    /// is a compile error.
    pub const fn new(tags: &'a [Tag]) -> Self {
        assert!(is_sorted_set(tags), "known tags must be sorted and unique");
        Self(tags)
    }

    fn contains(&self, tag: Tag) -> bool {
        self.0.binary_search(&tag).is_ok()
    }
}

/// What the walker found for one group, without judging it.
#[derive(Clone, Debug)]
pub struct Walk<'a> {
    declared_count: Option<usize>,
    instances: Vec<Scope<'a>>,
    anomalies: Vec<Anomaly>,
}

impl<'a> Walk<'a> {
    /// The group's NumInGroup value, or `None` if it is not a count.
    pub fn declared_count(&self) -> Option<usize> {
        self.declared_count
    }

    /// The instances found, in wire order.
    pub fn instances(&self) -> &[Scope<'a>] {
        &self.instances
    }

    /// How the group departs from its table; empty when it is well formed.
    pub fn anomalies(&self) -> &[Anomaly] {
        &self.anomalies
    }
}

/// A way a group on the wire departs from its table.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Anomaly {
    /// The NumInGroup value is not a non-negative integer.
    InvalidCount,
    /// An instance starts with `tag` instead of the delimiter.
    MissingDelimiter { tag: Tag },
    /// The NumInGroup value disagrees with the instances found.
    CountMismatch { declared: usize, found: usize },
}

/// A well-formed repeating group's instances, in wire order.
#[derive(Clone, Debug)]
pub struct Group<'a> {
    instances: Vec<Scope<'a>>,
}

impl<'a> Group<'a> {
    /// The number of instances.
    pub fn len(&self) -> usize {
        self.instances.len()
    }

    /// Whether the group has no instances, as with a count of zero.
    pub fn is_empty(&self) -> bool {
        self.instances.is_empty()
    }

    /// The instances, in wire order.
    pub fn iter(&self) -> impl Iterator<Item = Scope<'a>> {
        self.instances.iter().copied()
    }
}

/// A group's instances.
///
/// This is a type wrapping the instance's [`Scope`],
/// such as a generated instance type.
///
/// An absent group has no instances, the same as a count of zero.
pub struct Instances<'a, T> {
    instances: Vec<Scope<'a>>,
    instance: PhantomData<fn() -> T>,
}

impl<T> Instances<'_, T> {
    /// The number of instances.
    pub fn len(&self) -> usize {
        self.instances.len()
    }

    /// Whether there are no instances.
    pub fn is_empty(&self) -> bool {
        self.instances.is_empty()
    }
}

impl<'a, T: From<Scope<'a>>> Instances<'a, T> {
    /// The instance at `index`, in wire order.
    pub fn get(&self, index: usize) -> Option<T> {
        self.instances.get(index).copied().map(T::from)
    }

    /// The instances, in wire order.
    pub fn iter(&self) -> Iter<'_, 'a, T> {
        Iter {
            scopes: self.instances.iter(),
            instance: PhantomData,
        }
    }
}

impl<'a, T> From<Option<Group<'a>>> for Instances<'a, T> {
    fn from(group: Option<Group<'a>>) -> Self {
        Self {
            instances: group.map(|group| group.instances).unwrap_or_default(),
            instance: PhantomData,
        }
    }
}

impl<T> Default for Instances<'_, T> {
    fn default() -> Self {
        Self {
            instances: Vec::new(),
            instance: PhantomData,
        }
    }
}

impl<T> Clone for Instances<'_, T> {
    fn clone(&self) -> Self {
        Self {
            instances: self.instances.clone(),
            instance: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Instances<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(&self.instances).finish()
    }
}

impl<'i, 'a, T: From<Scope<'a>>> IntoIterator for &'i Instances<'a, T> {
    type Item = T;
    type IntoIter = Iter<'i, 'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An iterator over a group's instances, each read through `T`.
pub struct Iter<'i, 'a, T> {
    scopes: std::slice::Iter<'i, Scope<'a>>,
    instance: PhantomData<fn() -> T>,
}

impl<'a, T: From<Scope<'a>>> Iterator for Iter<'_, 'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.scopes.next().copied().map(T::from)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.scopes.size_hint()
    }
}

impl<'a, T: From<Scope<'a>>> ExactSizeIterator for Iter<'_, 'a, T> {}

impl RawMessage {
    /// The group `table` describes, read from the whole frame.
    pub fn get_group(
        &self,
        table: &impl GroupLayout,
        known: &KnownTags<'_>,
    ) -> Result<Option<Group<'_>>, InvalidValue> {
        self.scope().get_group(table, known)
    }
}

impl<'a> Scope<'a> {
    /// Walks the group `table` describes, or `None` if its count field is
    /// not in this scope.
    ///
    /// An instance starts at the delimiter, or wherever one of its tags
    /// repeats. A tag the message does not know stays in its instance; any
    /// other tag outside the table, or CheckSum, ends the group. Nothing is
    /// rejected, and malformed groups are reported as anomalies.
    pub fn walk_group(&self, table: &impl GroupLayout, known: &KnownTags<'_>) -> Option<Walk<'a>> {
        let (count_slot, _) = self.find(table.count_tag(), self.start())?;
        Some(walk(self, count_slot, table, known).0)
    }

    /// The group `table` describes, or `Ok(None)` if its count field is
    /// absent.
    ///
    /// A group malformed in any way is an error on the count tag. A count of
    /// zero is an empty group.
    pub fn get_group(
        &self,
        table: &impl GroupLayout,
        known: &KnownTags<'_>,
    ) -> Result<Option<Group<'a>>, InvalidValue> {
        let Some(walk) = self.walk_group(table, known) else {
            return Ok(None);
        };
        if !walk.anomalies.is_empty() {
            return Err(InvalidValue {
                tag: table.count_tag(),
            });
        }
        Ok(Some(Group {
            instances: walk.instances,
        }))
    }
}

/// Walks the group whose count field sits at `count_slot`, returning what
/// it found and the slot where the group ends.
fn walk<'a, L: GroupLayout>(
    scope: &Scope<'a>,
    count_slot: Slot,
    table: &L,
    known: &KnownTags<'_>,
) -> (Walk<'a>, Slot) {
    let declared_count = parse_count(scope.value_at(count_slot));
    let mut anomalies = Vec::new();
    if declared_count.is_none() {
        anomalies.push(Anomaly::InvalidCount);
    }

    let mut instances = Vec::new();
    let mut instance_start = None;
    let mut seen = Vec::new();
    let mut slot = count_slot.next();
    while slot < scope.end() {
        let tag = scope.tag_at(slot);
        if tag == CHECK_SUM {
            break;
        }
        if table.is_member(tag) {
            if instance_start.is_none() || seen.contains(&tag) {
                if let Some(start) = instance_start {
                    instances.push(scope.narrow(start, slot));
                }
                if tag != table.delimiter() {
                    anomalies.push(Anomaly::MissingDelimiter { tag });
                }
                instance_start = Some(slot);
                seen.clear();
            }
            seen.push(tag);
            slot = match table.nested_counted_by(tag) {
                Some(nested) => walk(scope, slot, nested, known).1,
                None => slot.next(),
            };
        } else if known.contains(tag) {
            break;
        } else {
            slot = slot.next();
        }
    }
    if let Some(start) = instance_start {
        instances.push(scope.narrow(start, slot));
    }

    if let Some(declared) = declared_count
        && declared != instances.len()
    {
        anomalies.push(Anomaly::CountMismatch {
            declared,
            found: instances.len(),
        });
    }

    let walk = Walk {
        declared_count,
        instances,
        anomalies,
    };
    (walk, slot)
}

/// Parses a NumInGroup value, which must be a non-negative integer.
fn parse_count(value: &[u8]) -> Option<usize> {
    std::str::from_utf8(value).ok()?.parse().ok()
}

/// Whether `tags` is strictly increasing.
const fn is_sorted_set(tags: &[Tag]) -> bool {
    let mut index = 1;
    while index < tags.len() {
        if tags[index - 1].0 >= tags[index].0 {
            return false;
        }
        index += 1;
    }
    true
}

/// Whether `tags` contains `tag`.
const fn contains(tags: &[Tag], tag: Tag) -> bool {
    let mut index = 0;
    while index < tags.len() {
        if tags[index].0 == tag.0 {
            return true;
        }
        index += 1;
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::construct_valid_frame;
    use crate::{RawMessage, Tokenizer};
    use bytes::Bytes;

    const NO_PARTY_SUB_IDS: GroupTable<'static> =
        GroupTable::new(Tag(802), Tag(523), &[Tag(523), Tag(803)], &[]);

    const NO_PARTY_IDS: GroupTable<'static> = GroupTable::new(
        Tag(453),
        Tag(448),
        &[Tag(447), Tag(448), Tag(452), Tag(802)],
        &[NO_PARTY_SUB_IDS],
    );

    const KNOWN: KnownTags<'static> = KnownTags::new(&[
        Tag(11),
        Tag(35),
        Tag(54),
        Tag(447),
        Tag(448),
        Tag(452),
        Tag(453),
        Tag(523),
        Tag(802),
        Tag(803),
    ]);

    /// A FIX.4.4 frame around the `|`-delimited `body`.
    fn message(body: &str) -> RawMessage {
        let frame = construct_valid_frame("FIX.4.4", body);
        Tokenizer::default().tokenize(Bytes::from(frame)).unwrap()
    }

    fn walk_parties(message: &RawMessage) -> Walk<'_> {
        message.scope().walk_group(&NO_PARTY_IDS, &KNOWN).unwrap()
    }

    fn text<'a>(scope: &Scope<'a>, tag: u32) -> Option<&'a str> {
        scope.get_str(Tag(tag)).unwrap()
    }

    mod structure {
        use super::*;

        #[test]
        fn an_absent_group_walks_to_nothing() {
            let message = message("35=D|11=X|54=1|");
            assert!(message.scope().walk_group(&NO_PARTY_IDS, &KNOWN).is_none());
        }

        #[test]
        fn finds_each_instance() {
            let message = message("35=D|453=2|448=AL|452=1|448=BOB|452=3|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(walk.declared_count(), Some(2));
            assert!(walk.anomalies().is_empty());
            let [first, second] = walk.instances() else {
                panic!("expected two instances");
            };
            assert_eq!(
                (text(first, 448), text(first, 452)),
                (Some("AL"), Some("1"))
            );
            assert_eq!(
                (text(second, 448), text(second, 452)),
                (Some("BOB"), Some("3"))
            );
            assert_eq!(text(second, 54), None);
        }

        #[test]
        fn a_missing_optional_field_does_not_read_the_next_instance() {
            let message = message("35=D|453=2|448=AL|448=BOB|452=3|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(text(&walk.instances()[0], 452), None);
        }

        #[test]
        fn a_nested_group_stays_inside_its_instance() {
            let message = message("35=D|453=2|448=AL|802=1|523=S1|452=1|448=BOB|452=3|54=1|");
            let walk = walk_parties(&message);

            assert!(walk.anomalies().is_empty());
            let [first, second] = walk.instances() else {
                panic!("expected two instances");
            };
            assert_eq!(text(first, 452), Some("1"));
            let nested = first.walk_group(&NO_PARTY_SUB_IDS, &KNOWN).unwrap();
            assert_eq!(nested.instances().len(), 1);
            assert_eq!(text(&nested.instances()[0], 523), Some("S1"));
            assert!(second.walk_group(&NO_PARTY_SUB_IDS, &KNOWN).is_none());
        }

        #[test]
        fn a_nested_group_can_be_the_delimiter() {
            const OUTER: GroupTable<'static> = GroupTable::new(
                Tag(453),
                Tag(802),
                &[Tag(452), Tag(802)],
                &[NO_PARTY_SUB_IDS],
            );
            let message = message("35=D|453=2|802=1|523=A|452=1|802=1|523=B|54=1|");
            let walk = message.scope().walk_group(&OUTER, &KNOWN).unwrap();

            assert!(walk.anomalies().is_empty());
            let [first, second] = walk.instances() else {
                panic!("expected two instances");
            };
            assert_eq!((text(first, 523), text(first, 452)), (Some("A"), Some("1")));
            assert_eq!((text(second, 523), text(second, 452)), (Some("B"), None));
        }

        #[test]
        fn an_unknown_tag_stays_in_its_instance() {
            let message = message("35=D|453=2|448=AL|5001=x|452=1|448=BOB|54=1|");
            let walk = walk_parties(&message);

            assert!(walk.anomalies().is_empty());
            let first = &walk.instances()[0];
            assert_eq!(
                (text(first, 5001), text(first, 452)),
                (Some("x"), Some("1"))
            );
        }

        #[test]
        fn check_sum_ends_a_group_at_the_end_of_the_body() {
            let message = message("35=D|453=1|448=AL|");
            let walk = walk_parties(&message);

            assert_eq!(walk.instances().len(), 1);
            assert_eq!(walk.instances()[0].get(Tag(10)), None);
        }

        #[test]
        fn a_zero_count_is_an_empty_group() {
            let message = message("35=D|453=0|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(walk.declared_count(), Some(0));
            assert!(walk.instances().is_empty());
            assert!(walk.anomalies().is_empty());
        }
    }

    mod anomalies {
        use super::*;

        #[test]
        fn an_invalid_count_is_reported() {
            let message = message("35=D|453=x|448=AL|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(walk.declared_count(), None);
            assert_eq!(walk.anomalies(), [Anomaly::InvalidCount]);
            assert_eq!(walk.instances().len(), 1);
        }

        #[test]
        fn a_count_mismatch_is_reported() {
            let message = message("35=D|453=3|448=AL|448=BOB|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(
                walk.anomalies(),
                [Anomaly::CountMismatch {
                    declared: 3,
                    found: 2,
                }]
            );
        }

        #[test]
        fn a_reordered_instance_is_kept_whole() {
            let message = message("35=D|453=1|452=1|448=AL|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(
                walk.anomalies(),
                [Anomaly::MissingDelimiter { tag: Tag(452) }]
            );
            let [instance] = walk.instances() else {
                panic!("expected one instance");
            };
            assert_eq!(
                (text(instance, 452), text(instance, 448)),
                (Some("1"), Some("AL"))
            );
        }

        #[test]
        fn a_repeated_tag_starts_a_new_instance() {
            let message = message("35=D|453=2|448=AL|452=1|452=3|54=1|");
            let walk = walk_parties(&message);

            assert_eq!(
                walk.anomalies(),
                [Anomaly::MissingDelimiter { tag: Tag(452) }]
            );
            let [first, second] = walk.instances() else {
                panic!("expected two instances");
            };
            assert_eq!(text(first, 452), Some("1"));
            assert_eq!((text(second, 452), text(second, 448)), (Some("3"), None));
        }
    }

    mod contract {
        use super::*;

        #[test]
        fn an_absent_group_is_none() {
            let message = message("35=D|11=X|54=1|");
            assert!(matches!(message.get_group(&NO_PARTY_IDS, &KNOWN), Ok(None)));
        }

        #[test]
        fn a_well_formed_group_reads_its_instances() {
            let message = message("35=D|453=2|448=AL|452=1|448=BOB|54=1|");
            let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();

            assert_eq!(group.len(), 2);
            let parties: Vec<(Option<&str>, Option<&str>)> = group
                .iter()
                .map(|instance| (text(&instance, 448), text(&instance, 452)))
                .collect();
            assert_eq!(parties, [(Some("AL"), Some("1")), (Some("BOB"), None)]);
        }

        #[test]
        fn a_zero_count_is_an_empty_group() {
            let message = message("35=D|453=0|54=1|");
            let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();

            assert!(group.is_empty());
        }

        #[test]
        fn any_anomaly_is_an_error_on_the_count_tag() {
            let malformed = [
                "35=D|453=x|448=AL|54=1|",
                "35=D|453=3|448=AL|448=BOB|54=1|",
                "35=D|453=1|452=1|448=AL|54=1|",
            ];
            for body in malformed {
                let message = message(body);
                assert_eq!(
                    message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap_err(),
                    InvalidValue { tag: Tag(453) },
                    "{body}"
                );
            }
        }

        #[test]
        fn a_nested_group_is_read_from_its_instance() {
            let message = message("35=D|453=1|448=AL|802=2|523=S1|523=S2|54=1|");
            let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
            let instance = group.iter().next().unwrap();
            let nested = instance
                .get_group(&NO_PARTY_SUB_IDS, &KNOWN)
                .unwrap()
                .unwrap();

            let sub_ids: Vec<Option<&str>> = nested.iter().map(|sub| text(&sub, 523)).collect();
            assert_eq!(sub_ids, [Some("S1"), Some("S2")]);
        }
    }

    mod instances {
        use super::*;

        /// An instance type as codegen would write it.
        #[derive(Clone, Copy, Debug)]
        struct Party<'a>(Scope<'a>);

        impl<'a> From<Scope<'a>> for Party<'a> {
            fn from(scope: Scope<'a>) -> Self {
                Self(scope)
            }
        }

        impl<'a> Party<'a> {
            fn party_id(&self) -> Option<&'a str> {
                text(&self.0, 448)
            }
        }

        fn parties(message: &RawMessage) -> Instances<'_, Party<'_>> {
            Instances::from(message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap())
        }

        #[test]
        fn reads_each_instance_through_its_type() {
            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
            let parties = parties(&message);

            assert_eq!(parties.len(), 2);
            let ids: Vec<Option<&str>> = parties.iter().map(|party| party.party_id()).collect();
            assert_eq!(ids, [Some("AL"), Some("BOB")]);
        }

        #[test]
        fn an_absent_group_has_no_instances() {
            let message = message("35=D|11=X|54=1|");
            let parties = parties(&message);

            assert!(parties.is_empty());
            assert_eq!(parties.iter().count(), 0);
        }

        #[test]
        fn get_reads_one_instance_by_position() {
            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
            let parties = parties(&message);

            assert_eq!(parties.get(1).unwrap().party_id(), Some("BOB"));
            assert!(parties.get(2).is_none());
        }

        #[test]
        fn iterates_by_reference() {
            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
            let parties = parties(&message);

            let mut ids = Vec::new();
            for party in &parties {
                ids.push(party.party_id());
            }
            assert_eq!(ids, [Some("AL"), Some("BOB")]);
        }

        #[test]
        fn the_iterator_knows_its_length() {
            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
            let parties = parties(&message);

            let mut iter = parties.iter();
            assert_eq!(iter.len(), 2);
            iter.next();
            assert_eq!(iter.len(), 1);
        }

        #[test]
        fn default_is_empty() {
            let parties: Instances<'_, Party<'_>> = Instances::default();
            assert!(parties.is_empty());
        }

        #[test]
        fn a_nested_group_is_read_through_an_instance_scope() {
            let message = message("35=D|453=1|448=AL|802=2|523=S1|523=S2|54=1|");
            let parties = parties(&message);
            let party = parties.get(0).unwrap();

            let sub_ids: Instances<'_, Scope<'_>> =
                Instances::from(party.0.get_group(&NO_PARTY_SUB_IDS, &KNOWN).unwrap());
            let values: Vec<Option<&str>> = sub_ids.iter().map(|sub| text(&sub, 523)).collect();
            assert_eq!(values, [Some("S1"), Some("S2")]);
        }
    }

    mod tables {
        use super::*;

        #[test]
        #[should_panic(expected = "group members must be sorted and unique")]
        fn unsorted_members_are_rejected() {
            GroupTable::new(Tag(453), Tag(448), &[Tag(452), Tag(448)], &[]);
        }

        #[test]
        #[should_panic(expected = "group members must include the delimiter")]
        fn members_without_the_delimiter_are_rejected() {
            GroupTable::new(Tag(453), Tag(448), &[Tag(452)], &[]);
        }

        #[test]
        #[should_panic(expected = "group members must include every nested count tag")]
        fn members_without_a_nested_count_tag_are_rejected() {
            GroupTable::new(Tag(453), Tag(448), &[Tag(448)], &[NO_PARTY_SUB_IDS]);
        }

        #[test]
        #[should_panic(expected = "known tags must be sorted and unique")]
        fn duplicate_known_tags_are_rejected() {
            KnownTags::new(&[Tag(35), Tag(35)]);
        }
    }

    mod owned {
        use super::*;

        fn owned(
            count_tag: u32,
            delimiter: u32,
            members: &[u32],
            nested: Vec<OwnedGroupTable>,
        ) -> Result<OwnedGroupTable, GroupTableError> {
            let members = members.iter().map(|&tag| Tag(tag)).collect();
            OwnedGroupTable::new(Tag(count_tag), Tag(delimiter), members, nested)
        }

        fn party_sub_ids() -> OwnedGroupTable {
            owned(802, 523, &[523, 803], vec![]).unwrap()
        }

        fn parties() -> OwnedGroupTable {
            owned(453, 448, &[447, 448, 452, 802], vec![party_sub_ids()]).unwrap()
        }

        #[test]
        fn walks_like_its_const_twin() {
            fn ids<'a>(group: &Group<'a>) -> Vec<Option<&'a str>> {
                group.iter().map(|party| text(&party, 448)).collect()
            }
            let message = message("35=D|453=2|448=AL|802=2|523=S1|523=S2|448=BOB|54=1|");

            let owned = message.get_group(&parties(), &KNOWN).unwrap().unwrap();
            let borrowed = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
            assert_eq!(ids(&owned), ids(&borrowed));
            assert_eq!(ids(&owned), [Some("AL"), Some("BOB")]);

            let first = owned.iter().next().unwrap();
            let sub_ids = first.get_group(&party_sub_ids(), &KNOWN).unwrap().unwrap();
            let sub_ids: Vec<Option<&str>> = sub_ids.iter().map(|sub| text(&sub, 523)).collect();
            assert_eq!(sub_ids, [Some("S1"), Some("S2")]);
        }

        #[test]
        fn unsorted_or_duplicate_members_are_an_error() {
            assert_eq!(
                owned(453, 448, &[448, 447], vec![]).unwrap_err(),
                GroupTableError::UnsortedMembers
            );
            assert_eq!(
                owned(453, 448, &[448, 448], vec![]).unwrap_err(),
                GroupTableError::UnsortedMembers
            );
        }

        #[test]
        fn a_delimiter_outside_the_members_is_an_error() {
            assert_eq!(
                owned(453, 448, &[447], vec![]).unwrap_err(),
                GroupTableError::DelimiterNotMember {
                    delimiter: Tag(448)
                }
            );
        }

        #[test]
        fn a_nested_count_tag_outside_the_members_is_an_error() {
            assert_eq!(
                owned(453, 448, &[448], vec![party_sub_ids()]).unwrap_err(),
                GroupTableError::NestedCountNotMember {
                    count_tag: Tag(802)
                }
            );
        }

        #[test]
        fn errors_name_the_broken_rule() {
            assert_eq!(
                GroupTableError::NestedCountNotMember {
                    count_tag: Tag(802)
                }
                .to_string(),
                "group members must include the nested count tag 802"
            );
        }
    }
}