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    Char,
149    MultipleCharValue,
150    /// Also FIX 4.4's `MultipleValueString`.
151    MultipleStringValue,
152    /// A type no consumer interprets yet, e.g. `"PRICE"`.
153    Other(String),
154}
155
156impl DataType {
157    /// Whether the type is `Int` or one of its subtypes.
158    pub fn is_int_based(&self) -> bool {
159        matches!(
160            self,
161            Self::Int
162                | Self::Length
163                | Self::NumInGroup
164                | Self::SeqNum
165                | Self::TagNum
166                | Self::DayOfMonth
167        )
168    }
169
170    /// Whether the type holds space-delimited values, as `ExecInst(18)` does.
171    pub fn is_multiple_value(&self) -> bool {
172        matches!(self, Self::MultipleCharValue | Self::MultipleStringValue)
173    }
174
175    /// A code in the form every code for its value shares.
176    ///
177    /// An int-based type reads codes as numbers, so `01` and `1` agree.
178    pub(crate) fn canonical_code<'a>(&self, code: &'a str) -> Cow<'a, str> {
179        match code.parse::<i64>() {
180            Ok(number) if self.is_int_based() => Cow::Owned(number.to_string()),
181            _ => Cow::Borrowed(code),
182        }
183    }
184}
185
186/// The FIX version a dictionary describes, e.g. FIX 4.4 or FIXT 1.1.
187#[derive(Clone, Copy, Debug, Eq, PartialEq)]
188pub struct Version {
189    pub protocol: Protocol,
190    pub major: u8,
191    pub minor: u8,
192    pub service_pack: u8,
193}
194
195/// The protocol family a dictionary belongs to.
196#[derive(Clone, Copy, Debug, Eq, PartialEq)]
197pub enum Protocol {
198    /// Classic FIX (4.x and earlier), session and application layers in
199    /// one dictionary.
200    Fix,
201    /// The FIXT transport (FIX 5.x onwards), where the session layer is
202    /// versioned separately from application semantics.
203    Fixt,
204}
205
206/// Whether a message belongs to the session layer or the application layer.
207#[derive(Clone, Copy, Debug, Eq, PartialEq)]
208pub enum Category {
209    /// Session-level machinery: Logon, Heartbeat, Reject, etc.
210    Admin,
211    /// Business messages: orders, executions, market data.
212    App,
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    #[test]
220    fn the_int_family_is_int_based() {
221        for data_type in [
222            DataType::Int,
223            DataType::Length,
224            DataType::NumInGroup,
225            DataType::SeqNum,
226            DataType::TagNum,
227            DataType::DayOfMonth,
228        ] {
229            assert!(data_type.is_int_based(), "{data_type:?}");
230        }
231    }
232
233    #[test]
234    fn other_types_are_not_int_based() {
235        for data_type in [
236            DataType::String,
237            DataType::Char,
238            DataType::MultipleStringValue,
239            DataType::Other("PRICE".to_owned()),
240        ] {
241            assert!(!data_type.is_int_based(), "{data_type:?}");
242        }
243    }
244
245    #[test]
246    fn the_multiple_value_types_hold_multiple_values() {
247        assert!(DataType::MultipleCharValue.is_multiple_value());
248        assert!(DataType::MultipleStringValue.is_multiple_value());
249        assert!(!DataType::String.is_multiple_value());
250        assert!(!DataType::Char.is_multiple_value());
251    }
252
253    #[test]
254    fn int_codes_are_canonical_as_numbers() {
255        assert_eq!(DataType::Int.canonical_code("01"), "1");
256        assert_eq!(DataType::Int.canonical_code("-007"), "-7");
257        assert_eq!(DataType::Char.canonical_code("01"), "01");
258    }
259
260    #[test]
261    fn a_header_group_names_the_header() {
262        assert_eq!(
263            MemberContext::Header.group("NoHops").to_string(),
264            "group 'NoHops' in the header"
265        );
266        assert_eq!(MemberContext::Trailer.to_string(), "the trailer");
267    }
268
269    #[test]
270    fn a_nested_group_context_names_its_whole_path() {
271        let context = MemberContext::Group {
272            name: "NoPartySubIDs".to_owned(),
273            parent: Box::new(MemberContext::Group {
274                name: "NoPartyIDs".to_owned(),
275                parent: Box::new(MemberContext::Component("Parties".to_owned())),
276            }),
277        };
278
279        assert_eq!(
280            context.to_string(),
281            "group 'NoPartySubIDs' in group 'NoPartyIDs' in component 'Parties'"
282        );
283
284        assert_eq!(
285            context.to_string(),
286            "group 'NoPartySubIDs' in group 'NoPartyIDs' in component 'Parties'"
287        );
288    }
289}