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;
9
10const CHECK_SUM: Tag = Tag(10);
12
13#[derive(Clone, Copy, Debug)]
18pub struct GroupTable<'a> {
19 count_tag: Tag,
20 delimiter: Tag,
21 members: &'a [Tag],
22 nested: &'a [GroupTable<'a>],
23}
24
25impl<'a> GroupTable<'a> {
26 pub const fn new(
35 count_tag: Tag,
36 delimiter: Tag,
37 members: &'a [Tag],
38 nested: &'a [GroupTable<'a>],
39 ) -> Self {
40 assert!(
41 is_sorted_set(members),
42 "group members must be sorted and unique"
43 );
44 assert!(
45 contains(members, delimiter),
46 "group members must include the delimiter"
47 );
48 let mut index = 0;
49 while index < nested.len() {
50 assert!(
51 contains(members, nested[index].count_tag),
52 "group members must include every nested count tag"
53 );
54 index += 1;
55 }
56 Self {
57 count_tag,
58 delimiter,
59 members,
60 nested,
61 }
62 }
63}
64
65pub trait GroupLayout: Layout {}
70
71mod layout {
72 use crate::Tag;
73
74 pub trait Layout {
76 fn count_tag(&self) -> Tag;
77 fn delimiter(&self) -> Tag;
78 fn is_member(&self, tag: Tag) -> bool;
79 fn nested_counted_by(&self, tag: Tag) -> Option<&Self>;
80 }
81}
82
83#[derive(Clone, Debug)]
85pub struct OwnedGroupTable {
86 count_tag: Tag,
87 delimiter: Tag,
88 members: Vec<Tag>,
89 nested: Vec<OwnedGroupTable>,
90}
91
92impl OwnedGroupTable {
93 pub fn new(
98 count_tag: Tag,
99 delimiter: Tag,
100 members: Vec<Tag>,
101 nested: Vec<OwnedGroupTable>,
102 ) -> Result<Self, GroupTableError> {
103 if !is_sorted_set(&members) {
104 return Err(GroupTableError::UnsortedMembers);
105 }
106 if !contains(&members, delimiter) {
107 return Err(GroupTableError::DelimiterNotMember { delimiter });
108 }
109 if let Some(nested) = nested
110 .iter()
111 .find(|nested| !contains(&members, nested.count_tag))
112 {
113 return Err(GroupTableError::NestedCountNotMember {
114 count_tag: nested.count_tag,
115 });
116 }
117 Ok(Self {
118 count_tag,
119 delimiter,
120 members,
121 nested,
122 })
123 }
124}
125
126impl GroupLayout for GroupTable<'_> {}
127
128impl GroupLayout for OwnedGroupTable {}
129
130impl Layout for GroupTable<'_> {
131 fn count_tag(&self) -> Tag {
132 self.count_tag
133 }
134
135 fn delimiter(&self) -> Tag {
136 self.delimiter
137 }
138
139 fn is_member(&self, tag: Tag) -> bool {
140 self.members.binary_search(&tag).is_ok()
141 }
142
143 fn nested_counted_by(&self, tag: Tag) -> Option<&Self> {
144 self.nested.iter().find(|nested| nested.count_tag == tag)
145 }
146}
147
148impl Layout for OwnedGroupTable {
149 fn count_tag(&self) -> Tag {
150 self.count_tag
151 }
152
153 fn delimiter(&self) -> Tag {
154 self.delimiter
155 }
156
157 fn is_member(&self, tag: Tag) -> bool {
158 self.members.binary_search(&tag).is_ok()
159 }
160
161 fn nested_counted_by(&self, tag: Tag) -> Option<&Self> {
162 self.nested.iter().find(|nested| nested.count_tag == tag)
163 }
164}
165
166#[derive(Clone, Copy, Debug)]
168pub struct KnownTags<'a>(&'a [Tag]);
169
170impl<'a> KnownTags<'a> {
171 pub const fn new(tags: &'a [Tag]) -> Self {
176 assert!(is_sorted_set(tags), "known tags must be sorted and unique");
177 Self(tags)
178 }
179
180 fn contains(&self, tag: Tag) -> bool {
181 self.0.binary_search(&tag).is_ok()
182 }
183}
184
185#[derive(Clone, Debug)]
187pub struct Walk<'a> {
188 declared_count: Option<usize>,
189 instances: Vec<Scope<'a>>,
190 anomalies: Vec<Anomaly>,
191}
192
193impl<'a> Walk<'a> {
194 pub fn declared_count(&self) -> Option<usize> {
196 self.declared_count
197 }
198
199 pub fn instances(&self) -> &[Scope<'a>] {
201 &self.instances
202 }
203
204 pub fn anomalies(&self) -> &[Anomaly] {
206 &self.anomalies
207 }
208}
209
210#[derive(Clone, Copy, Debug, Eq, PartialEq)]
212pub enum Anomaly {
213 InvalidCount,
215 MissingDelimiter { tag: Tag },
217 CountMismatch { declared: usize, found: usize },
219}
220
221#[derive(Clone, Debug)]
223pub struct Group<'a> {
224 instances: Vec<Scope<'a>>,
225}
226
227impl<'a> Group<'a> {
228 pub fn len(&self) -> usize {
230 self.instances.len()
231 }
232
233 pub fn is_empty(&self) -> bool {
235 self.instances.is_empty()
236 }
237
238 pub fn iter(&self) -> impl Iterator<Item = Scope<'a>> {
240 self.instances.iter().copied()
241 }
242}
243
244pub struct Instances<'a, T> {
251 instances: Vec<Scope<'a>>,
252 instance: PhantomData<fn() -> T>,
253}
254
255impl<T> Instances<'_, T> {
256 pub fn len(&self) -> usize {
258 self.instances.len()
259 }
260
261 pub fn is_empty(&self) -> bool {
263 self.instances.is_empty()
264 }
265}
266
267impl<'a, T: From<Scope<'a>>> Instances<'a, T> {
268 pub fn get(&self, index: usize) -> Option<T> {
270 self.instances.get(index).copied().map(T::from)
271 }
272
273 pub fn iter(&self) -> Iter<'_, 'a, T> {
275 Iter {
276 scopes: self.instances.iter(),
277 instance: PhantomData,
278 }
279 }
280}
281
282impl<'a, T> From<Option<Group<'a>>> for Instances<'a, T> {
283 fn from(group: Option<Group<'a>>) -> Self {
284 Self {
285 instances: group.map(|group| group.instances).unwrap_or_default(),
286 instance: PhantomData,
287 }
288 }
289}
290
291impl<T> Default for Instances<'_, T> {
292 fn default() -> Self {
293 Self {
294 instances: Vec::new(),
295 instance: PhantomData,
296 }
297 }
298}
299
300impl<T> Clone for Instances<'_, T> {
301 fn clone(&self) -> Self {
302 Self {
303 instances: self.instances.clone(),
304 instance: PhantomData,
305 }
306 }
307}
308
309impl<T> fmt::Debug for Instances<'_, T> {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 f.debug_list().entries(&self.instances).finish()
312 }
313}
314
315impl<'i, 'a, T: From<Scope<'a>>> IntoIterator for &'i Instances<'a, T> {
316 type Item = T;
317 type IntoIter = Iter<'i, 'a, T>;
318
319 fn into_iter(self) -> Self::IntoIter {
320 self.iter()
321 }
322}
323
324pub struct Iter<'i, 'a, T> {
326 scopes: std::slice::Iter<'i, Scope<'a>>,
327 instance: PhantomData<fn() -> T>,
328}
329
330impl<'a, T: From<Scope<'a>>> Iterator for Iter<'_, 'a, T> {
331 type Item = T;
332
333 fn next(&mut self) -> Option<T> {
334 self.scopes.next().copied().map(T::from)
335 }
336
337 fn size_hint(&self) -> (usize, Option<usize>) {
338 self.scopes.size_hint()
339 }
340}
341
342impl<'a, T: From<Scope<'a>>> ExactSizeIterator for Iter<'_, 'a, T> {}
343
344impl RawMessage {
345 pub fn get_group(
347 &self,
348 table: &impl GroupLayout,
349 known: &KnownTags<'_>,
350 ) -> Result<Option<Group<'_>>, InvalidValue> {
351 self.scope().get_group(table, known)
352 }
353}
354
355impl<'a> Scope<'a> {
356 pub fn walk_group(&self, table: &impl GroupLayout, known: &KnownTags<'_>) -> Option<Walk<'a>> {
364 let (count_slot, _) = self.find(table.count_tag(), self.start())?;
365 Some(walk(self, count_slot, table, known).0)
366 }
367
368 pub fn get_group(
374 &self,
375 table: &impl GroupLayout,
376 known: &KnownTags<'_>,
377 ) -> Result<Option<Group<'a>>, InvalidValue> {
378 let Some(walk) = self.walk_group(table, known) else {
379 return Ok(None);
380 };
381 if !walk.anomalies.is_empty() {
382 return Err(InvalidValue {
383 tag: table.count_tag(),
384 });
385 }
386 Ok(Some(Group {
387 instances: walk.instances,
388 }))
389 }
390}
391
392fn walk<'a, L: GroupLayout>(
395 scope: &Scope<'a>,
396 count_slot: Slot,
397 table: &L,
398 known: &KnownTags<'_>,
399) -> (Walk<'a>, Slot) {
400 let declared_count = parse_count(scope.value_at(count_slot));
401 let mut anomalies = Vec::new();
402 if declared_count.is_none() {
403 anomalies.push(Anomaly::InvalidCount);
404 }
405
406 let mut instances = Vec::new();
407 let mut instance_start = None;
408 let mut seen = Vec::new();
409 let mut slot = count_slot.next();
410 while slot < scope.end() {
411 let tag = scope.tag_at(slot);
412 if tag == CHECK_SUM {
413 break;
414 }
415 if table.is_member(tag) {
416 if instance_start.is_none() || seen.contains(&tag) {
417 if let Some(start) = instance_start {
418 instances.push(scope.narrow(start, slot));
419 }
420 if tag != table.delimiter() {
421 anomalies.push(Anomaly::MissingDelimiter { tag });
422 }
423 instance_start = Some(slot);
424 seen.clear();
425 }
426 seen.push(tag);
427 slot = match table.nested_counted_by(tag) {
428 Some(nested) => walk(scope, slot, nested, known).1,
429 None => slot.next(),
430 };
431 } else if known.contains(tag) {
432 break;
433 } else {
434 slot = slot.next();
435 }
436 }
437 if let Some(start) = instance_start {
438 instances.push(scope.narrow(start, slot));
439 }
440
441 if let Some(declared) = declared_count
442 && declared != instances.len()
443 {
444 anomalies.push(Anomaly::CountMismatch {
445 declared,
446 found: instances.len(),
447 });
448 }
449
450 let walk = Walk {
451 declared_count,
452 instances,
453 anomalies,
454 };
455 (walk, slot)
456}
457
458fn parse_count(value: &[u8]) -> Option<usize> {
460 std::str::from_utf8(value).ok()?.parse().ok()
461}
462
463const fn is_sorted_set(tags: &[Tag]) -> bool {
465 let mut index = 1;
466 while index < tags.len() {
467 if tags[index - 1].0 >= tags[index].0 {
468 return false;
469 }
470 index += 1;
471 }
472 true
473}
474
475const fn contains(tags: &[Tag], tag: Tag) -> bool {
477 let mut index = 0;
478 while index < tags.len() {
479 if tags[index].0 == tag.0 {
480 return true;
481 }
482 index += 1;
483 }
484 false
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490 use crate::test_utils::construct_valid_frame;
491 use crate::{RawMessage, Tokenizer};
492 use bytes::Bytes;
493
494 const NO_PARTY_SUB_IDS: GroupTable<'static> =
495 GroupTable::new(Tag(802), Tag(523), &[Tag(523), Tag(803)], &[]);
496
497 const NO_PARTY_IDS: GroupTable<'static> = GroupTable::new(
498 Tag(453),
499 Tag(448),
500 &[Tag(447), Tag(448), Tag(452), Tag(802)],
501 &[NO_PARTY_SUB_IDS],
502 );
503
504 const KNOWN: KnownTags<'static> = KnownTags::new(&[
505 Tag(11),
506 Tag(35),
507 Tag(54),
508 Tag(447),
509 Tag(448),
510 Tag(452),
511 Tag(453),
512 Tag(523),
513 Tag(802),
514 Tag(803),
515 ]);
516
517 fn message(body: &str) -> RawMessage {
519 let frame = construct_valid_frame("FIX.4.4", body);
520 Tokenizer::default().tokenize(Bytes::from(frame)).unwrap()
521 }
522
523 fn walk_parties(message: &RawMessage) -> Walk<'_> {
524 message.scope().walk_group(&NO_PARTY_IDS, &KNOWN).unwrap()
525 }
526
527 fn text<'a>(scope: &Scope<'a>, tag: u32) -> Option<&'a str> {
528 scope.get_str(Tag(tag)).unwrap()
529 }
530
531 mod structure {
532 use super::*;
533
534 #[test]
535 fn an_absent_group_walks_to_nothing() {
536 let message = message("35=D|11=X|54=1|");
537 assert!(message.scope().walk_group(&NO_PARTY_IDS, &KNOWN).is_none());
538 }
539
540 #[test]
541 fn finds_each_instance() {
542 let message = message("35=D|453=2|448=AL|452=1|448=BOB|452=3|54=1|");
543 let walk = walk_parties(&message);
544
545 assert_eq!(walk.declared_count(), Some(2));
546 assert!(walk.anomalies().is_empty());
547 let [first, second] = walk.instances() else {
548 panic!("expected two instances");
549 };
550 assert_eq!(
551 (text(first, 448), text(first, 452)),
552 (Some("AL"), Some("1"))
553 );
554 assert_eq!(
555 (text(second, 448), text(second, 452)),
556 (Some("BOB"), Some("3"))
557 );
558 assert_eq!(text(second, 54), None);
559 }
560
561 #[test]
562 fn a_missing_optional_field_does_not_read_the_next_instance() {
563 let message = message("35=D|453=2|448=AL|448=BOB|452=3|54=1|");
564 let walk = walk_parties(&message);
565
566 assert_eq!(text(&walk.instances()[0], 452), None);
567 }
568
569 #[test]
570 fn a_nested_group_stays_inside_its_instance() {
571 let message = message("35=D|453=2|448=AL|802=1|523=S1|452=1|448=BOB|452=3|54=1|");
572 let walk = walk_parties(&message);
573
574 assert!(walk.anomalies().is_empty());
575 let [first, second] = walk.instances() else {
576 panic!("expected two instances");
577 };
578 assert_eq!(text(first, 452), Some("1"));
579 let nested = first.walk_group(&NO_PARTY_SUB_IDS, &KNOWN).unwrap();
580 assert_eq!(nested.instances().len(), 1);
581 assert_eq!(text(&nested.instances()[0], 523), Some("S1"));
582 assert!(second.walk_group(&NO_PARTY_SUB_IDS, &KNOWN).is_none());
583 }
584
585 #[test]
586 fn a_nested_group_can_be_the_delimiter() {
587 const OUTER: GroupTable<'static> = GroupTable::new(
588 Tag(453),
589 Tag(802),
590 &[Tag(452), Tag(802)],
591 &[NO_PARTY_SUB_IDS],
592 );
593 let message = message("35=D|453=2|802=1|523=A|452=1|802=1|523=B|54=1|");
594 let walk = message.scope().walk_group(&OUTER, &KNOWN).unwrap();
595
596 assert!(walk.anomalies().is_empty());
597 let [first, second] = walk.instances() else {
598 panic!("expected two instances");
599 };
600 assert_eq!((text(first, 523), text(first, 452)), (Some("A"), Some("1")));
601 assert_eq!((text(second, 523), text(second, 452)), (Some("B"), None));
602 }
603
604 #[test]
605 fn an_unknown_tag_stays_in_its_instance() {
606 let message = message("35=D|453=2|448=AL|5001=x|452=1|448=BOB|54=1|");
607 let walk = walk_parties(&message);
608
609 assert!(walk.anomalies().is_empty());
610 let first = &walk.instances()[0];
611 assert_eq!(
612 (text(first, 5001), text(first, 452)),
613 (Some("x"), Some("1"))
614 );
615 }
616
617 #[test]
618 fn check_sum_ends_a_group_at_the_end_of_the_body() {
619 let message = message("35=D|453=1|448=AL|");
620 let walk = walk_parties(&message);
621
622 assert_eq!(walk.instances().len(), 1);
623 assert_eq!(walk.instances()[0].get(Tag(10)), None);
624 }
625
626 #[test]
627 fn a_zero_count_is_an_empty_group() {
628 let message = message("35=D|453=0|54=1|");
629 let walk = walk_parties(&message);
630
631 assert_eq!(walk.declared_count(), Some(0));
632 assert!(walk.instances().is_empty());
633 assert!(walk.anomalies().is_empty());
634 }
635 }
636
637 mod anomalies {
638 use super::*;
639
640 #[test]
641 fn an_invalid_count_is_reported() {
642 let message = message("35=D|453=x|448=AL|54=1|");
643 let walk = walk_parties(&message);
644
645 assert_eq!(walk.declared_count(), None);
646 assert_eq!(walk.anomalies(), [Anomaly::InvalidCount]);
647 assert_eq!(walk.instances().len(), 1);
648 }
649
650 #[test]
651 fn a_count_mismatch_is_reported() {
652 let message = message("35=D|453=3|448=AL|448=BOB|54=1|");
653 let walk = walk_parties(&message);
654
655 assert_eq!(
656 walk.anomalies(),
657 [Anomaly::CountMismatch {
658 declared: 3,
659 found: 2,
660 }]
661 );
662 }
663
664 #[test]
665 fn a_reordered_instance_is_kept_whole() {
666 let message = message("35=D|453=1|452=1|448=AL|54=1|");
667 let walk = walk_parties(&message);
668
669 assert_eq!(
670 walk.anomalies(),
671 [Anomaly::MissingDelimiter { tag: Tag(452) }]
672 );
673 let [instance] = walk.instances() else {
674 panic!("expected one instance");
675 };
676 assert_eq!(
677 (text(instance, 452), text(instance, 448)),
678 (Some("1"), Some("AL"))
679 );
680 }
681
682 #[test]
683 fn a_repeated_tag_starts_a_new_instance() {
684 let message = message("35=D|453=2|448=AL|452=1|452=3|54=1|");
685 let walk = walk_parties(&message);
686
687 assert_eq!(
688 walk.anomalies(),
689 [Anomaly::MissingDelimiter { tag: Tag(452) }]
690 );
691 let [first, second] = walk.instances() else {
692 panic!("expected two instances");
693 };
694 assert_eq!(text(first, 452), Some("1"));
695 assert_eq!((text(second, 452), text(second, 448)), (Some("3"), None));
696 }
697 }
698
699 mod contract {
700 use super::*;
701
702 #[test]
703 fn an_absent_group_is_none() {
704 let message = message("35=D|11=X|54=1|");
705 assert!(matches!(message.get_group(&NO_PARTY_IDS, &KNOWN), Ok(None)));
706 }
707
708 #[test]
709 fn a_well_formed_group_reads_its_instances() {
710 let message = message("35=D|453=2|448=AL|452=1|448=BOB|54=1|");
711 let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
712
713 assert_eq!(group.len(), 2);
714 let parties: Vec<(Option<&str>, Option<&str>)> = group
715 .iter()
716 .map(|instance| (text(&instance, 448), text(&instance, 452)))
717 .collect();
718 assert_eq!(parties, [(Some("AL"), Some("1")), (Some("BOB"), None)]);
719 }
720
721 #[test]
722 fn a_zero_count_is_an_empty_group() {
723 let message = message("35=D|453=0|54=1|");
724 let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
725
726 assert!(group.is_empty());
727 }
728
729 #[test]
730 fn any_anomaly_is_an_error_on_the_count_tag() {
731 let malformed = [
732 "35=D|453=x|448=AL|54=1|",
733 "35=D|453=3|448=AL|448=BOB|54=1|",
734 "35=D|453=1|452=1|448=AL|54=1|",
735 ];
736 for body in malformed {
737 let message = message(body);
738 assert_eq!(
739 message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap_err(),
740 InvalidValue { tag: Tag(453) },
741 "{body}"
742 );
743 }
744 }
745
746 #[test]
747 fn a_nested_group_is_read_from_its_instance() {
748 let message = message("35=D|453=1|448=AL|802=2|523=S1|523=S2|54=1|");
749 let group = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
750 let instance = group.iter().next().unwrap();
751 let nested = instance
752 .get_group(&NO_PARTY_SUB_IDS, &KNOWN)
753 .unwrap()
754 .unwrap();
755
756 let sub_ids: Vec<Option<&str>> = nested.iter().map(|sub| text(&sub, 523)).collect();
757 assert_eq!(sub_ids, [Some("S1"), Some("S2")]);
758 }
759 }
760
761 mod instances {
762 use super::*;
763
764 #[derive(Clone, Copy, Debug)]
766 struct Party<'a>(Scope<'a>);
767
768 impl<'a> From<Scope<'a>> for Party<'a> {
769 fn from(scope: Scope<'a>) -> Self {
770 Self(scope)
771 }
772 }
773
774 impl<'a> Party<'a> {
775 fn party_id(&self) -> Option<&'a str> {
776 text(&self.0, 448)
777 }
778 }
779
780 fn parties(message: &RawMessage) -> Instances<'_, Party<'_>> {
781 Instances::from(message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap())
782 }
783
784 #[test]
785 fn reads_each_instance_through_its_type() {
786 let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
787 let parties = parties(&message);
788
789 assert_eq!(parties.len(), 2);
790 let ids: Vec<Option<&str>> = parties.iter().map(|party| party.party_id()).collect();
791 assert_eq!(ids, [Some("AL"), Some("BOB")]);
792 }
793
794 #[test]
795 fn an_absent_group_has_no_instances() {
796 let message = message("35=D|11=X|54=1|");
797 let parties = parties(&message);
798
799 assert!(parties.is_empty());
800 assert_eq!(parties.iter().count(), 0);
801 }
802
803 #[test]
804 fn get_reads_one_instance_by_position() {
805 let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
806 let parties = parties(&message);
807
808 assert_eq!(parties.get(1).unwrap().party_id(), Some("BOB"));
809 assert!(parties.get(2).is_none());
810 }
811
812 #[test]
813 fn iterates_by_reference() {
814 let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
815 let parties = parties(&message);
816
817 let mut ids = Vec::new();
818 for party in &parties {
819 ids.push(party.party_id());
820 }
821 assert_eq!(ids, [Some("AL"), Some("BOB")]);
822 }
823
824 #[test]
825 fn the_iterator_knows_its_length() {
826 let message = message("35=D|453=2|448=AL|448=BOB|54=1|");
827 let parties = parties(&message);
828
829 let mut iter = parties.iter();
830 assert_eq!(iter.len(), 2);
831 iter.next();
832 assert_eq!(iter.len(), 1);
833 }
834
835 #[test]
836 fn default_is_empty() {
837 let parties: Instances<'_, Party<'_>> = Instances::default();
838 assert!(parties.is_empty());
839 }
840
841 #[test]
842 fn a_nested_group_is_read_through_an_instance_scope() {
843 let message = message("35=D|453=1|448=AL|802=2|523=S1|523=S2|54=1|");
844 let parties = parties(&message);
845 let party = parties.get(0).unwrap();
846
847 let sub_ids: Instances<'_, Scope<'_>> =
848 Instances::from(party.0.get_group(&NO_PARTY_SUB_IDS, &KNOWN).unwrap());
849 let values: Vec<Option<&str>> = sub_ids.iter().map(|sub| text(&sub, 523)).collect();
850 assert_eq!(values, [Some("S1"), Some("S2")]);
851 }
852 }
853
854 mod tables {
855 use super::*;
856
857 #[test]
858 #[should_panic(expected = "group members must be sorted and unique")]
859 fn unsorted_members_are_rejected() {
860 GroupTable::new(Tag(453), Tag(448), &[Tag(452), Tag(448)], &[]);
861 }
862
863 #[test]
864 #[should_panic(expected = "group members must include the delimiter")]
865 fn members_without_the_delimiter_are_rejected() {
866 GroupTable::new(Tag(453), Tag(448), &[Tag(452)], &[]);
867 }
868
869 #[test]
870 #[should_panic(expected = "group members must include every nested count tag")]
871 fn members_without_a_nested_count_tag_are_rejected() {
872 GroupTable::new(Tag(453), Tag(448), &[Tag(448)], &[NO_PARTY_SUB_IDS]);
873 }
874
875 #[test]
876 #[should_panic(expected = "known tags must be sorted and unique")]
877 fn duplicate_known_tags_are_rejected() {
878 KnownTags::new(&[Tag(35), Tag(35)]);
879 }
880 }
881
882 mod owned {
883 use super::*;
884
885 fn owned(
886 count_tag: u32,
887 delimiter: u32,
888 members: &[u32],
889 nested: Vec<OwnedGroupTable>,
890 ) -> Result<OwnedGroupTable, GroupTableError> {
891 let members = members.iter().map(|&tag| Tag(tag)).collect();
892 OwnedGroupTable::new(Tag(count_tag), Tag(delimiter), members, nested)
893 }
894
895 fn party_sub_ids() -> OwnedGroupTable {
896 owned(802, 523, &[523, 803], vec![]).unwrap()
897 }
898
899 fn parties() -> OwnedGroupTable {
900 owned(453, 448, &[447, 448, 452, 802], vec![party_sub_ids()]).unwrap()
901 }
902
903 #[test]
904 fn walks_like_its_const_twin() {
905 fn ids<'a>(group: &Group<'a>) -> Vec<Option<&'a str>> {
906 group.iter().map(|party| text(&party, 448)).collect()
907 }
908 let message = message("35=D|453=2|448=AL|802=2|523=S1|523=S2|448=BOB|54=1|");
909
910 let owned = message.get_group(&parties(), &KNOWN).unwrap().unwrap();
911 let borrowed = message.get_group(&NO_PARTY_IDS, &KNOWN).unwrap().unwrap();
912 assert_eq!(ids(&owned), ids(&borrowed));
913 assert_eq!(ids(&owned), [Some("AL"), Some("BOB")]);
914
915 let first = owned.iter().next().unwrap();
916 let sub_ids = first.get_group(&party_sub_ids(), &KNOWN).unwrap().unwrap();
917 let sub_ids: Vec<Option<&str>> = sub_ids.iter().map(|sub| text(&sub, 523)).collect();
918 assert_eq!(sub_ids, [Some("S1"), Some("S2")]);
919 }
920
921 #[test]
922 fn unsorted_or_duplicate_members_are_an_error() {
923 assert_eq!(
924 owned(453, 448, &[448, 447], vec![]).unwrap_err(),
925 GroupTableError::UnsortedMembers
926 );
927 assert_eq!(
928 owned(453, 448, &[448, 448], vec![]).unwrap_err(),
929 GroupTableError::UnsortedMembers
930 );
931 }
932
933 #[test]
934 fn a_delimiter_outside_the_members_is_an_error() {
935 assert_eq!(
936 owned(453, 448, &[447], vec![]).unwrap_err(),
937 GroupTableError::DelimiterNotMember {
938 delimiter: Tag(448)
939 }
940 );
941 }
942
943 #[test]
944 fn a_nested_count_tag_outside_the_members_is_an_error() {
945 assert_eq!(
946 owned(453, 448, &[448], vec![party_sub_ids()]).unwrap_err(),
947 GroupTableError::NestedCountNotMember {
948 count_tag: Tag(802)
949 }
950 );
951 }
952
953 #[test]
954 fn errors_name_the_broken_rule() {
955 assert_eq!(
956 GroupTableError::NestedCountNotMember {
957 count_tag: Tag(802)
958 }
959 .to_string(),
960 "group members must include the nested count tag 802"
961 );
962 }
963 }
964}