fixer 0.11.0

A full featured messaging engine for the FIX protocol implemented in Rust
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
use delegate::delegate;
use quick_xml::de::from_reader;
use simple_error::{SimpleError, SimpleResult};
use rustc_hash::FxHashMap;
use std::{
    collections::HashSet,
    fmt,
    io::BufRead,
};
use tokio::fs::File;
use tokio::io::AsyncReadExt;

pub mod build;
pub mod xml;

// MessagePart can represent a Field, Repeating Group, or Component
#[derive(Clone, Eq)]
pub enum MessagePart {
    FieldDef(FieldDef),
    FieldType(FieldType),
    ComponentType(ComponentType),
    Component(Component),
}

impl Default for MessagePart {
    fn default() -> Self {
        MessagePart::FieldDef(FieldDef::default())
    }
}

impl MessagePart {
    pub fn name(&self) -> &str {
        match self {
            Self::FieldDef(fd) => fd.name(),
            Self::FieldType(ft) => ft.name(),
            Self::ComponentType(ct) => ct.name(),
            Self::Component(c) => c.name(),
        }
    }

    pub fn required(&self) -> bool {
        match self {
            Self::FieldDef(fd) => fd.required(),
            Self::FieldType(ft) => ft.required(),
            Self::ComponentType(ct) => ct.required(),
            Self::Component(c) => c.required(),
        }
    }

    pub fn fields(&self) -> Option<&Vec<FieldDef>> {
        match self {
            Self::FieldDef(_) | Self::FieldType(_) => None,
            Self::ComponentType(ct) => Some(ct.fields()),
            Self::Component(c) => Some(c.fields()),
        }
    }

    // required_fields returns those fields that are required for this component
    pub fn required_fields(&self) -> Option<&Vec<FieldDef>> {
        match self {
            Self::FieldDef(fd) => Some(fd.required_fields()),
            Self::FieldType(_) => None,
            Self::ComponentType(ct) => Some(ct.required_fields()),
            Self::Component(c) => Some(c.required_fields()),
        }
    }
}

impl fmt::Debug for MessagePart {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "name: {}, required: {}", self.name(), self.required())
    }
}

impl PartialEq for MessagePart {
    fn eq(&self, other: &Self) -> bool {
        self.name() == other.name() && self.required() == other.required()
    }
}

#[derive(Default, Debug, Clone, PartialEq, Eq)]
// ComponentType is a grouping of fields.
pub struct ComponentType {
    name: String,
    parts: Vec<MessagePart>,
    fields: Vec<FieldDef>,
    required_fields: Vec<FieldDef>,
    required_parts: Vec<MessagePart>,
}

impl ComponentType {
    // new returns an initialized ComponentType
    pub fn new(name: String, parts: Vec<MessagePart>) -> Self {
        let mut comp = ComponentType {
            name,
            parts,
            ..Default::default()
        };

        for part in &comp.parts {
            if part.required() {
                comp.required_parts.push(part.clone());
            }

            match part {
                MessagePart::FieldDef(fd) => {
                    comp.fields.push(fd.clone());
                    if part.required() {
                        comp.required_fields.push(fd.clone());
                    }
                }
                MessagePart::FieldType(_) => {}
                MessagePart::ComponentType(ct) => {
                    comp.fields.extend_from_slice(ct.fields());
                    if ct.required() {
                        comp.required_fields.extend_from_slice(ct.required_fields());
                    }
                }
                MessagePart::Component(c) => {
                    comp.fields.extend_from_slice(c.fields());
                    if c.required() {
                        comp.required_fields.extend_from_slice(c.required_fields());
                    }
                }
            }
        }
        comp
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn required(&self) -> bool {
        false
    }

    // required_parts returns those parts that are required for this component
    pub fn required_parts(&self) -> &Vec<MessagePart> {
        &self.required_parts
    }

    // parts returns all parts in declaration order contained in this component
    pub fn parts(&self) -> &Vec<MessagePart> {
        &self.parts
    }

    // fields returns all fields contained in this component.
    // Includes fields encapsulated in components of this component
    pub fn fields(&self) -> &Vec<FieldDef> {
        &self.fields
    }

    // required_fields returns those fields that are required for this component
    pub fn required_fields(&self) -> &Vec<FieldDef> {
        &self.required_fields
    }
}

// TagSet is set for tags.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct TagSet(pub HashSet<isize>);

// add adds a tag to the tagset.
impl TagSet {
    pub fn new() -> Self {
        TagSet(hashset!())
    }

    pub fn add(&mut self, tag: isize) {
        self.0.insert(tag);
    }
}

// Component is a Component as it appears in a given MessageDef
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct Component {
    pub component_type: ComponentType,
    pub required: bool,
}

impl Component {
    // new returns an initialized Component instance
    pub fn new(component_type: ComponentType, required: bool) -> Self {
        Component {
            component_type,
            required,
        }
    }

    pub fn required(&self) -> bool {
        self.required
    }

    delegate! {
        to self.component_type {
            pub fn name(&self) -> &str;
            pub fn fields(&self) -> &Vec<FieldDef>;
            pub fn required_fields(&self) -> &Vec<FieldDef>;
        }
    }
}

// FieldDef models a field belonging to a message.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct FieldDef {
    field_type: FieldType,
    required: bool,
    pub parts: Vec<MessagePart>,
    pub fields: Vec<FieldDef>,
    required_parts: Vec<MessagePart>,
    required_fields: Vec<FieldDef>,
}

impl FieldDef {
    // new returns an initialized FieldDef
    pub fn new(field_type: FieldType, required: bool) -> Self {
        FieldDef {
            field_type,
            required,
            ..Default::default()
        }
    }

    // new_group returns an initialized FieldDef for a repeating group
    pub fn new_group(field_type: FieldType, required: bool, parts: Vec<MessagePart>) -> FieldDef {
        let mut field = FieldDef {
            field_type,
            required,
            parts,
            ..Default::default()
        };

        for part in &field.parts {
            if part.required() {
                field.required_parts.push(part.clone());
            }

            match part {
                MessagePart::FieldDef(fd) => {
                    field.fields.push(fd.clone());
                    if part.required() {
                        field.required_fields.push(fd.clone());
                    }
                }
                MessagePart::Component(c) => {
                    field.fields.extend_from_slice(c.fields());
                    if c.required() {
                        field.required_fields.extend_from_slice(c.required_fields());
                    }
                }
                _ => {}
            }
        }
        field
    }

    delegate! {
        to self.field_type {
            pub fn name(&self) -> &str;
            pub fn tag(&self) -> isize;
        }
    }

    // required returns true if this FieldDef is required for the containing MessageDef
    pub fn required(&self) -> bool {
        self.required
    }

    // is_group is true if the field is a repeating group.
    pub fn is_group(&self) -> bool {
        !self.fields.is_empty()
    }

    // required_parts returns those parts that are required for this FieldDef.
    // is_group must return true
    pub fn required_parts(&self) -> &Vec<MessagePart> {
        &self.required_parts
    }

    // required_fields returns those fields that are required for this FieldDef.
    // is_group must return true
    pub fn required_fields(&self) -> &Vec<FieldDef> {
        &self.required_fields
    }

    pub fn child_tags(&self) -> Vec<isize> {
        let mut tags = vec![];

        for field in &self.fields {
            tags.push(field.tag());
            tags.extend(field.child_tags());
        }

        tags
    }
}

// FieldType holds information relating to a field.  Includes Tag, type, and enums, if defined.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct FieldType {
    name: String,
    tag: isize,
    pub r#type: String,
    pub enums: FxHashMap<String, Enum>,
}

impl FieldType {
    // new returns an initialized FieldType
    pub fn new(name: String, tag: isize, fix_type: String) -> Self {
        FieldType {
            name,
            tag,
            r#type: fix_type,
            enums: hashmap! {},
        }
    }

    // name returns the name of this component type
    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn required(&self) -> bool {
        false // will be overriden
    }

    pub fn tag(&self) -> isize {
        self.tag
    }
}

// Enum is a container for value and description.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct Enum {
    pub value: String,
    pub description: String,
}

// MessageDef can apply to header, trailer, or body of a FIX Message.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct MessageDef {
    pub name: String,
    pub msg_type: String,
    pub fields: FxHashMap<isize, FieldDef>,
    // Parts are the MessageParts of contained in this MessageDef in declaration order
    pub parts: Vec<MessagePart>,
    pub required_parts: Vec<MessagePart>,
    pub required_tags: TagSet,
    pub tags: TagSet,
}

impl MessageDef {
    // new returns an initialized MessageDef
    pub fn new(name: String, msg_type: String, parts: Vec<MessagePart>) -> Self {
        let mut msg = MessageDef {
            name,
            msg_type,
            fields: hashmap! {},
            required_tags: TagSet(hashset! {}),
            tags: TagSet(hashset! {}),
            parts,
            required_parts: vec![],
        };

        let mut process_field = |field: &FieldDef, allow_required: bool| {
            let tag = field.tag();
            msg.fields.insert(tag, field.clone());
            msg.tags.add(tag);
            for t in field.child_tags() {
                msg.tags.add(t);
            }

            if allow_required && field.required() {
                msg.required_tags.add(tag);
            }
        };

        for part in &msg.parts {
            if part.required() {
                msg.required_parts.push(part.clone());
            }

            match part {
                MessagePart::FieldDef(fd) => {
                    process_field(fd, true);
                }

                MessagePart::ComponentType(ct) => {
                    for f in ct.fields() {
                        process_field(f, ct.required());
                    }
                }
                MessagePart::Component(c) => {
                    for f in c.fields() {
                        process_field(f, c.required());
                    }
                }
                MessagePart::FieldType(_) => {}
            }
        }
        msg
    }

    // required_parts returns those parts that are required for this Message
    pub fn required_parts(&self) -> &Vec<MessagePart> {
        &self.required_parts
    }
}

// DataDictionary models FIX messages, components, and fields.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct DataDictionary {
    pub fix_type: String,
    pub major: isize,
    pub minor: isize,
    pub service_pack: isize,
    pub field_type_by_tag: FxHashMap<isize, FieldType>,
    pub field_type_by_name: FxHashMap<String, FieldType>,
    pub messages: FxHashMap<String, MessageDef>,
    pub component_types: FxHashMap<String, ComponentType>,
    pub header: MessageDef,
    pub trailer: MessageDef,
}

impl DataDictionary {
    // parse loads and build a datadictionary instance from an xml file.
    pub async fn parse(path: &str) -> SimpleResult<Self> {
        let mut file = File::open(path).await.map_err(SimpleError::from)?;

        let mut contents = vec![];
        map_err_with!(
            file.read_to_end(&mut contents).await,
            "problem opening file: {}",
            path
        )?;

        Self::parse_src(&*contents)
    }

    // parse_src loads and build a datadictionary instance from an xml source.
    pub fn parse_src<R: BufRead>(xml_src: R) -> SimpleResult<Self> {
        let xml_doc: xml::XMLDoc = map_err_with!(from_reader(xml_src), "problem parsing XML file")?;

        let mut builder = build::Builder::default();
        let dict = builder.build(&xml_doc)?;

        Ok(dict)
    }
}

#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod component_type_tests {
    use super::*;

    #[test]
    fn test_new_component_type() {
        let ft1 = FieldType::new(String::from("aname1"), 11, String::from("INT"));
        let ft2 = FieldType::new(String::from("aname2"), 12, String::from("INT"));

        let optional_field1 = FieldDef::new(ft1.clone(), false);
        let required_field1 = FieldDef::new(ft1.clone(), true);
        let optional_field2 = FieldDef::new(ft2.clone(), false);
        let required_field2 = FieldDef::new(ft2.clone(), true);

        let required_comp1 = Component::new(
            ComponentType::new(
                String::from("comp1"),
                vec![MessagePart::FieldDef(required_field1.clone())],
            ),
            true,
        );

        let optional_comp1 = Component::new(
            ComponentType::new(
                String::from("comp1"),
                vec![MessagePart::FieldDef(required_field1.clone())],
            ),
            false,
        );

        struct TestCase {
            test_name: String,
            parts: Vec<MessagePart>,
            expected_fields: Vec<FieldDef>,
            expected_required_parts: Vec<MessagePart>,
            expected_required_fields: Vec<FieldDef>,
        }

        let tests = [
            TestCase {
                test_name: String::from("test1"),
                parts: vec![MessagePart::FieldDef(optional_field1.clone())],
                expected_fields: vec![optional_field1.clone()],
                expected_required_parts: vec![],
                expected_required_fields: vec![],
            },
            TestCase {
                test_name: String::from("test2"),
                parts: vec![MessagePart::FieldDef(required_field1.clone())],
                expected_fields: vec![required_field1.clone()],
                expected_required_fields: vec![required_field1.clone()],
                expected_required_parts: vec![MessagePart::FieldDef(required_field1.clone())],
            },
            TestCase {
                test_name: String::from("test3"),
                parts: vec![
                    MessagePart::FieldDef(required_field1.clone()),
                    MessagePart::FieldDef(optional_field2.clone()),
                ],
                expected_fields: vec![required_field1.clone(), optional_field2.clone()],
                expected_required_fields: vec![required_field1.clone()],
                expected_required_parts: vec![MessagePart::FieldDef(required_field1.clone())],
            },
            TestCase {
                test_name: String::from("test4"),
                parts: vec![
                    MessagePart::FieldDef(required_field2.clone()),
                    MessagePart::Component(optional_comp1.clone()),
                ],
                expected_fields: vec![required_field2.clone(), required_field1.clone()],
                expected_required_fields: vec![required_field2.clone()],
                expected_required_parts: vec![MessagePart::FieldDef(required_field2.clone())],
            },
            TestCase {
                test_name: String::from("test5"),
                parts: vec![
                    MessagePart::FieldDef(required_field2.clone()),
                    MessagePart::Component(required_comp1.clone()),
                ],
                expected_fields: vec![required_field2.clone(), required_field1.clone()],
                expected_required_fields: vec![required_field2.clone(), required_field1.clone()],
                expected_required_parts: vec![
                    MessagePart::FieldDef(required_field2.clone()),
                    MessagePart::Component(required_comp1.clone()),
                ],
            },
        ];

        for test in &tests {
            let ct = ComponentType::new(String::from("cname"), test.parts.clone());

            assert_eq!(String::from("cname"), ct.name(), "{}", test.test_name);
            assert_eq!(&test.expected_fields, ct.fields(), "{}", test.test_name);
            assert_eq!(&test.parts, ct.parts(), "{}", test.test_name);
            assert_eq!(
                &test.expected_required_fields,
                ct.required_fields(),
                "{}",
                test.test_name,
            );
            assert_eq!(
                &test.expected_required_parts,
                ct.required_parts(),
                "{}",
                test.test_name,
            );
        }
    }
}

#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod tests {
    use super::*;
    use futures::executor::block_on;
    use std::sync::LazyLock;

    #[tokio::test]
    async fn test_parse_bad_path() {
        let result = DataDictionary::parse("../../spec/bogus.xml").await;
        assert!(result.is_err(), "Expected err");
    }

    #[tokio::test]
    async fn test_parse_recursive_components() {
        let result = DataDictionary::parse("../spec/FIX44.xml").await;
        assert!(result.is_ok(), "Unexpected err: {result:?}");
        assert!(result.is_ok(), "Dictionary is nil");
    }

    // global variable
    static DICT: LazyLock<DataDictionary> = LazyLock::new(|| {
        block_on(async { DataDictionary::parse("../spec/FIX43.xml").await.unwrap() })
    });

    #[tokio::test]
    async fn test_components() {
        let d = DICT.clone();
        assert!(
            d.component_types.contains_key("SpreadOrBenchmarkCurveData"),
            "Component not found"
        );
    }

    #[tokio::test]
    async fn test_fields_by_tag() {
        let d = DICT.clone();

        struct TestCase<'a> {
            tag: isize,
            name: &'a str,
            r#type: &'a str,
            enums_are_nil: bool,
        }

        let tests = [
            TestCase {
                tag: 655,
                name: "ContraLegRefID",
                r#type: "STRING",
                enums_are_nil: true,
            },
            TestCase {
                tag: 658,
                name: "QuoteRequestRejectReason",
                r#type: "INT",
                enums_are_nil: false,
            },
        ];

        for test in &tests {
            assert!(
                d.field_type_by_tag.contains_key(&test.tag),
                "{} not found",
                test.tag
            );

            let f = d.field_type_by_tag.get(&test.tag).unwrap();

            assert_eq!(
                f.name(),
                test.name,
                "Expected {} got {}",
                test.name,
                f.name()
            );

            assert_eq!(
                f.r#type, test.r#type,
                "Expected {} got {}",
                test.r#type, f.r#type
            );
            assert!(
                f.enums.is_empty() || !test.enums_are_nil,
                "Expected no enums"
            );

            assert!(!f.enums.is_empty() || test.enums_are_nil, "Expected enums");
        }
    }

    #[tokio::test]
    async fn test_enum_fields_by_tag() {
        let d = DICT.clone();

        let f = d.field_type_by_tag.get(&658).unwrap();

        struct TestCase<'a> {
            value: &'a str,
            description: &'a str,
        }

        let tests = [
            TestCase {
                value: "1",
                description: "UNKNOWN_SYMBOL",
            },
            TestCase {
                value: "2",
                description: "EXCHANGE",
            },
            TestCase {
                value: "3",
                description: "QUOTE_REQUEST_EXCEEDS_LIMIT",
            },
            TestCase {
                value: "4",
                description: "TOO_LATE_TO_ENTER",
            },
            TestCase {
                value: "5",
                description: "INVALID_PRICE",
            },
            TestCase {
                value: "6",
                description: "NOT_AUTHORIZED_TO_REQUEST_QUOTE",
            },
        ];

        assert_eq!(
            f.enums.len(),
            tests.len(),
            "Expected {} enums got {}",
            tests.len(),
            f.enums.len()
        );

        for test in &tests {
            assert!(
                f.enums.contains_key(test.value),
                "Expected Enum {}",
                test.value
            );

            let r#enum = f.enums.get(test.value).unwrap();
            assert_eq!(
                r#enum.value, test.value,
                "Expected value {} got {}",
                test.value, r#enum.value
            );

            assert_eq!(
                r#enum.description, test.description,
                "Expected value {} got {}",
                test.description, r#enum.description
            );
        }
    }

    #[tokio::test]
    async fn test_data_dictionary_messages() {
        let d = DICT.clone();
        assert!(d.messages.contains_key("D"), "Did not find message");
    }

    #[tokio::test]
    async fn test_data_dictionary_header() {
        // no need to test header existence as it's not Option
    }

    #[tokio::test]
    async fn test_data_dictionary_trailer() {
        // no need to test trailer existence as it's not Option
    }

    #[tokio::test]
    async fn test_message_required_tags() {
        let d = DICT.clone();

        let nos = d.messages.get("D").unwrap();

        struct TestCase {
            message_def: MessageDef,
            tag: isize,
            required: bool,
        }

        let tests = [
            TestCase {
                message_def: nos.clone(),
                tag: 11,
                required: true,
            },
            TestCase {
                message_def: nos.clone(),
                tag: 526,
                required: false,
            },
            TestCase {
                message_def: d.header.clone(),
                tag: 8,
                required: true,
            },
            TestCase {
                message_def: d.header.clone(),
                tag: 115,
                required: false,
            },
            TestCase {
                message_def: d.trailer.clone(),
                tag: 10,
                required: true,
            },
            TestCase {
                message_def: d.trailer.clone(),
                tag: 89,
                required: false,
            },
        ];

        for test in &tests {
            let TagSet(inner_tag) = &test.message_def.required_tags;
            let required = inner_tag.contains(&test.tag);
            assert!(
                !required || test.required,
                "{} should not be required",
                &test.tag
            );
            assert!(
                required || !test.required,
                "{} should not required",
                &test.tag
            );
        }
    }

    #[tokio::test]
    async fn test_message_tags() {
        let d = DICT.clone();

        let nos = d.messages.get("D").unwrap();

        struct TestCase {
            message_def: MessageDef,
            tag: isize,
        }

        let tests = [
            TestCase {
                message_def: nos.clone(),
                tag: 11,
            },
            TestCase {
                message_def: nos.clone(),
                tag: 526,
            },
            TestCase {
                message_def: d.header.clone(),
                tag: 8,
            },
            TestCase {
                message_def: d.header.clone(),
                tag: 115,
            },
            TestCase {
                message_def: d.trailer.clone(),
                tag: 10,
            },
            TestCase {
                message_def: d.trailer.clone(),
                tag: 89,
            },
        ];

        for test in &tests {
            let TagSet(inner_tag) = &test.message_def.tags;
            assert!(inner_tag.contains(&test.tag), "{} is not known", &test.tag);
        }
    }
}

#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod field_def_tests {
    use super::*;

    #[test]
    fn test_new_field_def() {
        let ft = FieldType::new(String::from("aname"), 11, String::from("INT"));

        struct TestCase {
            required: bool,
        }

        let tests = [TestCase { required: true }];

        for test in &tests {
            let fd = FieldDef::new(ft.clone(), test.required);
            assert!(!fd.is_group(), "field def is not a group");
            assert_eq!("aname", fd.name());
            assert_eq!(test.required, fd.required());
        }
    }
}

#[cfg(test)]
mod field_type_tests {
    use super::*;

    #[test]
    fn test_new_field_type() {
        let ft = FieldType::new(String::from("myname"), 10, String::from("STRING"));
        assert_eq!(String::from("myname"), ft.name());
        assert_eq!(10, ft.tag());
        assert_eq!("STRING", ft.r#type);
    }
}

#[cfg(test)]
mod group_field_def_tests {
    use super::*;

    #[test]
    fn test_new_group_field() {
        let ft = FieldType::new(String::from("aname"), 11, String::from("INT"));
        let fg = FieldDef::new_group(ft, true, vec![]);
        assert_eq!(String::from("aname"), fg.name());
        assert!(fg.required());
    }
}

#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod message_def_tests {
    use super::*;

    #[test]
    fn test_new_message_def() {
        let ft1 = FieldType::new(String::from("type1"), 11, String::from("STRING"));
        let ft2 = FieldType::new(String::from("type2"), 12, String::from("STRING"));
        let ft3 = FieldType::new(String::from("type3"), 13, String::from("INT"));

        let optionalfd1 = FieldDef::new(ft1.clone(), false);
        let requiredfd1 = FieldDef::new(ft1.clone(), true);

        let optionalfd2 = FieldDef::new(ft2.clone(), false);
        //	let requiredfd2 = FieldDef::new(ft2.clone(), true);

        let optional_group1 = FieldDef::new_group(
            ft3.clone(),
            false,
            vec![
                MessagePart::FieldDef(requiredfd1.clone()),
                MessagePart::FieldDef(optionalfd2.clone()),
            ],
        );
        let required_group1 = FieldDef::new_group(
            ft3.clone(),
            true,
            vec![
                MessagePart::FieldDef(requiredfd1.clone()),
                MessagePart::FieldDef(optionalfd2.clone()),
            ],
        );

        let ct1 = ComponentType::new(
            String::from("ct1"),
            vec![MessagePart::FieldDef(required_group1.clone())],
        );

        let optional_comp1 = Component::new(ct1.clone(), false);

        struct TestCase {
            parts: Vec<MessagePart>,
            expected_tags: TagSet,
            expected_required_tags: TagSet,
            expected_required_parts: Vec<MessagePart>,
        }

        let tests = [
            TestCase {
                parts: vec![],
                expected_tags: TagSet(hashset! {}),
                expected_required_tags: TagSet(hashset! {}),
                expected_required_parts: vec![],
            },
            TestCase {
                parts: vec![MessagePart::FieldDef(optionalfd1.clone())],
                expected_tags: TagSet(hashset! {11 }),
                expected_required_tags: TagSet(hashset! {}),
                expected_required_parts: vec![],
            },
            TestCase {
                parts: vec![
                    MessagePart::FieldDef(requiredfd1.clone()),
                    MessagePart::FieldDef(optionalfd2.clone()),
                ],
                expected_tags: TagSet(hashset! {11, 12 }),
                expected_required_tags: TagSet(hashset! {11 }),
                expected_required_parts: vec![MessagePart::FieldDef(requiredfd1.clone())],
            },
            TestCase {
                parts: vec![MessagePart::FieldDef(optional_group1.clone())],
                expected_tags: TagSet(hashset! {11, 12, 13 }),
                expected_required_tags: TagSet(hashset! {}),
                expected_required_parts: vec![],
            },
            TestCase {
                parts: vec![MessagePart::FieldDef(required_group1.clone())],
                expected_tags: TagSet(hashset! {11, 12, 13 }),
                expected_required_tags: TagSet(hashset! {13 }),
                expected_required_parts: vec![MessagePart::FieldDef(required_group1.clone())],
            },
            TestCase {
                parts: vec![MessagePart::Component(optional_comp1.clone())],
                expected_tags: TagSet(hashset! {11, 12, 13 }),
                expected_required_tags: TagSet(hashset! {}),
                expected_required_parts: vec![],
            },
        ];

        for test in &tests {
            let md = MessageDef::new(
                String::from("some message"),
                String::from("X"),
                test.parts.clone(),
            );

            assert_eq!(String::from("some message"), md.name);
            assert_eq!(String::from("X"), md.msg_type);
            assert_eq!(test.expected_tags, md.tags);
            assert_eq!(test.expected_required_tags, md.required_tags);
            assert_eq!(test.parts, md.parts);
            assert_eq!(&test.expected_required_parts, md.required_parts());
        }
    }
}