Skip to main content

refix_message/
group.rs

1mod error;
2
3use crate::message::{Scope, Slot};
4use crate::{InvalidValue, RawMessage, Tag};
5pub use error::GroupTableError;
6use layout::Layout;
7use std::fmt;
8use std::marker::PhantomData;
9use std::sync::OnceLock;
10
11/// CheckSum(10) closes every frame, so it always ends a group.
12const CHECK_SUM: Tag = Tag(10);
13
14/// The structure of a repeating group.
15///
16/// Codegen emits these as `const` items. Tables built at runtime are
17/// [`OwnedGroupTable`]s.
18#[derive(Clone, Copy, Debug)]
19pub struct GroupTable<'a> {
20    count_tag: Tag,
21    delimiter: Tag,
22    members: &'a [Tag],
23    nested: &'a [GroupTable<'a>],
24}
25
26impl<'a> GroupTable<'a> {
27    /// A group counted by `count_tag`, whose instances start with
28    /// `delimiter` and directly contain `members`.
29    ///
30    /// # Panics
31    ///
32    /// If `members` is not sorted and free of duplicates, or does not
33    /// include the delimiter and every nested count tag. In a `const`,
34    /// this is a compile error.
35    pub const fn new(
36        count_tag: Tag,
37        delimiter: Tag,
38        members: &'a [Tag],
39        nested: &'a [GroupTable<'a>],
40    ) -> Self {
41        assert!(
42            is_sorted_set(members),
43            "group members must be sorted and unique"
44        );
45        assert!(
46            contains(members, delimiter),
47            "group members must include the delimiter"
48        );
49        let mut index = 0;
50        while index < nested.len() {
51            assert!(
52                contains(members, nested[index].count_tag),
53                "group members must include every nested count tag"
54            );
55            index += 1;
56        }
57        Self {
58            count_tag,
59            delimiter,
60            members,
61            nested,
62        }
63    }
64}
65
66/// A group table the walker can follow, a [`GroupTable`] or an
67/// [`OwnedGroupTable`].
68///
69/// Sealed: only this crate implements it.
70pub trait GroupLayout: Layout {}
71
72mod layout {
73    use crate::Tag;
74
75    /// What the walker asks of a group table.
76    pub trait Layout {
77        fn count_tag(&self) -> Tag;
78        fn delimiter(&self) -> Tag;
79        fn is_member(&self, tag: Tag) -> bool;
80        fn nested_counted_by(&self, tag: Tag) -> Option<&Self>;
81    }
82}
83
84/// A [`GroupTable`] that owns its tags, built at runtime.
85#[derive(Clone, Debug)]
86pub struct OwnedGroupTable {
87    count_tag: Tag,
88    delimiter: Tag,
89    members: Vec<Tag>,
90    nested: Vec<OwnedGroupTable>,
91}
92
93impl OwnedGroupTable {
94    /// A group counted by `count_tag`, whose instances start with
95    /// `delimiter` and directly contain `members`.
96    ///
97    /// Fails where [`GroupTable::new`] panics.
98    pub fn new(
99        count_tag: Tag,
100        delimiter: Tag,
101        members: Vec<Tag>,
102        nested: Vec<OwnedGroupTable>,
103    ) -> Result<Self, GroupTableError> {
104        if !is_sorted_set(&members) {
105            return Err(GroupTableError::UnsortedMembers);
106        }
107        if !contains(&members, delimiter) {
108            return Err(GroupTableError::DelimiterNotMember { delimiter });
109        }
110        if let Some(nested) = nested
111            .iter()
112            .find(|nested| !contains(&members, nested.count_tag))
113        {
114            return Err(GroupTableError::NestedCountNotMember {
115                count_tag: nested.count_tag,
116            });
117        }
118        Ok(Self {
119            count_tag,
120            delimiter,
121            members,
122            nested,
123        })
124    }
125}
126
127impl GroupLayout for GroupTable<'_> {}
128
129impl GroupLayout for OwnedGroupTable {}
130
131impl Layout for GroupTable<'_> {
132    fn count_tag(&self) -> Tag {
133        self.count_tag
134    }
135
136    fn delimiter(&self) -> Tag {
137        self.delimiter
138    }
139
140    fn is_member(&self, tag: Tag) -> bool {
141        self.members.binary_search(&tag).is_ok()
142    }
143
144    fn nested_counted_by(&self, tag: Tag) -> Option<&Self> {
145        self.nested.iter().find(|nested| nested.count_tag == tag)
146    }
147}
148
149impl Layout for OwnedGroupTable {
150    fn count_tag(&self) -> Tag {
151        self.count_tag
152    }
153
154    fn delimiter(&self) -> Tag {
155        self.delimiter
156    }
157
158    fn is_member(&self, tag: Tag) -> bool {
159        self.members.binary_search(&tag).is_ok()
160    }
161
162    fn nested_counted_by(&self, tag: Tag) -> Option<&Self> {
163        self.nested.iter().find(|nested| nested.count_tag == tag)
164    }
165}
166
167/// Every tag the walked scope (a message or a group instance) can contain, at any depth.
168#[derive(Clone, Copy, Debug)]
169pub struct KnownTags<'a>(&'a [Tag]);
170
171impl<'a> KnownTags<'a> {
172    /// # Panics
173    ///
174    /// If `tags` is not sorted and free of duplicates. In a `const`, this
175    /// is a compile error.
176    pub const fn new(tags: &'a [Tag]) -> Self {
177        assert!(is_sorted_set(tags), "known tags must be sorted and unique");
178        Self(tags)
179    }
180
181    pub(crate) fn contains(&self, tag: Tag) -> bool {
182        self.0.binary_search(&tag).is_ok()
183    }
184}
185
186/// Known tags merged on first use from lists that are each written once.
187///
188/// Codegen emits these as `static` items. A message, component or group
189/// instance lists its own tags and names the lists of what it includes.
190#[derive(Debug)]
191pub struct LazyKnownTags {
192    own: &'static [Tag],
193    parts: &'static [&'static LazyKnownTags],
194    merged: OnceLock<Box<[Tag]>>,
195}
196
197impl LazyKnownTags {
198    /// `own` may be in any order and may repeat a tag of `parts`.
199    pub const fn new(own: &'static [Tag], parts: &'static [&'static LazyKnownTags]) -> Self {
200        Self {
201            own,
202            parts,
203            merged: OnceLock::new(),
204        }
205    }
206
207    /// The merged tags.
208    ///
209    /// The first call builds them. Every later call returns the same list.
210    pub fn get(&'static self) -> KnownTags<'static> {
211        KnownTags(self.merged.get_or_init(|| {
212            let mut tags = Vec::new();
213            self.collect(&mut tags);
214            tags.sort_unstable();
215            tags.dedup();
216            tags.into_boxed_slice()
217        }))
218    }
219
220    fn collect(&self, tags: &mut Vec<Tag>) {
221        tags.extend_from_slice(self.own);
222        for part in self.parts {
223            part.collect(tags);
224        }
225    }
226}
227
228/// What the walker found for one group, without judging it.
229#[derive(Clone, Debug)]
230pub struct Walk<'a> {
231    declared_count: Option<usize>,
232    instances: Vec<Scope<'a>>,
233    anomalies: Vec<Anomaly>,
234}
235
236impl<'a> Walk<'a> {
237    /// The group's NumInGroup value, or `None` if it is not a count.
238    pub fn declared_count(&self) -> Option<usize> {
239        self.declared_count
240    }
241
242    /// The instances found, in wire order.
243    pub fn instances(&self) -> &[Scope<'a>] {
244        &self.instances
245    }
246
247    /// How the group departs from its table; empty when it is well formed.
248    pub fn anomalies(&self) -> &[Anomaly] {
249        &self.anomalies
250    }
251}
252
253/// A way a group on the wire departs from its table.
254#[derive(Clone, Copy, Debug, Eq, PartialEq)]
255pub enum Anomaly {
256    /// The NumInGroup value is not a non-negative integer.
257    InvalidCount,
258    /// An instance starts with `tag` instead of the delimiter.
259    MissingDelimiter { tag: Tag },
260    /// The NumInGroup value disagrees with the instances found.
261    CountMismatch { declared: usize, found: usize },
262}
263
264/// A well-formed repeating group's instances, in wire order.
265#[derive(Clone, Debug)]
266pub struct Group<'a> {
267    instances: Vec<Scope<'a>>,
268}
269
270impl<'a> Group<'a> {
271    /// The number of instances.
272    pub fn len(&self) -> usize {
273        self.instances.len()
274    }
275
276    /// Whether the group has no instances, as with a count of zero.
277    pub fn is_empty(&self) -> bool {
278        self.instances.is_empty()
279    }
280
281    /// The instances, in wire order.
282    pub fn iter(&self) -> impl Iterator<Item = Scope<'a>> {
283        self.instances.iter().copied()
284    }
285}
286
287/// A group's instances.
288///
289/// This is a type wrapping the instance's [`Scope`],
290/// such as a generated instance type.
291///
292/// An absent group has no instances, the same as a count of zero.
293pub struct Instances<'a, T> {
294    instances: Vec<Scope<'a>>,
295    instance: PhantomData<fn() -> T>,
296}
297
298impl<T> Instances<'_, T> {
299    /// The number of instances.
300    pub fn len(&self) -> usize {
301        self.instances.len()
302    }
303
304    /// Whether there are no instances.
305    pub fn is_empty(&self) -> bool {
306        self.instances.is_empty()
307    }
308}
309
310impl<'a, T: From<Scope<'a>>> Instances<'a, T> {
311    /// The instance at `index`, in wire order.
312    pub fn get(&self, index: usize) -> Option<T> {
313        self.instances.get(index).copied().map(T::from)
314    }
315
316    /// The instances, in wire order.
317    pub fn iter(&self) -> Iter<'_, 'a, T> {
318        Iter {
319            scopes: self.instances.iter(),
320            instance: PhantomData,
321        }
322    }
323}
324
325impl<'a, T> From<Option<Group<'a>>> for Instances<'a, T> {
326    fn from(group: Option<Group<'a>>) -> Self {
327        Self {
328            instances: group.map(|group| group.instances).unwrap_or_default(),
329            instance: PhantomData,
330        }
331    }
332}
333
334impl<T> Default for Instances<'_, T> {
335    fn default() -> Self {
336        Self {
337            instances: Vec::new(),
338            instance: PhantomData,
339        }
340    }
341}
342
343impl<T> Clone for Instances<'_, T> {
344    fn clone(&self) -> Self {
345        Self {
346            instances: self.instances.clone(),
347            instance: PhantomData,
348        }
349    }
350}
351
352impl<T> fmt::Debug for Instances<'_, T> {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        f.debug_list().entries(&self.instances).finish()
355    }
356}
357
358impl<'i, 'a, T: From<Scope<'a>>> IntoIterator for &'i Instances<'a, T> {
359    type Item = T;
360    type IntoIter = Iter<'i, 'a, T>;
361
362    fn into_iter(self) -> Self::IntoIter {
363        self.iter()
364    }
365}
366
367/// An iterator over a group's instances, each read through `T`.
368pub struct Iter<'i, 'a, T> {
369    scopes: std::slice::Iter<'i, Scope<'a>>,
370    instance: PhantomData<fn() -> T>,
371}
372
373impl<'a, T: From<Scope<'a>>> Iterator for Iter<'_, 'a, T> {
374    type Item = T;
375
376    fn next(&mut self) -> Option<T> {
377        self.scopes.next().copied().map(T::from)
378    }
379
380    fn size_hint(&self) -> (usize, Option<usize>) {
381        self.scopes.size_hint()
382    }
383}
384
385impl<'a, T: From<Scope<'a>>> ExactSizeIterator for Iter<'_, 'a, T> {}
386
387impl RawMessage {
388    /// The group `table` describes, read from the whole frame.
389    pub fn get_group(
390        &self,
391        table: &impl GroupLayout,
392        known: &KnownTags<'_>,
393    ) -> Result<Option<Group<'_>>, InvalidValue> {
394        self.scope().get_group(table, known)
395    }
396}
397
398impl<'a> Scope<'a> {
399    /// Walks the group `table` describes, or `None` if its count field is
400    /// not in this scope.
401    ///
402    /// An instance starts at the delimiter, or wherever one of its tags
403    /// repeats. A tag the message does not know stays in its instance; any
404    /// other tag outside the table, or CheckSum, ends the group. Nothing is
405    /// rejected, and malformed groups are reported as anomalies.
406    pub fn walk_group(&self, table: &impl GroupLayout, known: &KnownTags<'_>) -> Option<Walk<'a>> {
407        let (count_slot, _) = self.find(table.count_tag(), self.start())?;
408        Some(walk(self, count_slot, table, known).0)
409    }
410
411    /// The group `table` describes, or `Ok(None)` if its count field is
412    /// absent.
413    ///
414    /// A group malformed in any way is an error on the count tag. A count of
415    /// zero is an empty group.
416    pub fn get_group(
417        &self,
418        table: &impl GroupLayout,
419        known: &KnownTags<'_>,
420    ) -> Result<Option<Group<'a>>, InvalidValue> {
421        let Some(walk) = self.walk_group(table, known) else {
422            return Ok(None);
423        };
424        if !walk.anomalies.is_empty() {
425            return Err(InvalidValue {
426                tag: table.count_tag(),
427            });
428        }
429        Ok(Some(Group {
430            instances: walk.instances,
431        }))
432    }
433}
434
435/// Walks the group whose count field sits at `count_slot`, returning what
436/// it found and the slot where the group ends.
437fn walk<'a, L: GroupLayout>(
438    scope: &Scope<'a>,
439    count_slot: Slot,
440    table: &L,
441    known: &KnownTags<'_>,
442) -> (Walk<'a>, Slot) {
443    let declared_count = parse_count(scope.value_at(count_slot));
444    let mut anomalies = Vec::new();
445    if declared_count.is_none() {
446        anomalies.push(Anomaly::InvalidCount);
447    }
448
449    let mut instances = Vec::new();
450    let mut instance_start = None;
451    let mut seen = Vec::new();
452    let mut slot = count_slot.next();
453    while slot < scope.end() {
454        let tag = scope.tag_at(slot);
455        if tag == CHECK_SUM {
456            break;
457        }
458        if table.is_member(tag) {
459            if instance_start.is_none() || seen.contains(&tag) {
460                if let Some(start) = instance_start {
461                    instances.push(scope.narrow(start, slot));
462                }
463                if tag != table.delimiter() {
464                    anomalies.push(Anomaly::MissingDelimiter { tag });
465                }
466                instance_start = Some(slot);
467                seen.clear();
468            }
469            seen.push(tag);
470            slot = match table.nested_counted_by(tag) {
471                Some(nested) => walk(scope, slot, nested, known).1,
472                None => slot.next(),
473            };
474        } else if known.contains(tag) {
475            break;
476        } else {
477            slot = slot.next();
478        }
479    }
480    if let Some(start) = instance_start {
481        instances.push(scope.narrow(start, slot));
482    }
483
484    if let Some(declared) = declared_count
485        && declared != instances.len()
486    {
487        anomalies.push(Anomaly::CountMismatch {
488            declared,
489            found: instances.len(),
490        });
491    }
492
493    let walk = Walk {
494        declared_count,
495        instances,
496        anomalies,
497    };
498    (walk, slot)
499}
500
501/// Parses a NumInGroup value, which must be a non-negative integer.
502fn parse_count(value: &[u8]) -> Option<usize> {
503    std::str::from_utf8(value).ok()?.parse().ok()
504}
505
506/// Whether `tags` is strictly increasing.
507const fn is_sorted_set(tags: &[Tag]) -> bool {
508    let mut index = 1;
509    while index < tags.len() {
510        if tags[index - 1].0 >= tags[index].0 {
511            return false;
512        }
513        index += 1;
514    }
515    true
516}
517
518/// Whether `tags` contains `tag`.
519const fn contains(tags: &[Tag], tag: Tag) -> bool {
520    let mut index = 0;
521    while index < tags.len() {
522        if tags[index].0 == tag.0 {
523            return true;
524        }
525        index += 1;
526    }
527    false
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::test_utils::construct_valid_frame;
534    use crate::{RawMessage, Tokenizer};
535    use bytes::Bytes;
536
537    const NO_PARTY_SUB_IDS: GroupTable<'static> =
538        GroupTable::new(Tag(802), Tag(523), &[Tag(523), Tag(803)], &[]);
539
540    const NO_PARTY_IDS: GroupTable<'static> = GroupTable::new(
541        Tag(453),
542        Tag(448),
543        &[Tag(447), Tag(448), Tag(452), Tag(802)],
544        &[NO_PARTY_SUB_IDS],
545    );
546
547    const KNOWN: KnownTags<'static> = KnownTags::new(&[
548        Tag(11),
549        Tag(35),
550        Tag(54),
551        Tag(447),
552        Tag(448),
553        Tag(452),
554        Tag(453),
555        Tag(523),
556        Tag(802),
557        Tag(803),
558    ]);
559
560    /// A FIX.4.4 frame around the `|`-delimited `body`.
561    fn message(body: &str) -> RawMessage {
562        let frame = construct_valid_frame("FIX.4.4", body);
563        Tokenizer::default().tokenize(Bytes::from(frame)).unwrap()
564    }
565
566    fn walk_parties(message: &RawMessage) -> Walk<'_> {
567        message.scope().walk_group(&NO_PARTY_IDS, &KNOWN).unwrap()
568    }
569
570    fn text<'a>(scope: &Scope<'a>, tag: u32) -> Option<&'a str> {
571        scope.get_str(Tag(tag)).unwrap()
572    }
573
574    mod structure {
575        use super::*;
576
577        #[test]
578        fn an_absent_group_walks_to_nothing() {
579            let message = message("35=D|11=X|54=1|");
580            assert!(message.scope().walk_group(&NO_PARTY_IDS, &KNOWN).is_none());
581        }
582
583        #[test]
584        fn finds_each_instance() {
585            let message = message("35=D|453=2|448=AL|452=1|448=BOB|452=3|54=1|");
586            let walk = walk_parties(&message);
587
588            assert_eq!(walk.declared_count(), Some(2));
589            assert!(walk.anomalies().is_empty());
590            let [first, second] = walk.instances() else {
591                panic!("expected two instances");
592            };
593            assert_eq!(
594                (text(first, 448), text(first, 452)),
595                (Some("AL"), Some("1"))
596            );
597            assert_eq!(
598                (text(second, 448), text(second, 452)),
599                (Some("BOB"), Some("3"))
600            );
601            assert_eq!(text(second, 54), None);
602        }
603
604        #[test]
605        fn a_missing_optional_field_does_not_read_the_next_instance() {
606            let message = message("35=D|453=2|448=AL|448=BOB|452=3|54=1|");
607            let walk = walk_parties(&message);
608
609            assert_eq!(text(&walk.instances()[0], 452), None);
610        }
611
612        #[test]
613        fn a_nested_group_stays_inside_its_instance() {
614            let message = message("35=D|453=2|448=AL|802=1|523=S1|452=1|448=BOB|452=3|54=1|");
615            let walk = walk_parties(&message);
616
617            assert!(walk.anomalies().is_empty());
618            let [first, second] = walk.instances() else {
619                panic!("expected two instances");
620            };
621            assert_eq!(text(first, 452), Some("1"));
622            let nested = first.walk_group(&NO_PARTY_SUB_IDS, &KNOWN).unwrap();
623            assert_eq!(nested.instances().len(), 1);
624            assert_eq!(text(&nested.instances()[0], 523), Some("S1"));
625            assert!(second.walk_group(&NO_PARTY_SUB_IDS, &KNOWN).is_none());
626        }
627
628        #[test]
629        fn a_nested_group_can_be_the_delimiter() {
630            const OUTER: GroupTable<'static> = GroupTable::new(
631                Tag(453),
632                Tag(802),
633                &[Tag(452), Tag(802)],
634                &[NO_PARTY_SUB_IDS],
635            );
636            let message = message("35=D|453=2|802=1|523=A|452=1|802=1|523=B|54=1|");
637            let walk = message.scope().walk_group(&OUTER, &KNOWN).unwrap();
638
639            assert!(walk.anomalies().is_empty());
640            let [first, second] = walk.instances() else {
641                panic!("expected two instances");
642            };
643            assert_eq!((text(first, 523), text(first, 452)), (Some("A"), Some("1")));
644            assert_eq!((text(second, 523), text(second, 452)), (Some("B"), None));
645        }
646
647        #[test]
648        fn an_unknown_tag_stays_in_its_instance() {
649            let message = message("35=D|453=2|448=AL|5001=x|452=1|448=BOB|54=1|");
650            let walk = walk_parties(&message);
651
652            assert!(walk.anomalies().is_empty());
653            let first = &walk.instances()[0];
654            assert_eq!(
655                (text(first, 5001), text(first, 452)),
656                (Some("x"), Some("1"))
657            );
658        }
659
660        #[test]
661        fn check_sum_ends_a_group_at_the_end_of_the_body() {
662            let message = message("35=D|453=1|448=AL|");
663            let walk = walk_parties(&message);
664
665            assert_eq!(walk.instances().len(), 1);
666            assert_eq!(walk.instances()[0].get(Tag(10)), None);
667        }
668
669        #[test]
670        fn a_zero_count_is_an_empty_group() {
671            let message = message("35=D|453=0|54=1|");
672            let walk = walk_parties(&message);
673
674            assert_eq!(walk.declared_count(), Some(0));
675            assert!(walk.instances().is_empty());
676            assert!(walk.anomalies().is_empty());
677        }
678    }
679
680    mod anomalies {
681        use super::*;
682
683        #[test]
684        fn an_invalid_count_is_reported() {
685            let message = message("35=D|453=x|448=AL|54=1|");
686            let walk = walk_parties(&message);
687
688            assert_eq!(walk.declared_count(), None);
689            assert_eq!(walk.anomalies(), [Anomaly::InvalidCount]);
690            assert_eq!(walk.instances().len(), 1);
691        }
692
693        #[test]
694        fn a_count_mismatch_is_reported() {
695            let message = message("35=D|453=3|448=AL|448=BOB|54=1|");
696            let walk = walk_parties(&message);
697
698            assert_eq!(
699                walk.anomalies(),
700                [Anomaly::CountMismatch {
701                    declared: 3,
702                    found: 2,
703                }]
704            );
705        }
706
707        #[test]
708        fn a_reordered_instance_is_kept_whole() {
709            let message = message("35=D|453=1|452=1|448=AL|54=1|");
710            let walk = walk_parties(&message);
711
712            assert_eq!(
713                walk.anomalies(),
714                [Anomaly::MissingDelimiter { tag: Tag(452) }]
715            );
716            let [instance] = walk.instances() else {
717                panic!("expected one instance");
718            };
719            assert_eq!(
720                (text(instance, 452), text(instance, 448)),
721                (Some("1"), Some("AL"))
722            );
723        }
724
725        #[test]
726        fn a_repeated_tag_starts_a_new_instance() {
727            let message = message("35=D|453=2|448=AL|452=1|452=3|54=1|");
728            let walk = walk_parties(&message);
729
730            assert_eq!(
731                walk.anomalies(),
732                [Anomaly::MissingDelimiter { tag: Tag(452) }]
733            );
734            let [first, second] = walk.instances() else {
735                panic!("expected two instances");
736            };
737            assert_eq!(text(first, 452), Some("1"));
738            assert_eq!((text(second, 452), text(second, 448)), (Some("3"), None));
739        }
740    }
741
742    mod contract {
743        use super::*;
744
745        #[test]
746        fn an_absent_group_is_none() {
747            let message = message("35=D|11=X|54=1|");
748            assert!(matches!(message.get_group(&NO_PARTY_IDS, &KNOWN), Ok(None)));
749        }
750
751        #[test]
752        fn a_well_formed_group_reads_its_instances() {
753            let message = message("35=D|453=2|448=AL|452=1|448=BOB|54=1|");
754            let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
755
756            assert_eq!(group.len(), 2);
757            let parties: Vec<(Option<&str>, Option<&str>)> = group
758                .iter()
759                .map(|instance| (text(&instance, 448), text(&instance, 452)))
760                .collect();
761            assert_eq!(parties, [(Some("AL"), Some("1")), (Some("BOB"), None)]);
762        }
763
764        #[test]
765        fn a_zero_count_is_an_empty_group() {
766            let message = message("35=D|453=0|54=1|");
767            let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
768
769            assert!(group.is_empty());
770        }
771
772        #[test]
773        fn any_anomaly_is_an_error_on_the_count_tag() {
774            let malformed = [
775                "35=D|453=x|448=AL|54=1|",
776                "35=D|453=3|448=AL|448=BOB|54=1|",
777                "35=D|453=1|452=1|448=AL|54=1|",
778            ];
779            for body in malformed {
780                let message = message(body);
781                assert_eq!(
782                    message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap_err(),
783                    InvalidValue { tag: Tag(453) },
784                    "{body}"
785                );
786            }
787        }
788
789        #[test]
790        fn a_nested_group_is_read_from_its_instance() {
791            let message = message("35=D|453=1|448=AL|802=2|523=S1|523=S2|54=1|");
792            let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
793            let instance = group.iter().next().unwrap();
794            let nested = instance
795                .get_group(&NO_PARTY_SUB_IDS, &KNOWN)
796                .unwrap()
797                .unwrap();
798
799            let sub_ids: Vec<Option<&str>> = nested.iter().map(|sub| text(&sub, 523)).collect();
800            assert_eq!(sub_ids, [Some("S1"), Some("S2")]);
801        }
802    }
803
804    mod instances {
805        use super::*;
806
807        /// An instance type as codegen would write it.
808        #[derive(Clone, Copy, Debug)]
809        struct Party<'a>(Scope<'a>);
810
811        impl<'a> From<Scope<'a>> for Party<'a> {
812            fn from(scope: Scope<'a>) -> Self {
813                Self(scope)
814            }
815        }
816
817        impl<'a> Party<'a> {
818            fn party_id(&self) -> Option<&'a str> {
819                text(&self.0, 448)
820            }
821        }
822
823        fn parties(message: &RawMessage) -> Instances<'_, Party<'_>> {
824            Instances::from(message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap())
825        }
826
827        #[test]
828        fn reads_each_instance_through_its_type() {
829            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
830            let parties = parties(&message);
831
832            assert_eq!(parties.len(), 2);
833            let ids: Vec<Option<&str>> = parties.iter().map(|party| party.party_id()).collect();
834            assert_eq!(ids, [Some("AL"), Some("BOB")]);
835        }
836
837        #[test]
838        fn an_absent_group_has_no_instances() {
839            let message = message("35=D|11=X|54=1|");
840            let parties = parties(&message);
841
842            assert!(parties.is_empty());
843            assert_eq!(parties.iter().count(), 0);
844        }
845
846        #[test]
847        fn get_reads_one_instance_by_position() {
848            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
849            let parties = parties(&message);
850
851            assert_eq!(parties.get(1).unwrap().party_id(), Some("BOB"));
852            assert!(parties.get(2).is_none());
853        }
854
855        #[test]
856        fn iterates_by_reference() {
857            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
858            let parties = parties(&message);
859
860            let mut ids = Vec::new();
861            for party in &parties {
862                ids.push(party.party_id());
863            }
864            assert_eq!(ids, [Some("AL"), Some("BOB")]);
865        }
866
867        #[test]
868        fn the_iterator_knows_its_length() {
869            let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
870            let parties = parties(&message);
871
872            let mut iter = parties.iter();
873            assert_eq!(iter.len(), 2);
874            iter.next();
875            assert_eq!(iter.len(), 1);
876        }
877
878        #[test]
879        fn default_is_empty() {
880            let parties: Instances<'_, Party<'_>> = Instances::default();
881            assert!(parties.is_empty());
882        }
883
884        #[test]
885        fn a_nested_group_is_read_through_an_instance_scope() {
886            let message = message("35=D|453=1|448=AL|802=2|523=S1|523=S2|54=1|");
887            let parties = parties(&message);
888            let party = parties.get(0).unwrap();
889
890            let sub_ids: Instances<'_, Scope<'_>> =
891                Instances::from(party.0.get_group(&NO_PARTY_SUB_IDS, &KNOWN).unwrap());
892            let values: Vec<Option<&str>> = sub_ids.iter().map(|sub| text(&sub, 523)).collect();
893            assert_eq!(values, [Some("S1"), Some("S2")]);
894        }
895    }
896
897    mod tables {
898        use super::*;
899
900        #[test]
901        #[should_panic(expected = "group members must be sorted and unique")]
902        fn unsorted_members_are_rejected() {
903            GroupTable::new(Tag(453), Tag(448), &[Tag(452), Tag(448)], &[]);
904        }
905
906        #[test]
907        #[should_panic(expected = "group members must include the delimiter")]
908        fn members_without_the_delimiter_are_rejected() {
909            GroupTable::new(Tag(453), Tag(448), &[Tag(452)], &[]);
910        }
911
912        #[test]
913        #[should_panic(expected = "group members must include every nested count tag")]
914        fn members_without_a_nested_count_tag_are_rejected() {
915            GroupTable::new(Tag(453), Tag(448), &[Tag(448)], &[NO_PARTY_SUB_IDS]);
916        }
917
918        #[test]
919        #[should_panic(expected = "known tags must be sorted and unique")]
920        fn duplicate_known_tags_are_rejected() {
921            KnownTags::new(&[Tag(35), Tag(35)]);
922        }
923    }
924
925    mod lazy {
926        use super::*;
927
928        static SUB_IDS: LazyKnownTags = LazyKnownTags::new(&[Tag(523)], &[]);
929        static PARTIES: LazyKnownTags =
930            LazyKnownTags::new(&[Tag(448), Tag(802), Tag(447)], &[&SUB_IDS]);
931        static ORDER: LazyKnownTags =
932            LazyKnownTags::new(&[Tag(453), Tag(55), Tag(448)], &[&PARTIES]);
933
934        #[test]
935        fn merges_its_own_tags_with_its_parts_at_any_depth() {
936            assert_eq!(
937                ORDER.get().0,
938                [Tag(55), Tag(447), Tag(448), Tag(453), Tag(523), Tag(802)]
939            );
940        }
941
942        #[test]
943        fn every_call_returns_the_same_list() {
944            assert!(std::ptr::eq(PARTIES.get().0, PARTIES.get().0));
945        }
946    }
947
948    mod owned {
949        use super::*;
950
951        fn owned(
952            count_tag: u32,
953            delimiter: u32,
954            members: &[u32],
955            nested: Vec<OwnedGroupTable>,
956        ) -> Result<OwnedGroupTable, GroupTableError> {
957            let members = members.iter().map(|&tag| Tag(tag)).collect();
958            OwnedGroupTable::new(Tag(count_tag), Tag(delimiter), members, nested)
959        }
960
961        fn party_sub_ids() -> OwnedGroupTable {
962            owned(802, 523, &[523, 803], vec![]).unwrap()
963        }
964
965        fn parties() -> OwnedGroupTable {
966            owned(453, 448, &[447, 448, 452, 802], vec![party_sub_ids()]).unwrap()
967        }
968
969        #[test]
970        fn walks_like_its_const_twin() {
971            fn ids<'a>(group: &Group<'a>) -> Vec<Option<&'a str>> {
972                group.iter().map(|party| text(&party, 448)).collect()
973            }
974            let message = message("35=D|453=2|448=AL|802=2|523=S1|523=S2|448=BOB|54=1|");
975
976            let owned = message.get_group(&parties(), &KNOWN).unwrap().unwrap();
977            let borrowed = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
978            assert_eq!(ids(&owned), ids(&borrowed));
979            assert_eq!(ids(&owned), [Some("AL"), Some("BOB")]);
980
981            let first = owned.iter().next().unwrap();
982            let sub_ids = first.get_group(&party_sub_ids(), &KNOWN).unwrap().unwrap();
983            let sub_ids: Vec<Option<&str>> = sub_ids.iter().map(|sub| text(&sub, 523)).collect();
984            assert_eq!(sub_ids, [Some("S1"), Some("S2")]);
985        }
986
987        #[test]
988        fn unsorted_or_duplicate_members_are_an_error() {
989            assert_eq!(
990                owned(453, 448, &[448, 447], vec![]).unwrap_err(),
991                GroupTableError::UnsortedMembers
992            );
993            assert_eq!(
994                owned(453, 448, &[448, 448], vec![]).unwrap_err(),
995                GroupTableError::UnsortedMembers
996            );
997        }
998
999        #[test]
1000        fn a_delimiter_outside_the_members_is_an_error() {
1001            assert_eq!(
1002                owned(453, 448, &[447], vec![]).unwrap_err(),
1003                GroupTableError::DelimiterNotMember {
1004                    delimiter: Tag(448)
1005                }
1006            );
1007        }
1008
1009        #[test]
1010        fn a_nested_count_tag_outside_the_members_is_an_error() {
1011            assert_eq!(
1012                owned(453, 448, &[448], vec![party_sub_ids()]).unwrap_err(),
1013                GroupTableError::NestedCountNotMember {
1014                    count_tag: Tag(802)
1015                }
1016            );
1017        }
1018
1019        #[test]
1020        fn errors_name_the_broken_rule() {
1021            assert_eq!(
1022                GroupTableError::NestedCountNotMember {
1023                    count_tag: Tag(802)
1024                }
1025                .to_string(),
1026                "group members must include the nested count tag 802"
1027            );
1028        }
1029    }
1030}