fefix 0.7.0

FIX & FAST (FIX Adapted for STreaming) in pure 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
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
//! Access to FIX Dictionary reference and message specifications.

#![allow(dead_code)]

use self::symbol_table::{Key, KeyRef, SymbolTable, SymbolTableIndex};
use super::TagU16;
use fnv::FnvHashMap;
use quickfix::{ParseDictionaryError, QuickFixReader};
use std::fmt;
use std::sync::Arc;

pub use datatype::FixDatatype;

/// The expected location of a field within a FIX message (i.e. header, body, or
/// trailer).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum FieldLocation {
    /// The field is located inside the "Standard Header".
    Header,
    /// This field is located inside the body of the FIX message.
    Body,
    /// This field is located inside the "Standard Trailer".
    Trailer,
}

type InternalId = u32;

/// Specifies business semantics for application-level entities within the FIX
/// Protocol.
///
/// You can rely on [`Dictionary`] for accessing details about
/// fields, messages, and other abstract entities as defined in the FIX
/// specifications. Examples of such information include:
///
/// - The mapping of FIX field names to numeric tags (e.g. `BeginString` is 8).
/// - Which FIX fields are mandatory and which are optional.
/// - The data type of each and every FIX field.
/// - What fields to expect in FIX headers.
///
/// N.B. The FIX Protocol mandates separation of concerns between session and
/// application protocol only for FIX 5.0 and subsequent versions. All FIX
/// Dictionaries for older versions will also contain information about the
/// session layer.
#[derive(Clone, Debug)]
pub struct Dictionary {
    inner: Arc<DictionaryData>,
}

#[derive(Clone, Debug)]
struct DictionaryData {
    version: String,
    symbol_table: SymbolTable,
    abbreviations: Vec<AbbreviationData>,
    data_types: Vec<DatatypeData>,
    fields: Vec<FieldData>,
    components: Vec<ComponentData>,
    messages: Vec<MessageData>,
    //layout_items: Vec<LayoutItemData>,
    categories: Vec<CategoryData>,
    header: Vec<FieldData>,
}

impl fmt::Display for Dictionary {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "<fix type='FIX' version='{}'>", self.inner.version)?;
        {
            writeln!(f, " <header>")?;
            let std_header = self.component_by_name("StandardHeader").unwrap();
            for item in std_header.items() {
                display_layout_item(2, item, f)?;
            }
            writeln!(f, " </header>")?;
        }
        {
            writeln!(f, " <messages>")?;
            for message in self.iter_messages() {
                writeln!(
                    f,
                    "  <message name='{}' msgtype='{}' msgcat='{}'>",
                    message.name(),
                    message.msg_type(),
                    "TODO"
                )?;
                for item in message.layout() {
                    display_layout_item(2, item, f)?;
                }
                writeln!(f, "  </message>")?;
            }
            writeln!(f, " </messages>")?;
        }
        {
            writeln!(f, " <header>")?;
            let std_header = self.component_by_name("StandardTrailer").unwrap();
            for item in std_header.items() {
                display_layout_item(2, item, f)?;
            }
            writeln!(f, " </header>")?;
        }
        Ok(())
    }
}

fn display_layout_item(indent: u32, item: LayoutItem, f: &mut fmt::Formatter) -> fmt::Result {
    for _ in 0..indent {
        write!(f, " ")?;
    }
    match item.kind() {
        LayoutItemKind::Field(_) => {
            writeln!(
                f,
                "<field name='{}' required='{}' />",
                item.tag_text(),
                item.required(),
            )?;
        }
        LayoutItemKind::Group(_, _fields) => {
            writeln!(
                f,
                "<group name='{}' required='{}' />",
                item.tag_text(),
                item.required(),
            )?;
            writeln!(f, "</group>")?;
        }
        LayoutItemKind::Component(_c) => {
            writeln!(
                f,
                "<component name='{}' required='{}' />",
                item.tag_text(),
                item.required(),
            )?;
            writeln!(f, "</component>")?;
        }
    }
    Ok(())
}

impl DictionaryData {
    fn symbol(&self, pkey: KeyRef) -> Option<&u32> {
        self.symbol_table.get(&pkey as &dyn SymbolTableIndex)
    }
}

impl Dictionary {
    /// Creates a new empty FIX Dictionary named `version`.
    fn new<S: ToString>(version: S) -> Self {
        Dictionary {
            inner: Arc::new(DictionaryData {
                version: version.to_string(),
                symbol_table: FnvHashMap::default(),
                abbreviations: Vec::new(),
                data_types: Vec::new(),
                fields: Vec::new(),
                components: Vec::new(),
                messages: Vec::new(),
                //layout_items: Vec::new(),
                categories: Vec::new(),
                header: Vec::new(),
            }),
        }
    }

    /// Attempts to read a QuickFIX-style specification file and convert it into
    /// a [`Dictionary`].
    pub fn from_quickfix_spec<S: AsRef<str>>(input: S) -> Result<Self, ParseDictionaryError> {
        let xml_document = roxmltree::Document::parse(input.as_ref())
            .map_err(|_| ParseDictionaryError::InvalidFormat)?;
        QuickFixReader::new(&xml_document)
    }

    /// Creates a new empty FIX Dictionary with `FIX.???` as its version string.
    pub fn empty() -> Self {
        Self::new("FIX.???")
    }

    /// Returns the version string associated with this [`Dictionary`] (e.g.
    /// `FIXT.1.1`, `FIX.4.2`).
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    /// assert_eq!(dict.get_version(), "FIX.4.4");
    /// ```
    pub fn get_version(&self) -> &str {
        self.inner.version.as_str()
    }

    /// Creates a new [`Dictionary`] for FIX 4.0.
    #[cfg(feature = "fix40")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix40")))]
    pub fn fix40() -> Self {
        let spec = include_str!("resources/quickfix/FIX-4.0.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 4.1.
    #[cfg(feature = "fix41")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix41")))]
    pub fn fix41() -> Self {
        let spec = include_str!("resources/quickfix/FIX-4.1.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 4.2.
    #[cfg(feature = "fix42")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix42")))]
    pub fn fix42() -> Self {
        let spec = include_str!("resources/quickfix/FIX-4.2.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 4.3.
    #[cfg(feature = "fix43")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix43")))]
    pub fn fix43() -> Self {
        let spec = include_str!("resources/quickfix/FIX-4.3.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 4.4.
    pub fn fix44() -> Self {
        let spec = include_str!("resources/quickfix/FIX-4.4.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 5.0.
    #[cfg(feature = "fix50")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix50")))]
    pub fn fix50() -> Self {
        let spec = include_str!("resources/quickfix/FIX-5.0.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 5.0 SP1.
    #[cfg(feature = "fix50sp1")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix50sp1")))]
    pub fn fix50sp1() -> Self {
        let spec = include_str!("resources/quickfix/FIX-5.0-SP1.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIX 5.0 SP2.
    #[cfg(feature = "fix50sp2")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix50sp1")))]
    pub fn fix50sp2() -> Self {
        let spec = include_str!("resources/quickfix/FIX-5.0-SP2.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    /// Creates a new [`Dictionary`] for FIXT 1.1.
    #[cfg(feature = "fixt11")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "fixt11")))]
    pub fn fixt11() -> Self {
        let spec = include_str!("resources/quickfix/FIXT-1.1.xml");
        Dictionary::from_quickfix_spec(spec).unwrap()
    }

    #[cfg(test)]
    pub fn all() -> Vec<Dictionary> {
        vec![
            #[cfg(feature = "fix40")]
            Self::fix40(),
            #[cfg(feature = "fix41")]
            Self::fix41(),
            #[cfg(feature = "fix42")]
            Self::fix42(),
            #[cfg(feature = "fix43")]
            Self::fix43(),
            Self::fix44(),
            #[cfg(feature = "fix50")]
            Self::fix50(),
            #[cfg(feature = "fix50sp1")]
            Self::fix50sp1(),
            #[cfg(feature = "fix50sp2")]
            Self::fix50sp2(),
            #[cfg(feature = "fixt11")]
            Self::fixt11(),
        ]
    }

    fn symbol(&self, pkey: KeyRef) -> Option<&u32> {
        self.inner.symbol(pkey)
    }

    /// Return the known abbreviation for `term` -if any- according to the
    /// documentation of this FIX Dictionary.
    pub fn abbreviation_for<S: AsRef<str>>(&self, term: S) -> Option<Abbreviation> {
        self.symbol(KeyRef::Abbreviation(term.as_ref()))
            .map(|iid| self.inner.abbreviations.get(*iid as usize).unwrap())
            .map(move |data| Abbreviation(self, data))
    }

    /// Returns the [`Message`](Message) associated with `name`, if any.
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    ///
    /// let msg1 = dict.message_by_name("Heartbeat").unwrap();
    /// let msg2 = dict.message_by_msgtype("0").unwrap();
    /// assert_eq!(msg1.name(), msg2.name());
    /// ```
    pub fn message_by_name<S: AsRef<str>>(&self, name: S) -> Option<Message> {
        self.symbol(KeyRef::MessageByName(name.as_ref()))
            .map(|iid| self.inner.messages.get(*iid as usize).unwrap())
            .map(|data| Message(self, data))
    }

    /// Returns the [`Message`](Message) that has the given `msgtype`, if any.
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    ///
    /// let msg1 = dict.message_by_msgtype("0").unwrap();
    /// let msg2 = dict.message_by_name("Heartbeat").unwrap();
    /// assert_eq!(msg1.name(), msg2.name());
    /// ```
    pub fn message_by_msgtype<S: AsRef<str>>(&self, msgtype: S) -> Option<Message> {
        self.symbol(KeyRef::MessageByMsgType(msgtype.as_ref()))
            .map(|iid| self.inner.messages.get(*iid as usize).unwrap())
            .map(|data| Message(self, data))
    }

    /// Returns the [`Component`] named `name`, if any.
    pub fn component_by_name<S: AsRef<str>>(&self, name: S) -> Option<Component> {
        self.symbol(KeyRef::ComponentByName(name.as_ref()))
            .map(|iid| self.inner.components.get(*iid as usize).unwrap())
            .map(|data| Component(self, data))
    }

    /// Returns the [`Datatype`] named `name`, if any.
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    /// let dt = dict.datatype_by_name("String").unwrap();
    /// assert_eq!(dt.name(), "String");
    /// ```
    pub fn datatype_by_name<S: AsRef<str>>(&self, name: S) -> Option<Datatype> {
        self.symbol(KeyRef::DatatypeByName(name.as_ref()))
            .map(|iid| self.inner.data_types.get(*iid as usize).unwrap())
            .map(|data| Datatype(self, data))
    }

    /// Returns the [`Field`] associated with `tag`, if any.
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    /// let field1 = dict.field_by_tag(112).unwrap();
    /// let field2 = dict.field_by_name("TestReqID").unwrap();
    /// assert_eq!(field1.name(), field2.name());
    /// ```
    pub fn field_by_tag(&self, tag: u32) -> Option<Field> {
        self.symbol(KeyRef::FieldByTag(tag))
            .map(|iid| self.inner.fields.get(*iid as usize).unwrap())
            .map(|data| Field(self, data))
    }

    /// Returns the [`Field`] named `name`, if any.
    pub fn field_by_name<S: AsRef<str>>(&self, name: S) -> Option<Field> {
        self.symbol(KeyRef::FieldByName(name.as_ref()))
            .map(|iid| self.inner.fields.get(*iid as usize).unwrap())
            .map(|data| Field(self, data))
    }

    /// Returns an [`Iterator`] over all [`Datatype`] defined
    /// in `self`. Items are in no particular order.
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    /// // FIX 4.4 defines 23 (FIXME) datatypes.
    /// assert_eq!(dict.iter_datatypes().count(), 23);
    /// ```
    pub fn iter_datatypes(&self) -> impl Iterator<Item = Datatype> {
        self.inner
            .data_types
            .iter()
            .map(move |data| Datatype(self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s messages. Items are in
    /// no particular order.
    ///
    /// ```
    /// use fefix::Dictionary;
    ///
    /// let dict = Dictionary::fix44();
    /// let msg = dict.iter_messages().find(|m| m.name() == "MarketDataRequest");
    /// assert_eq!(msg.unwrap().msg_type(), "V");
    /// ```
    pub fn iter_messages(&self) -> impl Iterator<Item = Message> {
        self.inner
            .messages
            .iter()
            .map(move |data| Message(&self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s categories. Items are
    /// in no particular order.
    pub fn iter_categories(&self) -> impl Iterator<Item = Category> {
        self.inner
            .categories
            .iter()
            .map(move |data| Category(&self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s fields. Items are
    /// in no particular order.
    pub fn iter_fields(&self) -> impl Iterator<Item = Field> {
        self.inner.fields.iter().map(move |data| Field(&self, data))
    }

    /// Returns an [`Iterator`] over this [`Dictionary`]'s components. Items are in
    /// no particular order.
    pub fn iter_components(&self) -> impl Iterator<Item = Component> {
        self.inner
            .components
            .iter()
            .map(move |data| Component(&self, data))
    }
}

struct DictionaryBuilder {
    version: String,
    symbol_table: FnvHashMap<Key, InternalId>,
    abbreviations: Vec<AbbreviationData>,
    data_types: Vec<DatatypeData>,
    fields: Vec<FieldData>,
    components: Vec<ComponentData>,
    messages: Vec<MessageData>,
    //layout_items: Vec<LayoutItemData>,
    categories: Vec<CategoryData>,
    header: Vec<FieldData>,
}

impl DictionaryBuilder {
    pub fn new(version: String) -> Self {
        Self {
            version,
            symbol_table: FnvHashMap::default(),
            abbreviations: Vec::new(),
            data_types: Vec::new(),
            fields: Vec::new(),
            components: Vec::new(),
            messages: Vec::new(),
            //layout_items: Vec::new(),
            categories: Vec::new(),
            header: Vec::new(),
        }
    }

    pub fn symbol(&self, pkey: KeyRef) -> Option<&InternalId> {
        self.symbol_table.get(&pkey as &dyn SymbolTableIndex)
    }

    pub fn add_field(&mut self, field: FieldData) -> InternalId {
        let iid = self.fields.len() as InternalId;
        self.symbol_table
            .insert(Key::FieldByName(field.name.clone()), iid);
        self.symbol_table
            .insert(Key::FieldByTag(field.tag as u32), iid);
        self.fields.push(field);
        iid
    }

    pub fn add_message(&mut self, message: MessageData) -> InternalId {
        let iid = self.messages.len() as InternalId;
        self.symbol_table
            .insert(Key::MessageByName(message.name.clone()), iid);
        self.symbol_table
            .insert(Key::MessageByMsgType(message.msg_type.to_string()), iid);
        self.messages.push(message);
        iid
    }

    pub fn add_component(&mut self, component: ComponentData) -> InternalId {
        let iid = self.components.len() as InternalId;
        self.symbol_table
            .insert(Key::ComponentByName(component.name.to_string()), iid);
        self.components.push(component);
        iid
    }

    pub fn build(self) -> Dictionary {
        Dictionary {
            inner: Arc::new(DictionaryData {
                version: self.version,
                symbol_table: self.symbol_table,
                abbreviations: self.abbreviations,
                data_types: self.data_types,
                fields: self.fields,
                components: self.components,
                messages: self.messages,
                //layout_items: self.layout_items,
                categories: self.categories,
                header: self.header,
            }),
        }
    }
}

#[derive(Clone, Debug)]
struct AbbreviationData {
    abbreviation: String,
    is_last: bool,
}

/// An [`Abbreviation`] is a standardized abbreviated form for a specific word,
/// pattern, or name. Abbreviation data is mostly meant for documentation
/// purposes, but in general it can have other uses as well, e.g. FIXML field
/// naming.
#[derive(Debug)]
pub struct Abbreviation<'a>(&'a Dictionary, &'a AbbreviationData);

impl<'a> Abbreviation<'a> {
    /// Returns the full term (non-abbreviated) associated with `self`.
    pub fn term(&self) -> &str {
        self.1.abbreviation.as_str()
    }
}

#[derive(Clone, Debug)]
struct CategoryData {
    /// **Primary key**. A string uniquely identifying this category.
    name: String,
    /// The FIXML file name for a Category.
    fixml_filename: String,
}

/// A [`Category`] is a collection of loosely related FIX messages or components
/// all belonging to the same [`Section`].
#[derive(Clone, Debug)]
pub struct Category<'a>(&'a Dictionary, &'a CategoryData);

#[derive(Clone, Debug)]
struct ComponentData {
    /// **Primary key.** The unique integer identifier of this component
    /// type.
    id: usize,
    component_type: FixmlComponentAttributes,
    layout_items: Vec<LayoutItemData>,
    category_iid: InternalId,
    /// The human readable name of the component.
    name: String,
    /// The name for this component when used in an XML context.
    abbr_name: Option<String>,
}

/// A [`Component`] is an ordered collection of fields and/or other components.
/// There are two kinds of components: (1) common blocks and (2) repeating
/// groups. Common blocks are merely commonly reused sequences of the same
/// fields/components
/// which are given names for simplicity, i.e. they serve as "macros". Repeating
/// groups, on the other hand, are components which can appear zero or more times
/// inside FIX messages (or other components, for that matter).
#[derive(Clone, Debug)]
pub struct Component<'a>(&'a Dictionary, &'a ComponentData);

impl<'a> Component<'a> {
    /// Returns the unique numberic ID of `self`.
    pub fn id(&self) -> u32 {
        self.1.id as u32
    }

    /// Returns the name of `self`. The name of every [`Component`] is unique
    /// across a [`Dictionary`].
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    /// Returns `true` if and only if `self` is a "group" component; `false`
    /// otherwise.
    pub fn is_group(&self) -> bool {
        match self.1.component_type {
            FixmlComponentAttributes::Block { is_repeating, .. } => is_repeating,
            _ => false,
        }
    }

    /// Returns the [`Category`] to which `self` belongs.
    pub fn category(&self) -> Category {
        let data = self
            .0
            .inner
            .categories
            .get(self.1.category_iid as usize)
            .unwrap();
        Category(self.0, data)
    }

    /// Returns an [`Iterator`] over all items that are part of `self`.
    pub fn items(&self) -> impl Iterator<Item = LayoutItem> {
        self.1
            .layout_items
            .iter()
            .map(move |data| LayoutItem(self.0, data))
    }

    /// Checks whether `field` appears in the definition of `self` and returns
    /// `true` if it does, `false` otherwise.
    pub fn contains_field(&self, field: &Field) -> bool {
        self.items().any(|layout_item| {
            if let LayoutItemKind::Field(f) = layout_item.kind() {
                f.tag() == field.tag()
            } else {
                false
            }
        })
    }
}

/// Component type (FIXML-specific information).
#[derive(Clone, Debug, PartialEq)]
#[allow(dead_code)]
pub enum FixmlComponentAttributes {
    Xml,
    Block {
        is_repeating: bool,
        is_implicit: bool,
        is_optimized: bool,
    },
    Message,
}

#[derive(Clone, Debug, PartialEq)]
struct DatatypeData {
    /// **Primary key.** Identifier of the datatype.
    datatype: FixDatatype,
    /// Human readable description of this Datatype.
    description: String,
    /// A string that contains examples values for a datatype
    examples: Vec<String>,
    // TODO: 'XML'.
}

/// A FIX data type defined as part of a [`Dictionary`].
#[derive(Debug)]
pub struct Datatype<'a>(&'a Dictionary, &'a DatatypeData);

impl<'a> Datatype<'a> {
    /// Returns the name of `self`.  This is also guaranteed to be a valid Rust
    /// identifier.
    pub fn name(&self) -> &str {
        self.1.datatype.name()
    }

    /// Returns `self` as an `enum`.
    pub fn basetype(&self) -> FixDatatype {
        self.1.datatype
    }
}

mod datatype {
    use strum::IntoEnumIterator;
    use strum_macros::{EnumIter, IntoStaticStr};

    /// Sum type for all possible FIX data types ever defined across all FIX
    /// application versions.
    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, EnumIter, IntoStaticStr)]
    #[repr(u8)]
    #[non_exhaustive]
    pub enum FixDatatype {
        /// Single character value, can include any alphanumeric character or
        /// punctuation except the delimiter. All char fields are case sensitive
        /// (i.e. m != M). The following fields are based on char.
        Char,
        /// char field containing one of two values: 'Y' = True/Yes 'N' = False/No.
        Boolean,
        /// Sequence of digits with optional decimal point and sign character (ASCII
        /// characters "-", "0" - "9" and "."); the absence of the decimal point
        /// within the string will be interpreted as the float representation of an
        /// integer value. All float fields must accommodate up to fifteen
        /// significant digits. The number of decimal places used should be a factor
        /// of business/market needs and mutual agreement between counterparties.
        /// Note that float values may contain leading zeros (e.g. "00023.23" =
        /// "23.23") and may contain or omit trailing zeros after the decimal point
        /// (e.g. "23.0" = "23.0000" = "23" = "23."). Note that fields which are
        /// derived from float may contain negative values unless explicitly
        /// specified otherwise. The following data types are based on float.
        Float,
        /// float field typically representing a Price times a Qty.
        Amt,
        /// float field representing a price. Note the number of decimal places may
        /// vary. For certain asset classes prices may be negative values. For
        /// example, prices for options strategies can be negative under certain
        /// market conditions. Refer to Volume 7: FIX Usage by Product for asset
        /// classes that support negative price values.
        Price,
        /// float field representing a price offset, which can be mathematically
        /// added to a "Price". Note the number of decimal places may vary and some
        /// fields such as LastForwardPoints may be negative.
        PriceOffset,
        /// float field capable of storing either a whole number (no decimal places)
        /// of "shares" (securities denominated in whole units) or a decimal value
        /// containing decimal places for non-share quantity asset classes
        /// (securities denominated in fractional units).
        Qty,
        /// float field representing a percentage (e.g. 0.05 represents 5% and 0.9525
        /// represents 95.25%). Note the number of decimal places may vary.
        Percentage,
        /// Sequence of digits without commas or decimals and optional sign character
        /// (ASCII characters "-" and "0" - "9" ). The sign character utilizes one
        /// byte (i.e. positive int is "99999" while negative int is "-99999"). Note
        /// that int values may contain leading zeros (e.g. "00023" = "23").
        /// Examples: 723 in field 21 would be mapped int as |21=723|. -723 in field
        /// 12 would be mapped int as |12=-723| The following data types are based on
        /// int.
        Int,
        /// int field representing a day during a particular monthy (values 1 to 31).
        DayOfMonth,
        /// int field representing the length in bytes. Value must be positive.
        Length,
        /// int field representing the number of entries in a repeating group. Value
        /// must be positive.
        NumInGroup,
        /// int field representing a message sequence number. Value must be positive.
        SeqNum,
        /// `int` field representing a field's tag number when using FIX "Tag=Value"
        /// syntax. Value must be positive and may not contain leading zeros.
        TagNum,
        /// Alpha-numeric free format strings, can include any character or
        /// punctuation except the delimiter. All String fields are case sensitive
        /// (i.e. morstatt != Morstatt).
        String,
        /// string field containing raw data with no format or content restrictions.
        /// Data fields are always immediately preceded by a length field. The length
        /// field should specify the number of bytes of the value of the data field
        /// (up to but not including the terminating SOH). Caution: the value of one
        /// of these fields may contain the delimiter (SOH) character. Note that the
        /// value specified for this field should be followed by the delimiter (SOH)
        /// character as all fields are terminated with an "SOH".
        Data,
        /// string field representing month of a year. An optional day of the month
        /// can be appended or an optional week code. Valid formats: YYYYMM YYYYMMDD
        /// YYYYMMWW Valid values: YYYY = 0000-9999; MM = 01-12; DD = 01-31; WW = w1,
        /// w2, w3, w4, w5.
        MonthYear,
        /// string field containing one or more space delimited single character
        /// values (e.g. |18=2 A F| ).
        MultipleCharValue,
        /// string field representing a currency type using ISO 4217 Currency code (3
        /// character) values (see Appendix 6-A).
        Currency,
        /// string field representing a market or exchange using ISO 10383 Market
        /// Identifier Code (MIC) values (see"Appendix 6-C).
        Exchange,
        /// Identifier for a national language - uses ISO 639-1 standard.
        Language,
        /// string field represening a Date of Local Market (as oppose to UTC) in
        /// YYYYMMDD format. This is the "normal" date field used by the FIX
        /// Protocol. Valid values: YYYY = 0000-9999, MM = 01-12, DD = 01-31.
        LocalMktDate,
        /// string field containing one or more space delimited multiple character
        /// values (e.g. |277=AV AN A| ).
        MultipleStringValue,
        /// string field representing Date represented in UTC (Universal Time
        /// Coordinated, also known as "GMT") in YYYYMMDD format. This
        /// special-purpose field is paired with UTCTimeOnly to form a proper
        /// UTCTimestamp for bandwidth-sensitive messages. Valid values: YYYY =
        /// 0000-9999, MM = 01-12, DD = 01-31.
        UtcDateOnly,
        /// string field representing Time-only represented in UTC (Universal Time
        /// Coordinated, also known as "GMT") in either HH:MM:SS (whole seconds) or
        /// HH:MM:SS.sss (milliseconds) format, colons, and period required. This
        /// special-purpose field is paired with UTCDateOnly to form a proper
        /// UTCTimestamp for bandwidth-sensitive messages. Valid values: HH = 00-23,
        /// MM = 00-60 (60 only if UTC leap second), SS = 00-59. (without
        /// milliseconds) HH = 00-23, MM = 00-59, SS = 00-60 (60 only if UTC leap
        /// second), sss=000-999 (indicating milliseconds).
        UtcTimeOnly,
        /// string field representing Time/date combination represented in UTC
        /// (Universal Time Coordinated, also known as "GMT") in either
        /// YYYYMMDD-HH:MM:SS (whole seconds) or YYYYMMDD-HH:MM:SS.sss (milliseconds)
        /// format, colons, dash, and period required. Valid values: * YYYY =
        /// 0000-9999, MM = 01-12, DD = 01-31, HH = 00-23, MM = 00-59, SS = 00-60 (60
        /// only if UTC leap second) (without milliseconds). * YYYY = 0000-9999, MM =
        /// 01-12, DD = 01-31, HH = 00-23, MM = 00-59, SS = 00-60 (60 only if UTC
        /// leap second), sss=000-999 (indicating milliseconds). Leap Seconds: Note
        /// that UTC includes corrections for leap seconds, which are inserted to
        /// account for slowing of the rotation of the earth. Leap second insertion
        /// is declared by the International Earth Rotation Service (IERS) and has,
        /// since 1972, only occurred on the night of Dec. 31 or Jun 30. The IERS
        /// considers March 31 and September 30 as secondary dates for leap second
        /// insertion, but has never utilized these dates. During a leap second
        /// insertion, a UTCTimestamp field may read "19981231-23:59:59",
        /// "19981231-23:59:60", "19990101-00:00:00". (see
        /// <http://tycho.usno.navy.mil/leapsec.html>)
        UtcTimestamp,
        /// Contains an XML document raw data with no format or content restrictions.
        /// XMLData fields are always immediately preceded by a length field. The
        /// length field should specify the number of bytes of the value of the data
        /// field (up to but not including the terminating SOH).
        XmlData,
        /// string field representing a country using ISO 3166 Country code (2
        /// character) values (see Appendix 6-B).
        Country,
    }

    impl FixDatatype {
        /// Compares `name` to the set of strings commonly used by QuickFIX's custom
        /// specification format and returns its associated
        /// [`Datatype`](super::Datatype) if a match
        /// was found. The query is case-insensitive.
        ///
        /// # Examples
        ///
        /// ```
        /// use fefix::dict::FixDatatype;
        ///
        /// assert_eq!(FixDatatype::from_quickfix_name("AMT"), Some(FixDatatype::Amt));
        /// assert_eq!(FixDatatype::from_quickfix_name("Amt"), Some(FixDatatype::Amt));
        /// assert_eq!(FixDatatype::from_quickfix_name("MONTHYEAR"), Some(FixDatatype::MonthYear));
        /// assert_eq!(FixDatatype::from_quickfix_name(""), None);
        /// ```
        pub fn from_quickfix_name(name: &str) -> Option<Self> {
            // https://github.com/quickfix/quickfix/blob/b6760f55ac6a46306b4e081bb13b65e6220ab02d/src/C%2B%2B/DataDictionary.cpp#L646-L680
            Some(match name.to_ascii_uppercase().as_str() {
                "AMT" => FixDatatype::Amt,
                "BOOLEAN" => FixDatatype::Boolean,
                "CHAR" => FixDatatype::Char,
                "COUNTRY" => FixDatatype::Country,
                "CURRENCY" => FixDatatype::Currency,
                "DATA" => FixDatatype::Data,
                "DATE" => FixDatatype::UtcDateOnly, // FIXME?
                "DAYOFMONTH" => FixDatatype::DayOfMonth,
                "EXCHANGE" => FixDatatype::Exchange,
                "FLOAT" => FixDatatype::Float,
                "INT" => FixDatatype::Int,
                "LANGUAGE" => FixDatatype::Language,
                "LENGTH" => FixDatatype::Length,
                "LOCALMKTDATE" => FixDatatype::LocalMktDate,
                "MONTHYEAR" => FixDatatype::MonthYear,
                "MULTIPLECHARVALUE" | "MULTIPLEVALUESTRING" => FixDatatype::MultipleCharValue,
                "MULTIPLESTRINGVALUE" => FixDatatype::MultipleStringValue,
                "NUMINGROUP" => FixDatatype::NumInGroup,
                "PERCENTAGE" => FixDatatype::Percentage,
                "PRICE" => FixDatatype::Price,
                "PRICEOFFSET" => FixDatatype::PriceOffset,
                "QTY" => FixDatatype::Qty,
                "STRING" => FixDatatype::String,
                "TZTIMEONLY" => FixDatatype::UtcTimeOnly, // FIXME
                "TZTIMESTAMP" => FixDatatype::UtcTimestamp, // FIXME
                "UTCDATE" => FixDatatype::UtcDateOnly,
                "UTCDATEONLY" => FixDatatype::UtcDateOnly,
                "UTCTIMEONLY" => FixDatatype::UtcTimeOnly,
                "UTCTIMESTAMP" => FixDatatype::UtcTimestamp,
                "SEQNUM" => FixDatatype::SeqNum,
                "TIME" => FixDatatype::UtcTimestamp,
                "XMLDATA" => FixDatatype::XmlData,
                _ => {
                    return None;
                }
            })
        }

        /// Returns the name adopted by QuickFIX for `self`.
        pub fn to_quickfix_name(&self) -> &str {
            match self {
                FixDatatype::Int => "INT",
                FixDatatype::Length => "LENGTH",
                FixDatatype::Char => "CHAR",
                FixDatatype::Boolean => "BOOLEAN",
                FixDatatype::Float => "FLOAT",
                FixDatatype::Amt => "AMT",
                FixDatatype::Price => "PRICE",
                FixDatatype::PriceOffset => "PRICEOFFSET",
                FixDatatype::Qty => "QTY",
                FixDatatype::Percentage => "PERCENTAGE",
                FixDatatype::DayOfMonth => "DAYOFMONTH",
                FixDatatype::NumInGroup => "NUMINGROUP",
                FixDatatype::Language => "LANGUAGE",
                FixDatatype::SeqNum => "SEQNUM",
                FixDatatype::TagNum => "TAGNUM",
                FixDatatype::String => "STRING",
                FixDatatype::Data => "DATA",
                FixDatatype::MonthYear => "MONTHYEAR",
                FixDatatype::Currency => "CURRENCY",
                FixDatatype::Exchange => "EXCHANGE",
                FixDatatype::LocalMktDate => "LOCALMKTDATE",
                FixDatatype::MultipleStringValue => "MULTIPLESTRINGVALUE",
                FixDatatype::UtcTimeOnly => "UTCTIMEONLY",
                FixDatatype::UtcTimestamp => "UTCTIMESTAMP",
                FixDatatype::UtcDateOnly => "UTCDATEONLY",
                FixDatatype::Country => "COUNTRY",
                FixDatatype::MultipleCharValue => "MULTIPLECHARVALUE",
                FixDatatype::XmlData => "XMLDATA",
            }
        }

        /// Returns the name of `self`, character by character identical to the name
        /// that appears in the official guidelines. **Generally** primitive datatypes
        /// will use `snake_case` and non-primitive ones will have `PascalCase`, but
        /// that's not true for every [`Datatype`](super::Datatype).
        ///
        /// # Examples
        ///
        /// ```
        /// use fefix::dict::FixDatatype;
        ///
        /// assert_eq!(FixDatatype::Qty.name(), "Qty");
        /// assert_eq!(FixDatatype::Float.name(), "float");
        /// assert_eq!(FixDatatype::String.name(), "String");
        /// ```
        pub fn name(&self) -> &'static str {
            // 1. Most primitive data types have `snake_case` names.
            // 2. Most derivative data types have `PascalCase` names.
            // 3. `data` and `String` ruin the party and mess it up.
            //    Why, you ask? Oh, you sweet summer child. You'll learn soon enough
            //    that nothing makes sense in FIX land.
            match self {
                FixDatatype::Int => "int",
                FixDatatype::Length => "Length",
                FixDatatype::Char => "char",
                FixDatatype::Boolean => "Boolean",
                FixDatatype::Float => "float",
                FixDatatype::Amt => "Amt",
                FixDatatype::Price => "Price",
                FixDatatype::PriceOffset => "PriceOffset",
                FixDatatype::Qty => "Qty",
                FixDatatype::Percentage => "Percentage",
                FixDatatype::DayOfMonth => "DayOfMonth",
                FixDatatype::NumInGroup => "NumInGroup",
                FixDatatype::Language => "Language",
                FixDatatype::SeqNum => "SeqNum",
                FixDatatype::TagNum => "TagNum",
                FixDatatype::String => "String",
                FixDatatype::Data => "data",
                FixDatatype::MonthYear => "MonthYear",
                FixDatatype::Currency => "Currency",
                FixDatatype::Exchange => "Exchange",
                FixDatatype::LocalMktDate => "LocalMktDate",
                FixDatatype::MultipleStringValue => "MultipleStringValue",
                FixDatatype::UtcTimeOnly => "UTCTimeOnly",
                FixDatatype::UtcTimestamp => "UTCTimestamp",
                FixDatatype::UtcDateOnly => "UTCDateOnly",
                FixDatatype::Country => "Country",
                FixDatatype::MultipleCharValue => "MultipleCharValue",
                FixDatatype::XmlData => "XMLData",
            }
        }

        /// Returns `true` if and only if `self` is a "base type", i.e. a primitive;
        /// returns `false` otherwise.
        ///
        /// # Examples
        ///
        /// ```
        /// use fefix::dict::FixDatatype;
        ///
        /// assert_eq!(FixDatatype::Float.is_base_type(), true);
        /// assert_eq!(FixDatatype::Price.is_base_type(), false);
        /// ```
        pub fn is_base_type(&self) -> bool {
            match self {
                Self::Char | Self::Float | Self::Int | Self::String => true,
                _ => false,
            }
        }

        /// Returns the primitive [`Datatype`](super::Datatype) from which `self` is derived. If
        /// `self` is primitive already, returns `self` unchanged.
        ///
        /// # Examples
        ///
        /// ```
        /// use fefix::dict::FixDatatype;
        ///
        /// assert_eq!(FixDatatype::Float.base_type(), FixDatatype::Float);
        /// assert_eq!(FixDatatype::Price.base_type(), FixDatatype::Float);
        /// ```
        pub fn base_type(&self) -> Self {
            let dt = match self {
                Self::Char | Self::Boolean => Self::Char,
                Self::Float
                | Self::Amt
                | Self::Price
                | Self::PriceOffset
                | Self::Qty
                | Self::Percentage => Self::Float,
                Self::Int
                | Self::DayOfMonth
                | Self::Length
                | Self::NumInGroup
                | Self::SeqNum
                | Self::TagNum => Self::Int,
                _ => Self::String,
            };
            debug_assert!(dt.is_base_type());
            dt
        }

        /// Returns an [`Iterator`] over all variants of
        /// [`Datatype`](super::Datatype).
        pub fn iter_all() -> impl Iterator<Item = Self> {
            <Self as IntoEnumIterator>::iter()
        }
    }

    #[cfg(test)]
    mod test {
        use super::*;
        use std::collections::HashSet;

        #[test]
        fn iter_all_unique() {
            let as_vec = FixDatatype::iter_all().collect::<Vec<FixDatatype>>();
            let as_set = FixDatatype::iter_all().collect::<HashSet<FixDatatype>>();
            assert_eq!(as_vec.len(), as_set.len());
        }

        #[test]
        fn more_than_20_datatypes() {
            // According to the official documentation, FIX has "about 20 data
            // types". Including recent revisions, we should well exceed that
            // number.
            assert!(FixDatatype::iter_all().count() > 20);
        }

        #[test]
        fn names_are_unique() {
            let as_vec = FixDatatype::iter_all()
                .map(|dt| dt.name())
                .collect::<Vec<&str>>();
            let as_set = FixDatatype::iter_all()
                .map(|dt| dt.name())
                .collect::<HashSet<&str>>();
            assert_eq!(as_vec.len(), as_set.len());
        }

        #[test]
        fn base_type_is_itself() {
            for dt in FixDatatype::iter_all() {
                if dt.is_base_type() {
                    assert_eq!(dt.base_type(), dt);
                } else {
                    assert_ne!(dt.base_type(), dt);
                }
            }
        }

        #[test]
        fn base_type_is_actually_base_type() {
            for dt in FixDatatype::iter_all() {
                assert!(dt.base_type().is_base_type());
            }
        }
    }
}

/// A field is identified by a unique tag number and a name. Each field in a
/// message is associated with a value.
#[derive(Clone, Debug)]
struct FieldData {
    /// A human readable string representing the name of the field.
    name: String,
    /// **Primary key.** A positive integer representing the unique
    /// identifier for this field type.
    tag: u32,
    /// The datatype of the field.
    data_type_iid: InternalId,
    /// The associated data field. If given, this field represents the length of
    /// the referenced data field
    associated_data_tag: Option<usize>,
    value_restrictions: Option<Vec<FieldEnumData>>,
    /// Abbreviated form of the Name, typically to specify the element name when
    /// the field is used in an XML message. Can be overridden by BaseCategory /
    /// BaseCategoryAbbrName.
    abbr_name: Option<String>,
    /// Specifies the base message category when field is used in an XML message.
    base_category_id: Option<usize>,
    /// If BaseCategory is specified, this is the XML element identifier to use
    /// for this field, overriding AbbrName.
    base_category_abbr_name: Option<String>,
    /// Indicates whether the field is required in an XML message.
    required: bool,
    description: Option<String>,
}

#[derive(Clone, Debug)]
struct FieldEnumData {
    value: String,
    description: String,
}

/// A limitation imposed on the value of a specific FIX [`Field`].  Also known as
/// "code set".
#[derive(Debug)]
pub struct FieldEnum<'a>(&'a Dictionary, &'a FieldEnumData);

impl<'a> FieldEnum<'a> {
    /// Returns the string representation of this field variant.
    pub fn value(&self) -> &str {
        &self.1.value[..]
    }

    /// Returns the documentation description for `self`.
    pub fn description(&self) -> &str {
        &self.1.description[..]
    }
}

/// A field is the most granular message structure abstraction. It carries a
/// specific business meaning as described by the FIX specifications. The data
/// domain of a [`Field`] is either a [`Datatype`] or a "code set", i.e.
/// enumeration.
#[derive(Debug, Copy, Clone)]
pub struct Field<'a>(&'a Dictionary, &'a FieldData);

impl<'a> Field<'a> {
    pub fn doc_url_onixs(&self, version: &str) -> String {
        let v = match version {
            "FIX.4.0" => "4.0",
            "FIX.4.1" => "4.1",
            "FIX.4.2" => "4.2",
            "FIX.4.3" => "4.3",
            "FIX.4.4" => "4.4",
            "FIX.5.0" => "5.0",
            "FIX.5.0SP1" => "5.0.SP1",
            "FIX.5.0SP2" => "5.0.SP2",
            "FIXT.1.1" => "FIXT.1.1",
            s => s,
        };
        format!(
            "https://www.onixs.biz/fix-dictionary/{}/tagNum_{}.html",
            v,
            self.1.tag.to_string().as_str()
        )
    }

    /// Returns the [`FixDatatype`] of `self`.
    pub fn fix_datatype(&self) -> FixDatatype {
        self.data_type().basetype()
    }

    /// Returns the name of `self`. Field names are unique across each FIX
    /// [`Dictionary`].
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    /// Returns the numeric tag of `self`. Field tags are unique across each FIX
    /// [`Dictionary`].
    pub fn tag(&self) -> TagU16 {
        TagU16::new(self.1.tag as u16).unwrap()
    }

    /// In case this field allows any value, it returns `None`; otherwise; it
    /// returns an [`Iterator`] of all allowed values.
    pub fn enums(&self) -> Option<impl Iterator<Item = FieldEnum>> {
        self.1
            .value_restrictions
            .as_ref()
            .map(move |v| v.iter().map(move |f| FieldEnum(self.0, f)))
    }

    /// Returns the [`Datatype`] of `self`.
    pub fn data_type(&self) -> Datatype {
        let data = self
            .0
            .inner
            .data_types
            .get(self.1.data_type_iid as usize)
            .unwrap();
        Datatype(self.0, data)
    }
}

impl<'a> IsFieldDefinition for Field<'a> {
    fn name(&self) -> &str {
        self.1.name.as_str()
    }

    fn tag(&self) -> TagU16 {
        TagU16::new(self.1.tag as u16).expect("Invalid FIX tag (0)")
    }

    fn location(&self) -> FieldLocation {
        FieldLocation::Body // FIXME
    }
}

#[derive(Clone, Debug)]
#[allow(dead_code)]
enum LayoutItemKindData {
    Component {
        iid: InternalId,
    },
    Group {
        len_field_iid: u32,
        items: Vec<LayoutItemData>,
    },
    Field {
        iid: InternalId,
    },
}

#[derive(Clone, Debug)]
struct LayoutItemData {
    required: bool,
    kind: LayoutItemKindData,
}

pub trait IsFieldDefinition {
    /// Returns the FIX tag associated with `self`.
    fn tag(&self) -> TagU16;

    /// Returns the official, ASCII, human-readable name associated with `self`.
    fn name(&self) -> &str;

    /// Returns the field location of `self`.
    fn location(&self) -> FieldLocation;
}

fn layout_item_kind<'a>(item: &'a LayoutItemKindData, dict: &'a Dictionary) -> LayoutItemKind<'a> {
    match item {
        LayoutItemKindData::Component { iid } => LayoutItemKind::Component(Component(
            dict,
            dict.inner.components.get(*iid as usize).unwrap(),
        )),
        LayoutItemKindData::Group {
            len_field_iid,
            items: items_data,
        } => {
            let items = items_data
                .iter()
                .map(|item_data| LayoutItem(dict, item_data))
                .collect::<Vec<_>>();
            let len_field_data = &dict.inner.fields[*len_field_iid as usize];
            let len_field = Field(dict, len_field_data);
            LayoutItemKind::Group(len_field, items)
        }
        LayoutItemKindData::Field { iid } => {
            LayoutItemKind::Field(Field(dict, dict.inner.fields.get(*iid as usize).unwrap()))
        }
    }
}

/// An entry in a sequence of FIX field definitions.
#[derive(Clone, Debug)]
pub struct LayoutItem<'a>(&'a Dictionary, &'a LayoutItemData);

/// The kind of element contained in a [`Message`].
#[derive(Debug)]
pub enum LayoutItemKind<'a> {
    /// This component item is another component.
    Component(Component<'a>),
    /// This component item is a FIX repeating group.
    Group(Field<'a>, Vec<LayoutItem<'a>>),
    /// This component item is a FIX field.
    Field(Field<'a>),
}

impl<'a> LayoutItem<'a> {
    /// Returns `true` if `self` is required in order to have a valid definition
    /// of its parent container, `false` otherwise.
    pub fn required(&self) -> bool {
        self.1.required
    }

    /// Returns the [`LayoutItemKind`] of `self`.
    pub fn kind(&self) -> LayoutItemKind {
        layout_item_kind(&self.1.kind, self.0)
    }

    /// Returns the human-readable name of `self`.
    pub fn tag_text(&self) -> &str {
        match &self.1.kind {
            LayoutItemKindData::Component { iid } => self
                .0
                .inner
                .components
                .get(*iid as usize)
                .unwrap()
                .name
                .as_str(),
            LayoutItemKindData::Group {
                len_field_iid,
                items: _items,
            } => self
                .0
                .inner
                .fields
                .get(*len_field_iid as usize)
                .unwrap()
                .name
                .as_str(),
            LayoutItemKindData::Field { iid } => self
                .0
                .inner
                .fields
                .get(*iid as usize)
                .unwrap()
                .name
                .as_str(),
        }
    }
}

type LayoutItems = Vec<LayoutItemData>;

#[derive(Clone, Debug)]
struct MessageData {
    /// The unique integer identifier of this message type.
    component_id: u32,
    /// **Primary key**. The unique character identifier of this message
    /// type; used literally in FIX messages.
    msg_type: String,
    /// The name of this message type.
    name: String,
    /// Identifier of the category to which this message belongs.
    category_iid: InternalId,
    /// Identifier of the section to which this message belongs.
    section_id: String,
    layout_items: LayoutItems,
    /// The abbreviated name of this message, when used in an XML context.
    abbr_name: Option<String>,
    /// A boolean used to indicate if the message is to be generated as part
    /// of FIXML.
    required: bool,
    description: String,
    elaboration: Option<String>,
}

/// A [`Message`] is a unit of information sent on the wire between
/// counterparties. Every [`Message`] is composed of fields and/or components.
#[derive(Debug)]
pub struct Message<'a>(&'a Dictionary, &'a MessageData);

impl<'a> Message<'a> {
    /// Returns the human-readable name of `self`.
    pub fn name(&self) -> &str {
        self.1.name.as_str()
    }

    /// Returns the message type of `self`.
    pub fn msg_type(&self) -> &str {
        self.1.msg_type.as_str()
    }

    /// Returns the description associated with `self`.
    pub fn description(&self) -> &str {
        &self.1.description
    }

    pub fn group_info(&self, num_in_group_tag: TagU16) -> Option<TagU16> {
        self.layout().find_map(|layout_item| {
            if let LayoutItemKind::Group(field, items) = layout_item.kind() {
                if field.tag() == num_in_group_tag {
                    if let LayoutItemKind::Field(f) = items[0].kind() {
                        Some(f.tag())
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else if let LayoutItemKind::Component(_component) = layout_item.kind() {
                None
            } else {
                None
            }
        })
    }

    /// Returns the component ID of `self`.
    pub fn component_id(&self) -> u32 {
        self.1.component_id
    }

    pub fn layout(&self) -> impl Iterator<Item = LayoutItem> {
        self.1
            .layout_items
            .iter()
            .map(move |data| LayoutItem(self.0, data))
    }
}

/// A [`Section`] is a collection of many [`Component`]-s. It has no practical
/// effect on encoding and decoding of FIX data and it's only used for
/// documentation and human readability.
#[derive(Clone, Debug, PartialEq)]
pub struct Section {}

mod symbol_table {
    use super::InternalId;
    use fnv::FnvHashMap;
    use std::borrow::Borrow;
    use std::hash::Hash;

    pub type SymbolTable = FnvHashMap<Key, InternalId>;

    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub enum Key {
        #[allow(dead_code)]
        Abbreviation(String),
        CategoryByName(String),
        ComponentByName(String),
        DatatypeByName(String),
        FieldByTag(u32),
        FieldByName(String),
        MessageByName(String),
        MessageByMsgType(String),
    }

    #[derive(Copy, Debug, Clone, PartialEq, Eq, Hash)]
    pub enum KeyRef<'a> {
        Abbreviation(&'a str),
        CategoryByName(&'a str),
        ComponentByName(&'a str),
        DatatypeByName(&'a str),
        FieldByTag(u32),
        FieldByName(&'a str),
        MessageByName(&'a str),
        MessageByMsgType(&'a str),
    }

    impl Key {
        fn as_ref(&self) -> KeyRef {
            match self {
                Key::Abbreviation(s) => KeyRef::Abbreviation(s.as_str()),
                Key::CategoryByName(s) => KeyRef::CategoryByName(s.as_str()),
                Key::ComponentByName(s) => KeyRef::ComponentByName(s.as_str()),
                Key::DatatypeByName(s) => KeyRef::DatatypeByName(s.as_str()),
                Key::FieldByTag(t) => KeyRef::FieldByTag(*t),
                Key::FieldByName(s) => KeyRef::FieldByName(s.as_str()),
                Key::MessageByName(s) => KeyRef::MessageByName(s.as_str()),
                Key::MessageByMsgType(s) => KeyRef::MessageByMsgType(s.as_str()),
            }
        }
    }

    pub trait SymbolTableIndex {
        fn to_key(&self) -> KeyRef;
    }

    impl SymbolTableIndex for Key {
        fn to_key(&self) -> KeyRef {
            self.as_ref()
        }
    }

    impl<'a> SymbolTableIndex for KeyRef<'a> {
        fn to_key(&self) -> KeyRef {
            *self
        }
    }

    impl<'a> Hash for dyn SymbolTableIndex + 'a {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
            self.to_key().hash(state);
        }
    }

    impl<'a> Borrow<dyn SymbolTableIndex + 'a> for Key {
        fn borrow(&self) -> &(dyn SymbolTableIndex + 'a) {
            self
        }
    }

    impl<'a> Eq for dyn SymbolTableIndex + 'a {}

    impl<'a> PartialEq for dyn SymbolTableIndex + 'a {
        fn eq(&self, other: &dyn SymbolTableIndex) -> bool {
            self.to_key() == other.to_key()
        }
    }
}

mod quickfix {
    use super::*;

    pub struct QuickFixReader<'a> {
        node_with_header: roxmltree::Node<'a, 'a>,
        node_with_trailer: roxmltree::Node<'a, 'a>,
        node_with_components: roxmltree::Node<'a, 'a>,
        node_with_messages: roxmltree::Node<'a, 'a>,
        node_with_fields: roxmltree::Node<'a, 'a>,
        builder: DictionaryBuilder,
    }

    impl<'a> QuickFixReader<'a> {
        pub fn new(xml_document: &'a roxmltree::Document<'a>) -> ParseResult<Dictionary> {
            let mut reader = Self::empty(&xml_document)?;
            for child in reader.node_with_fields.children() {
                if child.is_element() {
                    import_field(&mut reader.builder, child)?;
                }
            }
            for child in reader.node_with_components.children() {
                if child.is_element() {
                    let name = child
                        .attribute("name")
                        .ok_or(ParseDictionaryError::InvalidFormat)?
                        .to_string();
                    import_component(&mut reader.builder, child, name)?;
                }
            }
            for child in reader.node_with_messages.children() {
                if child.is_element() {
                    import_message(&mut reader.builder, child)?;
                }
            }
            // `StandardHeader` and `StandardTrailer` are defined in ad-hoc
            // sections of the XML files. They're always there, even if
            // potentially empty (e.g. FIX 5.0+).
            import_component(
                &mut reader.builder,
                reader.node_with_header,
                "StandardHeader",
            )?;
            import_component(
                &mut reader.builder,
                reader.node_with_trailer,
                "StandardTrailer",
            )?;
            Ok(reader.builder.build())
        }

        fn empty(xml_document: &'a roxmltree::Document<'a>) -> ParseResult<Self> {
            let root = xml_document.root_element();
            let find_tagged_child = |tag: &str| {
                root.children()
                    .find(|n| n.has_tag_name(tag))
                    .ok_or_else(|| {
                        ParseDictionaryError::InvalidData(format!("<{}> tag not found", tag))
                    })
            };
            let version_type = root
                .attribute("type")
                .ok_or(ParseDictionaryError::InvalidData(
                    "No version attribute.".to_string(),
                ))?;
            let version_major =
                root.attribute("major")
                    .ok_or(ParseDictionaryError::InvalidData(
                        "No major version attribute.".to_string(),
                    ))?;
            let version_minor =
                root.attribute("minor")
                    .ok_or(ParseDictionaryError::InvalidData(
                        "No minor version attribute.".to_string(),
                    ))?;
            let version_sp = root.attribute("servicepack").unwrap_or("0");
            let version = format!(
                "{}.{}.{}{}",
                version_type,
                version_major,
                version_minor,
                // Omit Service Pack ID if set to zero.
                if version_sp != "0" {
                    format!("-SP{}", version_sp)
                } else {
                    String::new()
                }
            );
            Ok(QuickFixReader {
                builder: DictionaryBuilder::new(version),
                node_with_header: find_tagged_child("header")?,
                node_with_trailer: find_tagged_child("trailer")?,
                node_with_messages: find_tagged_child("messages")?,
                node_with_components: find_tagged_child("components")?,
                node_with_fields: find_tagged_child("fields")?,
            })
        }
    }

    fn import_field(
        builder: &mut DictionaryBuilder,
        node: roxmltree::Node,
    ) -> ParseResult<InternalId> {
        if node.tag_name().name() != "field" {
            return Err(ParseDictionaryError::InvalidFormat);
        }
        let data_type_iid = import_datatype(builder, node);
        let value_restrictions = value_restrictions_from_node(node, data_type_iid);
        let name = node
            .attribute("name")
            .ok_or(ParseDictionaryError::InvalidFormat)?
            .to_string();
        let tag = node
            .attribute("number")
            .ok_or(ParseDictionaryError::InvalidFormat)?
            .parse()
            .map_err(|_| ParseDictionaryError::InvalidFormat)?;
        let field = FieldData {
            name,
            tag,
            data_type_iid,
            associated_data_tag: None,
            value_restrictions,
            required: true,
            abbr_name: None,
            base_category_abbr_name: None,
            base_category_id: None,
            description: None,
        };
        Ok(builder.add_field(field))
    }

    fn import_message(
        builder: &mut DictionaryBuilder,
        node: roxmltree::Node,
    ) -> ParseResult<InternalId> {
        debug_assert_eq!(node.tag_name().name(), "message");
        let category_iid = import_category(builder, node)?;
        let mut layout_items = LayoutItems::new();
        for child in node.children() {
            if child.is_element() {
                // We don't need to generate new IID's because we're dealing
                // with ranges.
                layout_items.push(import_layout_item(builder, child)?);
            }
        }
        let message = MessageData {
            name: node
                .attribute("name")
                .ok_or(ParseDictionaryError::InvalidFormat)?
                .to_string(),
            msg_type: node
                .attribute("msgtype")
                .ok_or(ParseDictionaryError::InvalidFormat)?
                .to_string(),
            component_id: 0,
            category_iid,
            section_id: String::new(),
            layout_items,
            abbr_name: None,
            required: true,
            elaboration: None,
            description: String::new(),
        };
        Ok(builder.add_message(message))
    }

    fn import_component<S: AsRef<str>>(
        builder: &mut DictionaryBuilder,
        node: roxmltree::Node,
        name: S,
    ) -> ParseResult<InternalId> {
        let mut layout_items = LayoutItems::new();
        for child in node.children() {
            if child.is_element() {
                layout_items.push(import_layout_item(builder, child)?);
            }
        }
        let component = ComponentData {
            id: 0,
            component_type: FixmlComponentAttributes::Block {
                // FIXME
                is_implicit: false,
                is_repeating: false,
                is_optimized: false,
            },
            layout_items,
            category_iid: 0, // FIXME
            name: name.as_ref().to_string(),
            abbr_name: None,
        };
        let iid = builder.add_component(component);
        match builder.symbol(KeyRef::ComponentByName(name.as_ref())) {
            Some(x) => Ok(*x),
            None => {
                builder
                    .symbol_table
                    .insert(Key::ComponentByName(name.as_ref().to_string()), iid);
                Ok(iid)
            }
        }
    }

    fn import_datatype(builder: &mut DictionaryBuilder, node: roxmltree::Node) -> InternalId {
        // References should only happen at <field> tags.
        debug_assert_eq!(node.tag_name().name(), "field");
        let datatype = {
            // The idenfier that QuickFIX uses for this type.
            let quickfix_name = node.attribute("type").unwrap();
            // Translate that into a real datatype.
            FixDatatype::from_quickfix_name(quickfix_name).unwrap()
        };
        // Get the official (not QuickFIX's) name of `datatype`.
        let name = datatype.name();
        match builder.symbol(KeyRef::DatatypeByName(name)) {
            Some(x) => *x,
            None => {
                let iid = builder.data_types.len() as u32;
                let data = DatatypeData {
                    datatype,
                    description: String::new(),
                    examples: Vec::new(),
                };
                builder.data_types.push(data);
                builder
                    .symbol_table
                    .insert(Key::DatatypeByName(name.to_string()), iid);
                iid
            }
        }
    }

    fn value_restrictions_from_node(
        node: roxmltree::Node,
        _datatype: InternalId,
    ) -> Option<Vec<FieldEnumData>> {
        let mut values = Vec::new();
        for child in node.children() {
            if child.is_element() {
                let variant = child.attribute("enum").unwrap().to_string();
                let description = child.attribute("description").unwrap().to_string();
                let enum_value = FieldEnumData {
                    value: variant,
                    description,
                };
                values.push(enum_value);
            }
        }
        if values.len() == 0 {
            None
        } else {
            Some(values)
        }
    }

    fn import_layout_item(
        builder: &mut DictionaryBuilder,
        node: roxmltree::Node,
    ) -> ParseResult<LayoutItemData> {
        // This processing step requires on fields being already present in
        // the dictionary.
        debug_assert_ne!(builder.fields.len(), 0);
        let name = node.attribute("name").unwrap();
        let required = node.attribute("required").unwrap() == "Y";
        let tag = node.tag_name().name();
        let kind = match tag {
            "field" => {
                let field_iid = builder.symbol(KeyRef::FieldByName(name)).unwrap();
                LayoutItemKindData::Field { iid: *field_iid }
            }
            "component" => {
                // Components may *not* be already present.
                let component_iid = import_component(builder, node, name)?;
                LayoutItemKindData::Component { iid: component_iid }
            }
            "group" => {
                let len_field_iid = *builder.symbol(KeyRef::FieldByName(name)).unwrap();
                let mut items = Vec::new();
                for child in node.children().filter(|n| n.is_element()) {
                    items.push(import_layout_item(builder, child)?);
                }
                LayoutItemKindData::Group {
                    len_field_iid,
                    items,
                }
            }
            _ => {
                return Err(ParseDictionaryError::InvalidFormat);
            }
        };
        let item = LayoutItemData { required, kind };
        Ok(item)
    }

    fn import_category(
        builder: &mut DictionaryBuilder,
        node: roxmltree::Node,
    ) -> ParseResult<InternalId> {
        debug_assert_eq!(node.tag_name().name(), "message");
        let name = node.attribute("msgcat").ok_or(ParseError::InvalidFormat)?;
        Ok(match builder.symbol(KeyRef::CategoryByName(name)) {
            Some(x) => *x,
            None => {
                let iid = builder.categories.len() as u32;
                builder.categories.push(CategoryData {
                    name: name.to_string(),
                    fixml_filename: String::new(),
                });
                builder
                    .symbol_table
                    .insert(Key::CategoryByName(name.to_string()), iid);
                iid
            }
        })
    }

    type ParseError = ParseDictionaryError;
    type ParseResult<T> = Result<T, ParseError>;

    /// The error type that can arise when decoding a QuickFIX Dictionary.
    #[derive(Clone, Debug)]
    pub enum ParseDictionaryError {
        InvalidFormat,
        InvalidData(String),
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn fix44_quickfix_is_ok() {
        let dict = Dictionary::fix44();
        let msg_heartbeat = dict.message_by_name("Heartbeat").unwrap();
        assert_eq!(msg_heartbeat.msg_type(), "0");
        assert_eq!(msg_heartbeat.name(), "Heartbeat".to_string());
        assert!(msg_heartbeat.layout().any(|c| {
            if let LayoutItemKind::Field(f) = c.kind() {
                f.name() == "TestReqID"
            } else {
                false
            }
        }));
    }

    #[test]
    fn all_datatypes_are_used_at_least_once() {
        for dict in Dictionary::all().iter() {
            let datatypes_count = dict.iter_datatypes().count();
            let mut datatypes = HashSet::new();
            for field in dict.iter_fields() {
                datatypes.insert(field.data_type().name().to_string());
            }
            assert_eq!(datatypes_count, datatypes.len());
        }
    }

    #[test]
    fn at_least_one_datatype() {
        for dict in Dictionary::all().iter() {
            assert!(dict.iter_datatypes().count() >= 1);
        }
    }

    #[test]
    fn std_header_and_trailer_always_present() {
        for dict in Dictionary::all().iter() {
            let std_header = dict.component_by_name("StandardHeader");
            let std_trailer = dict.component_by_name("StandardTrailer");
            assert!(std_header.is_some() && std_trailer.is_some());
        }
    }

    #[test]
    fn fix44_field_28_has_three_variants() {
        let dict = Dictionary::fix44();
        let field_28 = dict.field_by_tag(28).unwrap();
        assert_eq!(field_28.name(), "IOITransType");
        assert_eq!(field_28.enums().unwrap().count(), 3);
    }

    #[test]
    fn fix44_field_36_has_no_variants() {
        let dict = Dictionary::fix44();
        let field_36 = dict.field_by_tag(36).unwrap();
        assert_eq!(field_36.name(), "NewSeqNo");
        assert!(field_36.enums().is_none());
    }

    #[test]
    fn fix44_field_167_has_eucorp_variant() {
        let dict = Dictionary::fix44();
        let field_167 = dict.field_by_tag(167).unwrap();
        assert_eq!(field_167.name(), "SecurityType");
        assert!(field_167.enums().unwrap().any(|e| e.value() == "EUCORP"));
    }

    const INVALID_QUICKFIX_SPECS: &[&str] = &[
        include_str!("test_data/quickfix_specs/empty_file.xml"),
        include_str!("test_data/quickfix_specs/missing_components.xml"),
        include_str!("test_data/quickfix_specs/missing_fields.xml"),
        include_str!("test_data/quickfix_specs/missing_header.xml"),
        include_str!("test_data/quickfix_specs/missing_messages.xml"),
        include_str!("test_data/quickfix_specs/missing_trailer.xml"),
        include_str!("test_data/quickfix_specs/root_has_no_type_attr.xml"),
        include_str!("test_data/quickfix_specs/root_has_no_version_attrs.xml"),
        include_str!("test_data/quickfix_specs/root_is_not_fix.xml"),
    ];

    #[test]
    fn invalid_quickfix_specs() {
        for spec in INVALID_QUICKFIX_SPECS.iter() {
            let dict = Dictionary::from_quickfix_spec(spec);
            assert!(dict.is_err(), "{}", spec);
        }
    }
}