Skip to main content

refix_dictionary/
spec.rs

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