Skip to main content

refix_message/
message.rs

1use bytes::Bytes;
2
3/// Tag recorded for a run of bytes that could not be tokenised into a field.
4pub const MALFORMED_TAG: u32 = 0;
5
6/// A field's position in a message's index.
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
8pub struct Slot(u32);
9
10impl Slot {
11    /// The first field of a message, always `BeginString`.
12    pub const START: Slot = Slot(0);
13
14    fn index(self) -> usize {
15        self.0 as usize
16    }
17}
18
19/// The tag and byte range of a field's value within the frame.
20#[derive(Clone, Copy, Debug)]
21pub(crate) struct RawField {
22    pub(crate) tag: u32,
23    pub(crate) value_start: u32,
24    pub(crate) value_end: u32,
25}
26
27/// Raw bytes of a FIX message and an index of every field in wire order.
28#[derive(Clone, Debug)]
29pub struct RawMessage {
30    bytes: Bytes,
31    fields: Vec<RawField>,
32}
33
34impl RawMessage {
35    pub(crate) fn new(bytes: Bytes, fields: Vec<RawField>) -> Self {
36        Self { bytes, fields }
37    }
38
39    /// The whole frame, from `8=` to the SOH after CheckSum.
40    pub fn bytes(&self) -> &Bytes {
41        &self.bytes
42    }
43
44    /// Value of the first occurrence of `tag`, scanning from the start.
45    pub fn get(&self, tag: u32) -> Option<&[u8]> {
46        self.find(tag, Slot::START).map(|(_, value)| value)
47    }
48
49    /// Every field as `(tag, value)`, in wire order, duplicates included.
50    ///
51    /// Includes an entry with [`MALFORMED_TAG`] for any byte run that could
52    /// not be tokenised, so the entries cover the whole frame.
53    pub fn entries(&self) -> impl Iterator<Item = (u32, &[u8])> {
54        self.fields
55            .iter()
56            .map(|&field| (field.tag, self.slice(field)))
57    }
58
59    /// First occurrence of `tag` at or after `from`, with its slot so the
60    /// caller can continue or bound a range.
61    fn find(&self, tag: u32, from: Slot) -> Option<(Slot, &[u8])> {
62        let rest = self.fields.get(from.index()..)?;
63        let offset = rest.iter().position(|field| field.tag == tag)?;
64        let slot = Slot((from.index() + offset) as u32);
65        Some((slot, self.value(slot)))
66    }
67
68    fn value(&self, slot: Slot) -> &[u8] {
69        self.slice(self.fields[slot.index()])
70    }
71
72    fn slice(&self, field: RawField) -> &[u8] {
73        &self.bytes[field.value_start as usize..field.value_end as usize]
74    }
75
76    /// The index itself, for tests asserting offset-level invariants.
77    #[cfg(test)]
78    pub(crate) fn raw_fields(&self) -> &[RawField] {
79        &self.fields
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::framing::SOH;
87
88    fn message_of(fields: &[(u32, &str)]) -> RawMessage {
89        let mut bytes = Vec::new();
90        let mut index = Vec::new();
91        for &(tag, value) in fields {
92            bytes.extend_from_slice(tag.to_string().as_bytes());
93            bytes.push(b'=');
94            let value_start = bytes.len() as u32;
95            bytes.extend_from_slice(value.as_bytes());
96            let value_end = bytes.len() as u32;
97            bytes.push(SOH);
98            index.push(RawField {
99                tag,
100                value_start,
101                value_end,
102            });
103        }
104        RawMessage::new(Bytes::from(bytes), index)
105    }
106
107    #[test]
108    fn get_returns_first_occurrence() {
109        let message = message_of(&[(35, "0"), (58, "first"), (58, "second")]);
110        assert_eq!(message.get(58), Some(b"first".as_slice()));
111    }
112
113    #[test]
114    fn get_absent_tag() {
115        let message = message_of(&[(35, "0")]);
116        assert_eq!(message.get(58), None);
117    }
118}