Skip to main content

refix_message/
message.rs

1use crate::Tag;
2use crate::value::InvalidValue;
3use bytes::Bytes;
4
5/// A field's position in a message's index.
6#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
7pub struct Slot(u32);
8
9impl Slot {
10    /// The first field of a message, always `BeginString`.
11    pub const START: Slot = Slot(0);
12
13    fn index(self) -> usize {
14        self.0 as usize
15    }
16
17    /// The slot after this one.
18    pub(crate) fn next(self) -> Slot {
19        Slot(self.0 + 1)
20    }
21}
22
23/// The tag and byte range of a field's value within the frame.
24#[derive(Clone, Copy, Debug)]
25pub(crate) struct RawField {
26    pub(crate) tag: Tag,
27    pub(crate) value_start: u32,
28    pub(crate) value_end: u32,
29}
30
31/// Raw bytes of a FIX message and an index of every field in wire order.
32#[derive(Clone, Debug)]
33pub struct RawMessage {
34    bytes: Bytes,
35    fields: Vec<RawField>,
36}
37
38impl RawMessage {
39    pub(crate) fn new(bytes: Bytes, fields: Vec<RawField>) -> Self {
40        Self { bytes, fields }
41    }
42
43    /// The whole frame, from `8=` to the SOH after CheckSum.
44    pub fn bytes(&self) -> &Bytes {
45        &self.bytes
46    }
47
48    /// The whole frame as a [`Scope`].
49    pub fn scope(&self) -> Scope<'_> {
50        Scope {
51            message: self,
52            start: Slot::START,
53            end: Slot(self.fields.len() as u32),
54        }
55    }
56
57    /// The scope over the fields from `start` up to `end`, or `None` if
58    /// they don't fit this message.
59    pub fn scope_between(&self, start: Slot, end: Slot) -> Option<Scope<'_>> {
60        (start <= end && end.index() <= self.fields.len()).then_some(Scope {
61            message: self,
62            start,
63            end,
64        })
65    }
66
67    /// Value of the first occurrence of `tag`, scanning from the start.
68    pub fn get(&self, tag: Tag) -> Option<&[u8]> {
69        self.scope().get(tag)
70    }
71
72    /// First occurrence of `tag` as UTF-8 text or `Ok(None)` when absent.
73    pub fn get_str(&self, tag: Tag) -> Result<Option<&str>, InvalidValue> {
74        self.scope().get_str(tag)
75    }
76
77    /// First occurrence of `tag` parsed as an integer or `Ok(None)` when absent.
78    pub fn get_int(&self, tag: Tag) -> Result<Option<i64>, InvalidValue> {
79        self.scope().get_int(tag)
80    }
81
82    /// Every field as `(tag, value)`, in wire order, duplicates included.
83    ///
84    /// Includes an entry with [`Tag::MALFORMED`] for any byte run that could
85    /// not be tokenised, so the entries cover the whole frame.
86    pub fn entries(&self) -> impl Iterator<Item = (Tag, &[u8])> {
87        self.fields
88            .iter()
89            .map(|&field| (field.tag, self.slice(field)))
90    }
91
92    fn value(&self, slot: Slot) -> &[u8] {
93        self.slice(self.fields[slot.index()])
94    }
95
96    fn slice(&self, field: RawField) -> &[u8] {
97        &self.bytes[field.value_start as usize..field.value_end as usize]
98    }
99
100    /// The index itself, for tests asserting offset-level invariants.
101    #[cfg(test)]
102    pub(crate) fn raw_fields(&self) -> &[RawField] {
103        &self.fields
104    }
105}
106
107/// A bounded view of a message's fields - the whole frame or one group
108/// instance.
109#[derive(Clone, Copy, Debug)]
110pub struct Scope<'a> {
111    message: &'a RawMessage,
112    start: Slot,
113    end: Slot,
114}
115
116impl<'a> Scope<'a> {
117    /// Value of the first occurrence of `tag` in this scope.
118    pub fn get(&self, tag: Tag) -> Option<&'a [u8]> {
119        self.find(tag, self.start).map(|(_, value)| value)
120    }
121
122    /// First occurrence of `tag` as UTF-8 text or `Ok(None)` when absent.
123    pub fn get_str(&self, tag: Tag) -> Result<Option<&'a str>, InvalidValue> {
124        let Some(value) = self.get(tag) else {
125            return Ok(None);
126        };
127        let value = std::str::from_utf8(value).map_err(|_| InvalidValue { tag })?;
128        Ok(Some(value))
129    }
130
131    /// First occurrence of `tag` parsed as an integer or `Ok(None)` when absent.
132    pub fn get_int(&self, tag: Tag) -> Result<Option<i64>, InvalidValue> {
133        let Some(value) = self.get_str(tag)? else {
134            return Ok(None);
135        };
136        let value = value.parse().map_err(|_| InvalidValue { tag })?;
137        Ok(Some(value))
138    }
139
140    /// First occurrence of `tag` at or after `from` and before the end of
141    /// the scope, with its slot so the caller can continue or bound a range.
142    pub(crate) fn find(&self, tag: Tag, from: Slot) -> Option<(Slot, &'a [u8])> {
143        let fields = self.message.fields.get(from.index()..self.end.index())?;
144        let offset = fields.iter().position(|field| field.tag == tag)?;
145        let slot = Slot((from.index() + offset) as u32);
146        Some((slot, self.message.value(slot)))
147    }
148
149    /// The fields `start..end` of the same message.
150    pub(crate) fn narrow(&self, start: Slot, end: Slot) -> Scope<'a> {
151        Scope {
152            message: self.message,
153            start,
154            end,
155        }
156    }
157
158    /// The slot of this scope's first field.
159    pub fn start(&self) -> Slot {
160        self.start
161    }
162
163    /// The slot just past this scope's last field.
164    pub fn end(&self) -> Slot {
165        self.end
166    }
167
168    pub(crate) fn tag_at(&self, slot: Slot) -> Tag {
169        self.message.fields[slot.index()].tag
170    }
171
172    pub(crate) fn value_at(&self, slot: Slot) -> &'a [u8] {
173        self.message.value(slot)
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::framing::SOH;
181
182    fn message_of<V: AsRef<[u8]>>(fields: &[(u32, V)]) -> RawMessage {
183        let mut bytes = Vec::new();
184        let mut index = Vec::new();
185        for (tag, value) in fields {
186            bytes.extend_from_slice(tag.to_string().as_bytes());
187            bytes.push(b'=');
188            let value_start = bytes.len() as u32;
189            bytes.extend_from_slice(value.as_ref());
190            let value_end = bytes.len() as u32;
191            bytes.push(SOH);
192            index.push(RawField {
193                tag: Tag(*tag),
194                value_start,
195                value_end,
196            });
197        }
198        RawMessage::new(Bytes::from(bytes), index)
199    }
200
201    #[test]
202    fn get_returns_first_occurrence() {
203        let message = message_of(&[(35, "0"), (58, "first"), (58, "second")]);
204        assert_eq!(message.get(Tag(58)), Some(b"first".as_slice()));
205    }
206
207    #[test]
208    fn get_absent_tag() {
209        let message = message_of(&[(35, "0")]);
210        assert_eq!(message.get(Tag(58)), None);
211    }
212
213    #[test]
214    fn get_str_returns_text() {
215        let message = message_of(&[(58, "hello")]);
216        assert_eq!(message.get_str(Tag(58)), Ok(Some("hello")));
217    }
218
219    #[test]
220    fn get_str_absent_tag() {
221        let message = message_of(&[(35, "0")]);
222        assert_eq!(message.get_str(Tag(58)), Ok(None));
223    }
224
225    #[test]
226    fn get_str_empty_value() {
227        let message = message_of(&[(58, "")]);
228        assert_eq!(message.get_str(Tag(58)), Ok(Some("")));
229    }
230
231    #[test]
232    fn get_str_rejects_invalid_utf8() {
233        let message = message_of(&[(58, b"caf\xE9".as_slice())]);
234        assert_eq!(message.get_str(Tag(58)), Err(InvalidValue { tag: Tag(58) }));
235    }
236
237    #[test]
238    fn get_int_parses_digits() {
239        let message = message_of(&[(38, "200")]);
240        assert_eq!(message.get_int(Tag(38)), Ok(Some(200)));
241    }
242
243    #[test]
244    fn get_int_parses_a_negative_value() {
245        let message = message_of(&[(38, "-5")]);
246        assert_eq!(message.get_int(Tag(38)), Ok(Some(-5)));
247    }
248
249    #[test]
250    fn get_int_absent_tag() {
251        let message = message_of(&[(35, "0")]);
252        assert_eq!(message.get_int(Tag(38)), Ok(None));
253    }
254
255    #[test]
256    fn get_int_rejects_garbage() {
257        let message = message_of(&[(38, "12x3")]);
258        assert_eq!(message.get_int(Tag(38)), Err(InvalidValue { tag: Tag(38) }));
259    }
260
261    #[test]
262    fn get_int_rejects_an_empty_value() {
263        let message = message_of(&[(38, "")]);
264        assert_eq!(message.get_int(Tag(38)), Err(InvalidValue { tag: Tag(38) }));
265    }
266
267    #[test]
268    fn get_int_rejects_invalid_utf8() {
269        let message = message_of(&[(38, b"\xE9".as_slice())]);
270        assert_eq!(message.get_int(Tag(38)), Err(InvalidValue { tag: Tag(38) }));
271    }
272
273    mod scope {
274        use super::*;
275
276        /// A scope over the fields in slots `start..end` of `message`.
277        fn scope_of(message: &RawMessage, start: u32, end: u32) -> Scope<'_> {
278            Scope {
279                message,
280                start: Slot(start),
281                end: Slot(end),
282            }
283        }
284
285        #[test]
286        fn a_scope_rebuilds_from_its_bounds() {
287            let message = message_of(&[(38, "100"), (58, "first"), (38, "x"), (58, "second")]);
288            let tail = scope_of(&message, 2, 4);
289
290            let rebuilt = message.scope_between(tail.start(), tail.end()).unwrap();
291
292            assert_eq!(rebuilt.get_str(Tag(58)), Ok(Some("second")));
293        }
294
295        #[test]
296        fn bounds_that_do_not_fit_the_message_are_rejected() {
297            let message = message_of(&[(38, "100"), (58, "first")]);
298
299            assert!(message.scope_between(Slot(0), Slot(3)).is_none());
300            assert!(message.scope_between(Slot(2), Slot(1)).is_none());
301            assert!(message.scope_between(Slot(2), Slot(2)).is_some());
302        }
303
304        #[test]
305        fn a_scope_does_not_read_past_its_end() {
306            // Two party instances; only the second has a PartyRole(452).
307            let message = message_of(&[(453, "2"), (448, "AL"), (448, "BOB"), (452, "3")]);
308            let first_instance = scope_of(&message, 1, 2);
309
310            assert_eq!(first_instance.get(Tag(448)), Some(b"AL".as_slice()));
311            assert_eq!(first_instance.get(Tag(452)), None);
312        }
313
314        #[test]
315        fn a_scope_does_not_read_before_its_start() {
316            let message = message_of(&[(453, "2"), (448, "AL"), (448, "BOB"), (452, "3")]);
317            let second_instance = scope_of(&message, 2, 4);
318
319            assert_eq!(second_instance.get(Tag(448)), Some(b"BOB".as_slice()));
320            assert_eq!(second_instance.get(Tag(453)), None);
321        }
322
323        #[test]
324        fn conversions_stay_within_the_scope() {
325            let message = message_of(&[(38, "100"), (58, "first"), (38, "x"), (58, "second")]);
326            let tail = scope_of(&message, 2, 4);
327
328            assert_eq!(tail.get_str(Tag(58)), Ok(Some("second")));
329            assert_eq!(tail.get_int(Tag(38)), Err(InvalidValue { tag: Tag(38) }));
330        }
331
332        #[test]
333        fn an_empty_scope_finds_nothing() {
334            let message = message_of(&[(35, "D")]);
335            assert_eq!(scope_of(&message, 1, 1).get(Tag(35)), None);
336        }
337
338        #[test]
339        fn the_whole_frame_scope_reads_like_the_message() {
340            let message = message_of(&[(35, "D"), (38, "200"), (58, "hello")]);
341            let scope = message.scope();
342
343            assert_eq!(scope.get(Tag(35)), message.get(Tag(35)));
344            assert_eq!(scope.get_int(Tag(38)), Ok(Some(200)));
345            assert_eq!(scope.get_str(Tag(58)), Ok(Some("hello")));
346            assert_eq!(scope.get(Tag(99)), None);
347        }
348
349        #[test]
350        fn values_outlive_the_scope_they_were_read_from() {
351            let message = message_of(&[(58, "kept")]);
352            let value = {
353                let scope = message.scope();
354                scope.get(Tag(58))
355            };
356
357            assert_eq!(value, Some(b"kept".as_slice()));
358        }
359    }
360}