Skip to main content

refix_message/
message.rs

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