hotfix_dictionary/
dictionary.rs

1use crate::{Component, ComponentData, Datatype, DatatypeData, Field, FieldData};
2
3use crate::message_definition::{MessageData, MessageDefinition};
4use crate::quickfix::{ParseDictionaryError, QuickFixReader};
5use fnv::FnvHashMap;
6use smartstring::alias::String as SmartString;
7
8/// Specifies business semantics for application-level entities within the FIX
9/// Protocol.
10///
11/// You can rely on [`Dictionary`] for accessing details about
12/// fields, messages, and other abstract entities as defined in the FIX
13/// specifications. Examples of such information include:
14///
15/// - The mapping of FIX field names to numeric tags (e.g. `BeginString` is 8).
16/// - Which FIX fields are mandatory and which are optional.
17/// - The data type of each and every FIX field.
18/// - What fields to expect in FIX headers.
19///
20/// N.B. The FIX Protocol mandates separation of concerns between session and
21/// application protocol only for FIX 5.0 and subsequent versions. All FIX
22/// Dictionaries for older versions will also contain information about the
23/// session layer.
24#[derive(Debug, Clone)]
25pub struct Dictionary {
26    pub(crate) version: String,
27
28    pub(crate) data_types_by_name: FnvHashMap<SmartString, DatatypeData>,
29
30    pub(crate) fields_by_tags: FnvHashMap<u32, FieldData>,
31    pub(crate) field_tags_by_name: FnvHashMap<SmartString, u32>,
32
33    pub(crate) components_by_name: FnvHashMap<SmartString, ComponentData>,
34
35    pub(crate) messages_by_msgtype: FnvHashMap<SmartString, MessageData>,
36    pub(crate) message_msgtypes_by_name: FnvHashMap<SmartString, SmartString>,
37}
38
39impl Dictionary {
40    /// Creates a new empty FIX Dictionary named `version`.
41    pub fn new<S: ToString>(version: S) -> Self {
42        Dictionary {
43            version: version.to_string(),
44            data_types_by_name: FnvHashMap::default(),
45            fields_by_tags: FnvHashMap::default(),
46            field_tags_by_name: FnvHashMap::default(),
47            components_by_name: FnvHashMap::default(),
48            messages_by_msgtype: FnvHashMap::default(),
49            message_msgtypes_by_name: FnvHashMap::default(),
50        }
51    }
52
53    /// Attempts to read a QuickFIX-style specification file and convert it into
54    /// a [`Dictionary`].
55    pub fn from_quickfix_spec(input: &str) -> Result<Self, ParseDictionaryError> {
56        let xml_document =
57            roxmltree::Document::parse(input).map_err(|_| ParseDictionaryError::InvalidFormat)?;
58        QuickFixReader::new(&xml_document)
59    }
60
61    /// Returns the version string associated with this [`Dictionary`] (e.g.
62    /// `FIXT.1.1`, `FIX.4.2`).
63    ///
64    /// ```
65    /// use hotfix_dictionary::Dictionary;
66    ///
67    /// let dict = Dictionary::fix44();
68    /// assert_eq!(dict.version(), "FIX.4.4");
69    /// ```
70    pub fn version(&self) -> &str {
71        self.version.as_str()
72    }
73
74    pub fn load_from_file(path: &str) -> Result<Self, ParseDictionaryError> {
75        let spec = std::fs::read_to_string(path)
76            .unwrap_or_else(|_| panic!("unable to read FIX dictionary file at {path}"));
77        Dictionary::from_quickfix_spec(&spec)
78    }
79
80    /// Creates a new [`Dictionary`] for FIX 4.0.
81    #[cfg(feature = "fix40")]
82    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix40")))]
83    pub fn fix40() -> Self {
84        let spec = include_str!("resources/quickfix/FIX-4.0.xml");
85        Dictionary::from_quickfix_spec(spec).unwrap()
86    }
87
88    /// Creates a new [`Dictionary`] for FIX 4.1.
89    #[cfg(feature = "fix41")]
90    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix41")))]
91    pub fn fix41() -> Self {
92        let spec = include_str!("resources/quickfix/FIX-4.1.xml");
93        Dictionary::from_quickfix_spec(spec).unwrap()
94    }
95
96    /// Creates a new [`Dictionary`] for FIX 4.2.
97    #[cfg(feature = "fix42")]
98    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix42")))]
99    pub fn fix42() -> Self {
100        let spec = include_str!("resources/quickfix/FIX-4.2.xml");
101        Dictionary::from_quickfix_spec(spec).unwrap()
102    }
103
104    /// Creates a new [`Dictionary`] for FIX 4.3.
105    #[cfg(feature = "fix43")]
106    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix43")))]
107    pub fn fix43() -> Self {
108        let spec = include_str!("resources/quickfix/FIX-4.3.xml");
109        Dictionary::from_quickfix_spec(spec).unwrap()
110    }
111
112    /// Creates a new [`Dictionary`] for FIX 4.4.
113    pub fn fix44() -> Self {
114        let spec = include_str!("resources/quickfix/FIX-4.4.xml");
115        Dictionary::from_quickfix_spec(spec).unwrap()
116    }
117
118    /// Creates a new [`Dictionary`] for FIX 5.0.
119    #[cfg(feature = "fix50")]
120    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix50")))]
121    pub fn fix50() -> Self {
122        let spec = include_str!("resources/quickfix/FIX-5.0.xml");
123        Dictionary::from_quickfix_spec(spec).unwrap()
124    }
125
126    /// Creates a new [`Dictionary`] for FIX 5.0 SP1.
127    #[cfg(feature = "fix50sp1")]
128    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix50sp1")))]
129    pub fn fix50sp1() -> Self {
130        let spec = include_str!("resources/quickfix/FIX-5.0-SP1.xml");
131        Dictionary::from_quickfix_spec(spec).unwrap()
132    }
133
134    /// Creates a new [`Dictionary`] for FIX 5.0 SP2.
135    #[cfg(feature = "fix50sp2")]
136    #[cfg_attr(doc_cfg, doc(cfg(feature = "fix50sp1")))]
137    pub fn fix50sp2() -> Self {
138        let spec = include_str!("resources/quickfix/FIX-5.0-SP2.xml");
139        Dictionary::from_quickfix_spec(spec).unwrap()
140    }
141
142    /// Creates a new [`Dictionary`] for FIXT 1.1.
143    #[cfg(feature = "fixt11")]
144    #[cfg_attr(doc_cfg, doc(cfg(feature = "fixt11")))]
145    pub fn fixt11() -> Self {
146        let spec = include_str!("resources/quickfix/FIXT-1.1.xml");
147        Dictionary::from_quickfix_spec(spec).unwrap()
148    }
149
150    /// Returns a [`Vec`] of FIX [`Dictionary`]'s for the most common FIX
151    /// versions (that have been enabled via feature flags). This is only
152    /// intended for testing purposes.
153    pub fn common_dictionaries() -> Vec<Dictionary> {
154        vec![
155            #[cfg(feature = "fix40")]
156            Self::fix40(),
157            #[cfg(feature = "fix41")]
158            Self::fix41(),
159            #[cfg(feature = "fix42")]
160            Self::fix42(),
161            #[cfg(feature = "fix43")]
162            Self::fix43(),
163            Self::fix44(),
164            #[cfg(feature = "fix50")]
165            Self::fix50(),
166            #[cfg(feature = "fix50sp1")]
167            Self::fix50sp1(),
168            #[cfg(feature = "fix50sp2")]
169            Self::fix50sp2(),
170            #[cfg(feature = "fixt11")]
171            Self::fixt11(),
172        ]
173    }
174
175    /// Returns the [`Message`] associated with `name`, if any.
176    ///
177    /// ```
178    /// use hotfix_dictionary::Dictionary;
179    ///
180    /// let dict = Dictionary::fix44();
181    ///
182    /// let msg1 = dict.message_by_name("Heartbeat").unwrap();
183    /// let msg2 = dict.message_by_msgtype("0").unwrap();
184    /// assert_eq!(msg1.name(), msg2.name());
185    /// ```
186    pub fn message_by_name(&self, name: &str) -> Option<MessageDefinition<'_>> {
187        let msg_type = self.message_msgtypes_by_name.get(name)?;
188        self.message_by_msgtype(msg_type)
189    }
190
191    /// Returns the [`Message`] that has the given `msgtype`, if any.
192    ///
193    /// ```
194    /// use hotfix_dictionary::Dictionary;
195    ///
196    /// let dict = Dictionary::fix44();
197    ///
198    /// let msg1 = dict.message_by_msgtype("0").unwrap();
199    /// let msg2 = dict.message_by_name("Heartbeat").unwrap();
200    /// assert_eq!(msg1.name(), msg2.name());
201    /// ```
202    pub fn message_by_msgtype(&self, msgtype: &str) -> Option<MessageDefinition<'_>> {
203        self.messages_by_msgtype
204            .get(msgtype)
205            .map(|data| MessageDefinition(self, data))
206    }
207
208    /// Returns the [`Component`] named `name`, if any.
209    pub fn component_by_name(&self, name: &str) -> Option<Component<'_>> {
210        self.components_by_name
211            .get(name)
212            .map(|data| Component(self, data))
213    }
214
215    /// Returns the [`Datatype`] named `name`, if any.
216    ///
217    /// ```
218    /// use hotfix_dictionary::Dictionary;
219    ///
220    /// let dict = Dictionary::fix44();
221    /// let dt = dict.datatype_by_name("String").unwrap();
222    /// assert_eq!(dt.name(), "String");
223    /// ```
224    pub fn datatype_by_name(&self, name: &str) -> Option<Datatype<'_>> {
225        self.data_types_by_name
226            .get(name)
227            .map(|data| Datatype(self, data))
228    }
229
230    /// Returns the [`Field`] associated with `tag`, if any.
231    ///
232    /// ```
233    /// use hotfix_dictionary::Dictionary;
234    ///
235    /// let dict = Dictionary::fix44();
236    /// let field1 = dict.field_by_tag(112).unwrap();
237    /// let field2 = dict.field_by_name("TestReqID").unwrap();
238    /// assert_eq!(field1.name(), field2.name());
239    /// ```
240    pub fn field_by_tag(&self, tag: u32) -> Option<Field<'_>> {
241        self.fields_by_tags
242            .get(&tag)
243            .map(|data| Field::new(self, data))
244    }
245
246    /// Returns the [`Field`] named `name`, if any.
247    pub fn field_by_name(&self, name: &str) -> Option<Field<'_>> {
248        let tag = self.field_tags_by_name.get(name)?;
249        self.field_by_tag(*tag)
250    }
251
252    /// Returns a [`Vec`] of all [`Datatype`]'s in this [`Dictionary`]. The ordering
253    /// of items is not specified.
254    ///
255    /// ```
256    /// use hotfix_dictionary::Dictionary;
257    ///
258    /// let dict = Dictionary::fix44();
259    /// // FIX 4.4 defines 23 (FIXME) datatypes.
260    /// assert_eq!(dict.datatypes().len(), 23);
261    /// ```
262    pub fn datatypes(&self) -> Vec<Datatype<'_>> {
263        self.data_types_by_name
264            .values()
265            .map(|data| Datatype(self, data))
266            .collect()
267    }
268
269    /// Returns a [`Vec`] of all [`Message`]'s in this [`Dictionary`]. The ordering
270    /// of items is not specified.
271    ///
272    /// ```
273    /// use hotfix_dictionary::Dictionary;
274    ///
275    /// let dict = Dictionary::fix44();
276    /// let msgs = dict.messages();
277    /// let msg = msgs.iter().find(|m| m.name() == "MarketDataRequest");
278    /// assert_eq!(msg.unwrap().msg_type(), "V");
279    /// ```
280    pub fn messages(&self) -> Vec<MessageDefinition<'_>> {
281        self.messages_by_msgtype
282            .values()
283            .map(|data| MessageDefinition(self, data))
284            .collect()
285    }
286
287    /// Returns a [`Vec`] of all [`Field`]'s in this [`Dictionary`]. The ordering
288    /// of items is not specified.
289    pub fn fields(&self) -> Vec<Field<'_>> {
290        self.fields_by_tags
291            .values()
292            .map(|data| Field::new(self, data))
293            .collect()
294    }
295
296    /// Returns a [`Vec`] of all [`Component`]'s in this [`Dictionary`]. The ordering
297    /// of items is not specified.
298    pub fn components(&self) -> Vec<Component<'_>> {
299        self.components_by_name
300            .values()
301            .map(|data| Component(self, data))
302            .collect()
303    }
304}