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