Skip to main content

easyfix_dictionary/dictionary/
types.rs

1use std::rc::Rc;
2
3use easyfix_core::basic_types::{FixStr, FixString};
4
5use crate::{
6    xml,
7    xml::{BasicType, MsgCat, MsgType},
8};
9
10/// An enumerated value variant for a FIX field.
11///
12/// Some FIX fields have a predefined set of valid values, each with a
13/// specific meaning. For example, the `Side` field (tag 54) has variants
14/// like `1` (Buy) and `2` (Sell).
15#[derive(Clone, Debug)]
16pub struct Variant {
17    /// Name of this variant (e.g., "Buy", "Sell")
18    name: FixString,
19    /// The raw value from the field definition (e.g., "1", "2")
20    value: FixString,
21    /// Optional documentation text for this variant
22    doc: Option<String>,
23}
24
25impl Variant {
26    /// Returns the name of this variant
27    pub fn name(&self) -> &FixStr {
28        &self.name
29    }
30
31    /// Returns the raw value of this variant
32    pub fn value(&self) -> &FixStr {
33        &self.value
34    }
35
36    /// Returns the documentation text of this variant, if any
37    pub fn doc(&self) -> Option<&str> {
38        self.doc.as_deref()
39    }
40}
41
42impl From<xml::Value> for Variant {
43    fn from(v: xml::Value) -> Self {
44        Variant {
45            name: v.description,
46            value: v.value_enum,
47            doc: v.doc,
48        }
49    }
50}
51
52/// A field definition in the FIX dictionary.
53///
54/// Fields are the basic elements of FIX messages, representing individual
55/// data points with specific types and possible enumerated variants.
56#[derive(Clone, Debug)]
57pub struct Field {
58    /// The tag number that identifies this field
59    pub(super) number: u16,
60    /// The human-readable name of this field
61    pub(super) name: FixString,
62    /// The data type of this field
63    pub(super) data_type: BasicType,
64    /// Optional documentation text for this field
65    pub(super) doc: Option<String>,
66    /// Enumerated variants for this field
67    pub(super) variants: Vec<Variant>,
68}
69
70impl Field {
71    /// Returns the tag number that identifies this field
72    pub fn number(&self) -> u16 {
73        self.number
74    }
75
76    /// Returns the name of this field
77    pub fn name(&self) -> &FixStr {
78        &self.name
79    }
80
81    /// Returns the data type of this field
82    pub fn data_type(&self) -> BasicType {
83        self.data_type
84    }
85
86    /// Returns the enumerated variants for this field
87    pub fn variants(&self) -> &[Variant] {
88        &self.variants
89    }
90
91    /// Returns the documentation text of this field, if any
92    pub fn doc(&self) -> Option<&str> {
93        self.doc.as_deref()
94    }
95}
96
97impl From<xml::Field> for Field {
98    fn from(f: xml::Field) -> Self {
99        Field {
100            number: f.number,
101            name: f.name,
102            data_type: f.data_type,
103            doc: f.doc,
104            variants: f
105                .values
106                .unwrap_or_default()
107                .into_iter()
108                .map(Variant::from)
109                .collect(),
110        }
111    }
112}
113
114/// The shared definition of a field, component, or group: **what** a member
115/// is, separate from **how** it is used.
116///
117/// One definition is referenced by many [`Member`]s, each carrying the
118/// `required` flag of its own usage site.
119//
120// # Why `Rc<>`?
121//
122// In FIX dictionaries, components and groups are typically defined once but
123// referenced many times - a component like "Instrument" or "Parties" appears
124// in dozens of message types:
125//
126//     Component Definition (1x in memory)
127//           |
128//           +--> Member in Message A (required=true)
129//           +--> Member in Message B (required=false)
130//           +--> Member in Message C (required=true)
131#[derive(Clone, Debug)]
132pub enum MemberDefinition {
133    /// A field member (primitive element)
134    Field(Rc<Field>),
135
136    /// A raw data member (Length + Data/XmlData pair)
137    ///
138    /// In the FIX protocol, fields of type Data or XmlData must be immediately
139    /// preceded by an associated Length field. This variant represents that pair
140    /// as a single semantic unit, since the data may contain arbitrary bytes
141    /// including the SOH delimiter.
142    RawData {
143        /// The Length field that specifies the byte count
144        length: Rc<Field>,
145        /// The Data or XmlData field containing the raw bytes
146        data: Rc<Field>,
147    },
148
149    /// A component member (reusable collection of fields/components/groups)
150    Component(Rc<Component>),
151
152    /// A group member (repeating section of fields/components)
153    Group(Rc<Group>),
154}
155
156impl MemberDefinition {
157    /// Returns the name of this member definition
158    ///
159    /// The name corresponds to the name of the underlying field, component, or group.
160    pub fn name(&self) -> &FixStr {
161        match self {
162            MemberDefinition::Field(field) => &field.name,
163            MemberDefinition::RawData { data, .. } => &data.name,
164            MemberDefinition::Component(component) => &component.name,
165            MemberDefinition::Group(group) => &group.name,
166        }
167    }
168}
169
170/// A member reference within a message, component, or group.
171///
172/// Represents a **usage** of a field, component, or group, separate from its
173/// [`MemberDefinition`]: the definition is shared, while the `required` flag
174/// belongs to this one usage site. `Instrument` can be `required='Y'` in
175/// `NewOrderSingle` and `required='N'` in `OrderCancelRequest`, both pointing
176/// at the same definition.
177#[derive(Clone, Debug)]
178pub struct Member {
179    /// Whether this member is required (mandatory) in its parent container
180    pub(super) required: bool,
181
182    /// The underlying definition of this member
183    pub(super) definition: MemberDefinition,
184}
185
186impl Member {
187    /// Returns a reference to the underlying definition of this member
188    ///
189    /// The definition provides access to the field, component, or group that
190    /// this member represents.
191    pub fn definition(&self) -> &MemberDefinition {
192        &self.definition
193    }
194
195    /// Returns whether this member is required in its parent container
196    ///
197    /// Required members must be present in valid FIX messages.
198    pub fn required(&self) -> bool {
199        self.required
200    }
201
202    /// Returns the name of this member
203    ///
204    /// This is a convenience method that delegates to the underlying definition.
205    /// Works for fields, components, and groups.
206    pub fn name(&self) -> &FixStr {
207        self.definition.name()
208    }
209
210    /// Returns this member as a field reference if it is a field
211    pub fn as_field(&self) -> Option<&Field> {
212        match &self.definition {
213            MemberDefinition::Field(field) => Some(field),
214            _ => None,
215        }
216    }
217
218    /// Returns the `(length, data)` field references if this member is raw data
219    pub fn as_raw_data(&self) -> Option<(&Field, &Field)> {
220        match &self.definition {
221            MemberDefinition::RawData { length, data } => Some((length, data)),
222            _ => None,
223        }
224    }
225
226    /// Returns this member as a component reference if it is a component
227    pub fn as_component(&self) -> Option<&Component> {
228        match &self.definition {
229            MemberDefinition::Component(component) => Some(component),
230            _ => None,
231        }
232    }
233
234    /// Returns this member as a group reference if it is a group
235    pub fn as_group(&self) -> Option<&Group> {
236        match &self.definition {
237            MemberDefinition::Group(group) => Some(group),
238            _ => None,
239        }
240    }
241
242    /// Returns true if this member is a field
243    pub fn is_field(&self) -> bool {
244        matches!(self.definition, MemberDefinition::Field(_))
245    }
246
247    /// Returns true if this member is a raw data pair (Length + Data/XmlData)
248    pub fn is_raw_data(&self) -> bool {
249        matches!(self.definition, MemberDefinition::RawData { .. })
250    }
251
252    /// Returns true if this member is a component
253    pub fn is_component(&self) -> bool {
254        matches!(self.definition, MemberDefinition::Component(_))
255    }
256
257    /// Returns true if this member is a group
258    pub fn is_group(&self) -> bool {
259        matches!(self.definition, MemberDefinition::Group(_))
260    }
261}
262
263/// Represents a repeating group in the FIX protocol.
264///
265/// A group is a collection of fields, components, and/or nested groups
266/// that can appear multiple times within a message. Each group has a
267/// counter field that specifies how many instances of the group appear.
268///
269/// # Naming Convention
270///
271/// In XML dictionaries, groups follow a naming convention:
272/// - The counter field uses the "No" prefix: `NoHops`, `NoLegs`, `NoPartyIDs`
273/// - The group name omits the prefix: `Hops`, `Legs`, `PartyIDs`
274///
275/// ## Example
276///
277/// From the XML:
278/// ```xml
279/// <group name='NoHops' required='N'>
280///   <field name='HopCompID' required='N' />
281///   <field name='HopSendingTime' required='N' />
282/// </group>
283/// ```
284///
285/// Creates a `Group` with:
286/// - `name()` returns `"Hops"`
287/// - `num_in_group()` returns the field `"NoHops"` (tag 627)
288/// - `members()` contains `HopCompID` and `HopSendingTime`
289#[derive(Debug)]
290pub struct Group {
291    /// Name of the group (without "No" prefix)
292    pub(super) name: FixString,
293
294    /// The NumInGroup counter field (with "No" prefix)
295    pub(super) num_in_group: Rc<Field>,
296
297    /// Optional documentation text for this group
298    pub(super) doc: Option<String>,
299
300    /// Members (fields, components, and nested groups) within this group
301    pub(super) members: Vec<Member>,
302}
303
304impl Group {
305    /// Returns the name of this group
306    pub fn name(&self) -> &FixStr {
307        &self.name
308    }
309
310    /// Returns the documentation text of this group, if any
311    ///
312    /// For a group unwrapped from a component that contained only this group,
313    /// this is the component's documentation if present, otherwise the
314    /// group's own documentation - mirroring how the group takes over the
315    /// component's name.
316    pub fn doc(&self) -> Option<&str> {
317        self.doc.as_deref()
318    }
319
320    /// Returns a reference to the NumInGroup field that counts instances of this group
321    ///
322    /// In the FIX protocol, repeating groups start with a field that indicates
323    /// how many instances of the group follow.
324    pub fn num_in_group(&self) -> &Field {
325        &self.num_in_group
326    }
327
328    /// Returns all members (fields, components, and nested groups) in this group
329    pub fn members(&self) -> &[Member] {
330        &self.members
331    }
332}
333
334/// Represents a reusable component in the FIX protocol.
335///
336/// Components are reusable collections of fields, groups, and other components
337/// that can be included in multiple message types or other components.
338#[derive(Debug)]
339pub struct Component {
340    /// Name of the component
341    pub(super) name: FixString,
342
343    /// Optional documentation text for this component
344    pub(super) doc: Option<String>,
345
346    /// Members (fields, groups, and other components) within this component
347    pub(super) members: Vec<Member>,
348}
349
350impl Component {
351    /// Returns the name of this component
352    pub fn name(&self) -> &FixStr {
353        &self.name
354    }
355
356    /// Returns the documentation text of this component, if any
357    pub fn doc(&self) -> Option<&str> {
358        self.doc.as_deref()
359    }
360
361    /// Returns all members (fields, components, and groups) in this component
362    pub fn members(&self) -> &[Member] {
363        &self.members
364    }
365}
366
367/// Represents a FIX protocol message definition.
368///
369/// A message is a complete unit of communication in the FIX protocol,
370/// consisting of various fields, components, and groups.
371#[derive(Debug)]
372pub struct Message {
373    /// Human-readable name of the message (e.g., "Heartbeat")
374    pub(super) name: FixString,
375
376    /// Message type identifier (e.g., "0" for Heartbeat)
377    pub(super) msg_type: MsgType,
378
379    /// Category of the message (Admin or App)
380    pub(super) msg_cat: MsgCat,
381
382    /// Optional documentation text for this message
383    pub(super) doc: Option<String>,
384
385    /// Members (fields, components, and groups) that make up this message
386    pub(super) members: Vec<Member>,
387}
388
389impl Message {
390    /// Returns the human-readable name of this message
391    pub fn name(&self) -> &FixStr {
392        &self.name
393    }
394
395    /// Returns the message type identifier
396    ///
397    /// The message type is a short code (1-2 characters) that uniquely identifies
398    /// this message type in the FIX protocol (e.g., "0" for Heartbeat)
399    pub fn msg_type(&self) -> MsgType {
400        self.msg_type
401    }
402
403    /// Returns the category of this message (Admin or App)
404    pub fn msg_cat(&self) -> MsgCat {
405        self.msg_cat
406    }
407
408    /// Returns the documentation text of this message, if any
409    pub fn doc(&self) -> Option<&str> {
410        self.doc.as_deref()
411    }
412
413    /// Returns all members (fields, components, and groups) in this message
414    pub fn members(&self) -> &[Member] {
415        &self.members
416    }
417}