Skip to main content

easyfix_dictionary/
dictionary.rs

1//! Core dictionary implementation and data structures.
2//!
3//! This module provides the main implementation of the FIX dictionary, including:
4//! - The `Dictionary` struct for accessing fields, components, and messages
5//! - The `DictionaryBuilder` for configuring and creating dictionaries
6//! - Type definitions for FIX protocol elements (Message, Component, Group, etc.)
7//! - FIX protocol types (`MsgType`, `MsgCat`, etc.)
8//! - Error handling for dictionary operations
9
10mod builder;
11mod error;
12mod resolver;
13mod types;
14
15#[cfg(test)]
16mod tests;
17
18use std::{collections::HashMap, fs, rc::Rc};
19
20pub use easyfix_core::version::{SessionProtocol, Version};
21use easyfix_core::{
22    basic_types::{FixStr, FixString},
23    fix_str,
24};
25use quick_xml::de::from_str;
26
27use self::resolver::{Elements, Resolver, check_required_fields};
28pub use self::{
29    builder::DictionaryBuilder,
30    error::{BuilderError, Error, ValidationError},
31    types::{Component, Field, Group, Member, MemberDefinition, Message, Variant},
32};
33use crate::xml;
34pub use crate::xml::{BasicType, MsgCat, MsgType};
35
36impl xml::Dictionary {
37    /// Build a [`Version`] from this raw XML dictionary's header
38    /// attributes.
39    ///
40    /// Returns [`BuilderError::UnknownVersion`] (carrying the formatted
41    /// `BeginString`) when the version is not recognized.
42    pub(crate) fn version(&self) -> Result<Version, Error> {
43        Version::new(
44            self.session_protocol,
45            self.major,
46            self.minor,
47            self.servicepack,
48        )
49        .map_err(|_| {
50            let begin_string = if self.servicepack == 0 {
51                format!("{}.{}.{}", self.session_protocol, self.major, self.minor)
52            } else {
53                format!(
54                    "{}.{}.{}SP{}",
55                    self.session_protocol, self.major, self.minor, self.servicepack
56                )
57            };
58            Error::Builder(BuilderError::UnknownVersion(begin_string))
59        })
60    }
61}
62
63/// The main dictionary representing a FIX protocol specification.
64///
65/// A `Dictionary` provides access to all elements of a FIX protocol
66/// specification, including fields, components, messages, and version information.
67/// For modern FIX versions (FIXT/FIX5+), it may also contain subdictionaries
68/// for different message categories.
69#[derive(Debug)]
70pub struct Dictionary {
71    /// The version of this dictionary
72    version: Version,
73
74    /// Fields indexed by name
75    fields_by_name: HashMap<FixString, Rc<Field>>,
76
77    /// Fields indexed by ID (tag number)
78    fields_by_id: HashMap<u16, Rc<Field>>,
79
80    /// Groups indexed by name
81    groups: HashMap<FixString, Rc<Group>>,
82
83    /// Components indexed by name
84    components: HashMap<FixString, Rc<Component>>,
85
86    /// Messages in definition order (from XML)
87    messages: Vec<Rc<Message>>,
88
89    /// Messages indexed by name
90    messages_by_name: HashMap<FixString, Rc<Message>>,
91
92    /// Messages indexed by message type
93    messages_by_id: HashMap<MsgType, Rc<Message>>,
94
95    /// Standard header component definition
96    header: Component,
97
98    /// Standard trailer component definition
99    trailer: Component,
100
101    /// Application-level subdictionaries (for FIXT-based versions)
102    subdictionaries: HashMap<Version, Dictionary>,
103}
104
105impl Dictionary {
106    pub(crate) fn from_raw_dictionary(
107        raw_dictionary: xml::Dictionary,
108        _flatten: bool,
109        strict_check: bool,
110    ) -> Result<Dictionary, Error> {
111        let version = raw_dictionary.version()?;
112        let mut resolver = Resolver::new(raw_dictionary.fields, raw_dictionary.components)?;
113
114        let header = Component {
115            name: fix_str!("Header").to_owned(),
116            doc: None,
117            members: resolver.create_members(raw_dictionary.header.members, None)?,
118        };
119        let trailer = Component {
120            name: fix_str!("Trailer").to_owned(),
121            doc: None,
122            members: resolver.create_members(raw_dictionary.trailer.members, None)?,
123        };
124        if strict_check {
125            check_required_fields(&header, &trailer, version)?;
126        }
127
128        let mut messages = Vec::with_capacity(raw_dictionary.messages.len());
129        let mut messages_by_name = HashMap::with_capacity(raw_dictionary.messages.len());
130        let mut messages_by_id = HashMap::with_capacity(raw_dictionary.messages.len());
131        for raw_msg in raw_dictionary.messages {
132            let msg = Rc::new(resolver.create_message(raw_msg)?);
133            if let Some(msg) = messages_by_name.insert(msg.name.clone(), msg.clone()) {
134                return Err(Error::Validation(ValidationError::DuplicatedMessageName(
135                    msg.name.to_string(),
136                )));
137            }
138            if let Some(msg) = messages_by_id.insert(msg.msg_type, msg.clone()) {
139                return Err(Error::Validation(ValidationError::DuplicatedMessageType(
140                    msg.msg_type,
141                )));
142            }
143            messages.push(msg);
144        }
145
146        if strict_check {
147            resolver.check_unused_elements()?;
148        } else {
149            resolver.register_unused_elements()?;
150        }
151
152        let Elements {
153            fields: fields_by_name,
154            components,
155            groups,
156        } = resolver.into_elements();
157
158        let fields_by_id = fields_by_name
159            .values()
160            .map(|field| (field.number(), field.clone()))
161            .collect();
162
163        Ok(Dictionary {
164            version,
165            fields_by_name,
166            fields_by_id,
167            groups,
168            components,
169            messages,
170            messages_by_name,
171            messages_by_id,
172            header,
173            trailer,
174            subdictionaries: HashMap::new(),
175        })
176    }
177
178    /// Creates a new Dictionary by parsing a single XML specification file
179    ///
180    /// This is a convenience method for simple cases. For more complex scenarios,
181    /// use the `DictionaryBuilder` instead.
182    pub fn new(path: &str) -> Result<Dictionary, Error> {
183        let xml = fs::read_to_string(path)?;
184        let raw_dictionary: xml::Dictionary = from_str(&xml)?;
185
186        Dictionary::from_raw_dictionary(raw_dictionary, false, false)
187    }
188
189    fn flatten_component(
190        component_name: &FixStr,
191        output: &mut Vec<Member>,
192        components_map: &HashMap<FixString, Rc<Component>>,
193    ) -> Result<(), Error> {
194        // Get the component
195        let component = components_map.get(component_name).ok_or_else(|| {
196            Error::Validation(ValidationError::UnknownComponent(
197                component_name.to_string(),
198            ))
199        })?;
200
201        // Inline each member of the component with its own required flag.
202        // The component's usage-site required flag is not used - components
203        // are just grouping containers that disappear after flattening.
204        for member in &component.members {
205            match member.definition() {
206                MemberDefinition::Component(nested_comp) => {
207                    Self::flatten_component(&nested_comp.name, output, components_map)?;
208                }
209
210                MemberDefinition::Field(field) => {
211                    output.push(Member {
212                        required: member.required(),
213                        definition: MemberDefinition::Field(field.clone()),
214                    });
215                }
216
217                MemberDefinition::RawData { length, data } => {
218                    output.push(Member {
219                        required: member.required(),
220                        definition: MemberDefinition::RawData {
221                            length: length.clone(),
222                            data: data.clone(),
223                        },
224                    });
225                }
226
227                MemberDefinition::Group(group) => {
228                    let flattened_group = Self::flatten_group(group, components_map)?;
229
230                    output.push(Member {
231                        required: member.required(),
232                        definition: MemberDefinition::Group(flattened_group),
233                    });
234                }
235            }
236        }
237
238        Ok(())
239    }
240
241    // Helper function to flatten a list of members
242    fn flatten_members(
243        members: &[Member],
244        components_map: &HashMap<FixString, Rc<Component>>,
245    ) -> Result<Vec<Member>, Error> {
246        let mut flattened_members = Vec::new();
247
248        for member in members {
249            match member.definition() {
250                MemberDefinition::Component(component) => {
251                    Self::flatten_component(
252                        &component.name,
253                        &mut flattened_members,
254                        components_map,
255                    )?;
256                }
257
258                MemberDefinition::Field(field) => {
259                    flattened_members.push(Member {
260                        required: member.required(),
261                        definition: MemberDefinition::Field(field.clone()),
262                    });
263                }
264
265                MemberDefinition::RawData { length, data } => {
266                    flattened_members.push(Member {
267                        required: member.required(),
268                        definition: MemberDefinition::RawData {
269                            length: length.clone(),
270                            data: data.clone(),
271                        },
272                    });
273                }
274
275                MemberDefinition::Group(group) => {
276                    let flattened_group = Self::flatten_group(group, components_map)?;
277
278                    // Add the flattened group to the output
279                    flattened_members.push(Member {
280                        required: member.required(),
281                        definition: MemberDefinition::Group(flattened_group),
282                    });
283                }
284            }
285        }
286
287        Ok(flattened_members)
288    }
289
290    // Helper function to flatten a group
291    fn flatten_group(
292        group: &Rc<Group>,
293        components_map: &HashMap<FixString, Rc<Component>>,
294    ) -> Result<Rc<Group>, Error> {
295        let flattened_members = Self::flatten_members(group.members(), components_map)?;
296
297        // Create a new group with the flattened members
298        let flattened_group = Rc::new(Group {
299            name: group.name.clone(),
300            num_in_group: group.num_in_group.clone(),
301            doc: group.doc.clone(),
302            members: flattened_members,
303        });
304
305        Ok(flattened_group)
306    }
307
308    /// Returns a copy of this dictionary with every component inlined into
309    /// the message, group, header or trailer that used it.
310    ///
311    /// The result has an empty [`components`](Self::components) map and no
312    /// [`MemberDefinition::Component`] anywhere, so a consumer walking members
313    /// never has to resolve one. Everything else survives: message definition
314    /// order, group names, and the subdictionaries, which are flattened too.
315    ///
316    /// Each inlined field keeps the `required` flag from **its own definition
317    /// inside the component**, not the one on the component's usage site - a
318    /// field marked `required='Y'` within a component stays required even
319    /// where that component was included with `required='N'`.
320    ///
321    /// Returns [`ValidationError::UnknownComponent`] if a member references a
322    /// component this dictionary does not define.
323    pub fn flatten(&self) -> Result<Dictionary, Error> {
324        // Create copies of messages with flattened components, preserving definition order
325        let mut new_messages = Vec::with_capacity(self.messages.len());
326        let mut new_messages_by_name = HashMap::with_capacity(self.messages_by_name.len());
327        let mut new_messages_by_id = HashMap::with_capacity(self.messages_by_id.len());
328
329        for msg in &self.messages {
330            let flattened_members = Self::flatten_members(msg.members(), &self.components)?;
331            let flattened_msg = Rc::new(Message {
332                name: msg.name.clone(),
333                msg_type: msg.msg_type,
334                msg_cat: msg.msg_cat,
335                doc: msg.doc.clone(),
336                members: flattened_members,
337            });
338
339            new_messages.push(flattened_msg.clone());
340            new_messages_by_name.insert(msg.name.clone(), flattened_msg.clone());
341            new_messages_by_id.insert(msg.msg_type, flattened_msg);
342        }
343
344        // Flatten the header and trailer
345        let flattened_header_members =
346            Self::flatten_members(&self.header.members, &self.components)?;
347        let flattened_trailer_members =
348            Self::flatten_members(&self.trailer.members, &self.components)?;
349
350        let mut new_groups = HashMap::with_capacity(self.groups.len());
351        for (name, group) in &self.groups {
352            new_groups.insert(name.clone(), Self::flatten_group(group, &self.components)?);
353        }
354
355        let header = Component {
356            name: self.header.name.clone(),
357            doc: self.header.doc.clone(),
358            members: flattened_header_members,
359        };
360        let trailer = Component {
361            name: self.trailer.name.clone(),
362            doc: self.trailer.doc.clone(),
363            members: flattened_trailer_members,
364        };
365
366        let mut subdictionaries = HashMap::with_capacity(self.subdictionaries.len());
367        for (version, subdictionary) in &self.subdictionaries {
368            subdictionaries.insert(*version, subdictionary.flatten()?);
369        }
370
371        Ok(Dictionary {
372            version: self.version,
373            fields_by_name: self.fields_by_name.clone(),
374            fields_by_id: self.fields_by_id.clone(),
375            groups: new_groups,
376            components: HashMap::new(),
377            messages: new_messages,
378            messages_by_name: new_messages_by_name,
379            messages_by_id: new_messages_by_id,
380            header,
381            trailer,
382            subdictionaries,
383        })
384    }
385
386    /// Returns the version of this dictionary
387    pub fn version(&self) -> Version {
388        self.version
389    }
390
391    /// Returns the BeginString representation of this dictionary's version.
392    pub fn begin_string(&self) -> String {
393        self.version.to_string()
394    }
395
396    /// Looks up a field by name
397    pub fn field_by_name(&self, name: &FixStr) -> Option<&Field> {
398        self.fields_by_name.get(name).map(|v| &**v)
399    }
400
401    /// Looks up a field by tag number
402    pub fn field_by_id(&self, id: u16) -> Option<&Field> {
403        self.fields_by_id.get(&id).map(|v| &**v)
404    }
405
406    /// Returns an iterator over all fields in this dictionary
407    pub fn fields(&self) -> impl Iterator<Item = &Field> {
408        self.fields_by_id.values().map(|v| &**v)
409    }
410
411    /// Looks up a component by name
412    pub fn component(&self, name: &FixStr) -> Option<&Component> {
413        self.components.get(name).map(|v| &**v)
414    }
415
416    /// Returns an iterator over all components in this dictionary
417    pub fn components(&self) -> impl Iterator<Item = &Component> {
418        self.components.values().map(|v| &**v)
419    }
420
421    /// Looks up a group by name
422    pub fn group(&self, name: &FixStr) -> Option<&Group> {
423        self.groups.get(name).map(|v| &**v)
424    }
425
426    /// Returns an iterator over all groups in this dictionary
427    pub fn groups(&self) -> impl Iterator<Item = &Group> {
428        self.groups.values().map(|v| &**v)
429    }
430
431    /// Looks up a message by name
432    pub fn message_by_name(&self, name: &FixStr) -> Option<&Message> {
433        self.messages_by_name.get(name).map(|v| &**v)
434    }
435
436    /// Looks up a message by message type
437    pub fn message_by_type(&self, msg_type: &[u8]) -> Option<&Message> {
438        self.messages_by_id.get(msg_type).map(|v| &**v)
439    }
440
441    /// Returns an iterator over all messages in this dictionary, in definition order
442    pub fn messages(&self) -> impl Iterator<Item = &Message> {
443        self.messages.iter().map(|v| &**v)
444    }
445
446    /// Returns a reference to the standard header component
447    ///
448    /// The header component contains fields that appear at the beginning of every message.
449    pub fn header(&self) -> &Component {
450        &self.header
451    }
452
453    /// Returns a reference to the standard trailer component
454    ///
455    /// The trailer component contains fields that appear at the end of every message.
456    pub fn trailer(&self) -> &Component {
457        &self.trailer
458    }
459
460    /// Returns a subdictionary for the specified version, if available
461    ///
462    /// For FIXT-based FIX versions, this allows access to application-level dictionaries.
463    pub fn subdictionary(&self, version: Version) -> Option<&Dictionary> {
464        self.subdictionaries.get(&version)
465    }
466
467    /// Returns an iterator over all subdictionaries
468    ///
469    /// For FIXT-based FIX versions, this provides access to application-level dictionaries.
470    pub fn subdictionaries(&self) -> impl Iterator<Item = &Dictionary> {
471        self.subdictionaries.values()
472    }
473}