Skip to main content

refix_dictionary/
spec.rs

1use refix_message::Tag;
2use std::borrow::Cow;
3use std::fmt;
4
5/// The fields, messages, components, header and trailer of one FIX version
6/// or venue dialect, as authored.
7///
8/// A spec is plain data and makes no consistency guarantees. It is what
9/// frontends parse into and what dialect authors construct by hand.
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct Spec {
12    pub version: Version,
13    /// The members every message starts with, in source order.
14    pub header: Vec<Member>,
15    pub messages: Vec<Message>,
16    /// The members every message ends with, in source order.
17    pub trailer: Vec<Member>,
18    pub fields: Vec<Field>,
19    pub components: Vec<Component>,
20}
21
22/// The definition of a FIX message type.
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub struct Message {
25    /// The name of the message type.
26    pub name: String,
27    /// The wire value of `MsgType(35)`, verbatim, e.g. `"D"`.
28    pub msg_type: String,
29    /// The message's members in source order.
30    pub members: Vec<Member>,
31    /// The category of this message.
32    pub category: Category,
33}
34
35/// A field definition, as listed in the dictionary's fields section.
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct Field {
38    pub name: String,
39    pub tag: Tag,
40    pub data_type: DataType,
41    pub values: Vec<EnumValue>,
42}
43
44/// A component definition, as listed in the dictionary's components section.
45#[derive(Clone, Debug, Eq, PartialEq)]
46pub struct Component {
47    /// The name of the component.
48    pub name: String,
49    /// The component's members in source order.
50    pub members: Vec<Member>,
51}
52
53/// A member of a message, component or group instance.
54///
55/// This can be a field reference, a component reference or a repeating group.
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub enum Member {
58    Field(FieldRef),
59    Component(ComponentRef),
60    Group(Group),
61}
62
63/// A field as used by one message or component (Orchestra's `fieldRef`).
64#[derive(Clone, Debug, Eq, PartialEq)]
65pub struct FieldRef {
66    /// Tag of the referenced [`Field`] definition.
67    pub tag: Tag,
68    pub is_required: bool,
69}
70
71/// A component as used by one message or component.
72#[derive(Clone, Debug, Eq, PartialEq)]
73pub struct ComponentRef {
74    /// Name of the referenced [`Component`] definition.
75    pub name: String,
76    pub is_required: bool,
77}
78
79/// A repeating group, declared inline in a message, component or group
80/// instance.
81#[derive(Clone, Debug, Eq, PartialEq)]
82pub struct Group {
83    /// Tag of the group's NumInGroup count field.
84    pub count_tag: Tag,
85    pub is_required: bool,
86    /// The members of each instance, in source order.
87    pub members: Vec<Member>,
88}
89
90/// The message, component, group instance, header or trailer a member
91/// appears in.
92///
93/// Diagnostics use this to name the place a problem was found.
94#[derive(Clone, Debug, Eq, Hash, PartialEq)]
95pub enum MemberContext {
96    Message(String),
97    Component(String),
98    Header,
99    Trailer,
100    /// A group's instances, named after the group's count field.
101    Group {
102        name: String,
103        parent: Box<MemberContext>,
104    },
105}
106
107impl MemberContext {
108    /// The context of a group's instances, nested in this context.
109    pub fn group(&self, name: &str) -> MemberContext {
110        MemberContext::Group {
111            name: name.to_owned(),
112            parent: Box::new(self.clone()),
113        }
114    }
115}
116
117impl fmt::Display for MemberContext {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        match self {
120            Self::Message(name) => write!(f, "message '{name}'"),
121            Self::Component(name) => write!(f, "component '{name}'"),
122            Self::Header => write!(f, "the header"),
123            Self::Trailer => write!(f, "the trailer"),
124            Self::Group { name, parent } => write!(f, "group '{name}' in {parent}"),
125        }
126    }
127}
128
129/// An enum variant's value.
130///
131/// This models the `<value enum="..." description="..." />` elements in a field definition.
132#[derive(Clone, Debug, Eq, PartialEq)]
133pub struct EnumValue {
134    pub value: String,
135    pub description: String,
136}
137
138/// The FIX data type of a field, as declared in the dictionary.
139#[derive(Clone, Debug, Eq, PartialEq)]
140pub enum DataType {
141    String,
142    Int,
143    Length,
144    NumInGroup,
145    SeqNum,
146    TagNum,
147    DayOfMonth,
148    Float,
149    Qty,
150    Price,
151    PriceOffset,
152    Amt,
153    Percentage,
154    Char,
155    Boolean,
156    MultipleCharValue,
157    /// Also FIX 4.4's `MultipleValueString`.
158    MultipleStringValue,
159    Currency,
160    Exchange,
161    Country,
162    Language,
163    Xid,
164    XidRef,
165    /// Also FIX 4.0 and 4.1's `Time`.
166    UtcTimestamp,
167    UtcTimeOnly,
168    /// Also FIX 4.2 and 4.3's `UtcDate`.
169    UtcDateOnly,
170    /// Also FIX 4.0 and 4.1's `Date`.
171    LocalMktDate,
172    LocalMktTime,
173    MonthYear,
174    TzTimestamp,
175    TzTimeOnly,
176    Data,
177    XmlData,
178    /// A type outside the standard, such as a venue's own.
179    Other(String),
180}
181
182/// The type's name in upper case, as dictionaries declare it, or a type outside
183/// the standard as given.
184impl fmt::Display for DataType {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        let name = match self {
187            Self::String => "STRING",
188            Self::Int => "INT",
189            Self::Length => "LENGTH",
190            Self::NumInGroup => "NUMINGROUP",
191            Self::SeqNum => "SEQNUM",
192            Self::TagNum => "TAGNUM",
193            Self::DayOfMonth => "DAYOFMONTH",
194            Self::Float => "FLOAT",
195            Self::Qty => "QTY",
196            Self::Price => "PRICE",
197            Self::PriceOffset => "PRICEOFFSET",
198            Self::Amt => "AMT",
199            Self::Percentage => "PERCENTAGE",
200            Self::Char => "CHAR",
201            Self::Boolean => "BOOLEAN",
202            Self::MultipleCharValue => "MULTIPLECHARVALUE",
203            Self::MultipleStringValue => "MULTIPLESTRINGVALUE",
204            Self::Currency => "CURRENCY",
205            Self::Exchange => "EXCHANGE",
206            Self::Country => "COUNTRY",
207            Self::Language => "LANGUAGE",
208            Self::Xid => "XID",
209            Self::XidRef => "XIDREF",
210            Self::UtcTimestamp => "UTCTIMESTAMP",
211            Self::UtcTimeOnly => "UTCTIMEONLY",
212            Self::UtcDateOnly => "UTCDATEONLY",
213            Self::LocalMktDate => "LOCALMKTDATE",
214            Self::LocalMktTime => "LOCALMKTTIME",
215            Self::MonthYear => "MONTHYEAR",
216            Self::TzTimestamp => "TZTIMESTAMP",
217            Self::TzTimeOnly => "TZTIMEONLY",
218            Self::Data => "DATA",
219            Self::XmlData => "XMLDATA",
220            Self::Other(name) => name,
221        };
222        f.write_str(name)
223    }
224}
225
226impl DataType {
227    /// Whether the type is `Int` or one of its subtypes.
228    pub fn is_int_based(&self) -> bool {
229        matches!(
230            self,
231            Self::Int
232                | Self::Length
233                | Self::NumInGroup
234                | Self::SeqNum
235                | Self::TagNum
236                | Self::DayOfMonth
237        )
238    }
239
240    /// Whether the type is `Float` or one of its subtypes.
241    pub fn is_float_based(&self) -> bool {
242        matches!(
243            self,
244            Self::Float
245                | Self::Qty
246                | Self::Price
247                | Self::PriceOffset
248                | Self::Amt
249                | Self::Percentage
250        )
251    }
252
253    /// Whether the type holds space-delimited values, as `ExecInst(18)` does.
254    pub fn is_multiple_value(&self) -> bool {
255        matches!(self, Self::MultipleCharValue | Self::MultipleStringValue)
256    }
257
258    /// A code in the form every code for its value shares.
259    ///
260    /// An int-based type reads codes as numbers, so `01` and `1` agree.
261    pub(crate) fn canonical_code<'a>(&self, code: &'a str) -> Cow<'a, str> {
262        match code.parse::<i64>() {
263            Ok(number) if self.is_int_based() => Cow::Owned(number.to_string()),
264            _ => Cow::Borrowed(code),
265        }
266    }
267}
268
269/// The FIX version a dictionary describes, e.g. FIX 4.4 or FIXT 1.1.
270#[derive(Clone, Copy, Debug, Eq, PartialEq)]
271pub struct Version {
272    pub protocol: Protocol,
273    pub major: u8,
274    pub minor: u8,
275    pub service_pack: u8,
276}
277
278/// The protocol family a dictionary belongs to.
279#[derive(Clone, Copy, Debug, Eq, PartialEq)]
280pub enum Protocol {
281    /// Classic FIX (4.x and earlier), session and application layers in
282    /// one dictionary.
283    Fix,
284    /// The FIXT transport (FIX 5.x onwards), where the session layer is
285    /// versioned separately from application semantics.
286    Fixt,
287}
288
289/// Whether a message belongs to the session layer or the application layer.
290#[derive(Clone, Copy, Debug, Eq, PartialEq)]
291pub enum Category {
292    /// Session-level machinery: Logon, Heartbeat, Reject, etc.
293    Admin,
294    /// Business messages: orders, executions, market data.
295    App,
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn the_int_family_is_int_based() {
304        for data_type in [
305            DataType::Int,
306            DataType::Length,
307            DataType::NumInGroup,
308            DataType::SeqNum,
309            DataType::TagNum,
310            DataType::DayOfMonth,
311        ] {
312            assert!(data_type.is_int_based(), "{data_type:?}");
313        }
314    }
315
316    #[test]
317    fn other_types_are_not_int_based() {
318        for data_type in [
319            DataType::String,
320            DataType::Char,
321            DataType::MultipleStringValue,
322            DataType::Price,
323            DataType::Other("CUSTOM".to_owned()),
324        ] {
325            assert!(!data_type.is_int_based(), "{data_type:?}");
326        }
327    }
328
329    #[test]
330    fn the_float_family_is_float_based() {
331        for data_type in [
332            DataType::Float,
333            DataType::Qty,
334            DataType::Price,
335            DataType::PriceOffset,
336            DataType::Amt,
337            DataType::Percentage,
338        ] {
339            assert!(data_type.is_float_based(), "{data_type:?}");
340        }
341    }
342
343    #[test]
344    fn other_types_are_not_float_based() {
345        for data_type in [
346            DataType::Int,
347            DataType::String,
348            DataType::UtcTimestamp,
349            DataType::Other("CUSTOM".to_owned()),
350        ] {
351            assert!(!data_type.is_float_based(), "{data_type:?}");
352        }
353    }
354
355    #[test]
356    fn the_multiple_value_types_hold_multiple_values() {
357        assert!(DataType::MultipleCharValue.is_multiple_value());
358        assert!(DataType::MultipleStringValue.is_multiple_value());
359        assert!(!DataType::String.is_multiple_value());
360        assert!(!DataType::Char.is_multiple_value());
361    }
362
363    #[test]
364    fn int_codes_are_canonical_as_numbers() {
365        assert_eq!(DataType::Int.canonical_code("01"), "1");
366        assert_eq!(DataType::Int.canonical_code("-007"), "-7");
367        assert_eq!(DataType::Char.canonical_code("01"), "01");
368    }
369
370    #[test]
371    fn a_header_group_names_the_header() {
372        assert_eq!(
373            MemberContext::Header.group("NoHops").to_string(),
374            "group 'NoHops' in the header"
375        );
376        assert_eq!(MemberContext::Trailer.to_string(), "the trailer");
377    }
378
379    #[test]
380    fn a_nested_group_context_names_its_whole_path() {
381        let context = MemberContext::Group {
382            name: "NoPartySubIDs".to_owned(),
383            parent: Box::new(MemberContext::Group {
384                name: "NoPartyIDs".to_owned(),
385                parent: Box::new(MemberContext::Component("Parties".to_owned())),
386            }),
387        };
388
389        assert_eq!(
390            context.to_string(),
391            "group 'NoPartySubIDs' in group 'NoPartyIDs' in component 'Parties'"
392        );
393
394        assert_eq!(
395            context.to_string(),
396            "group 'NoPartySubIDs' in group 'NoPartyIDs' in component 'Parties'"
397        );
398    }
399}