Skip to main content

refix_message/
framing.rs

1//! Framing: delimiting one checksum-verified FIX message from a byte stream.
2//!
3//! A FIX connection is an unbroken stream with no external length prefix, so the
4//! only way to know where a message starts is to know where the previous one
5//! ended. [`Scanner::scan`] answers that one message at a time, borrowing
6//! from the caller's buffer and allocating nothing.
7//!
8//! Each call returns one of three outcomes, and each implies a different action:
9//! a [`Frame`] to consume, [`Outcome::Incomplete`] to wait on, or
10//! [`Outcome::Garbled`] to skip. Driving it is a loop:
11//!
12//! ```
13//! use refix_message::framing::{Scanner, Outcome};
14//!
15//! // Two heartbeats back to back, SOH-delimited.
16//! let stream = b"8=FIX.4.4\x019=10\x0135=0\x0134=2\x0110=166\x01\
17//!                8=FIX.4.4\x019=10\x0135=0\x0134=2\x0110=166\x01";
18//!
19//! let scanner = Scanner::default();
20//! let mut buf = &stream[..];
21//! let mut seen = Vec::new();
22//! loop {
23//!     let advance = match scanner.scan(buf) {
24//!         Outcome::Frame(frame) => {
25//!             seen.push(frame.msg_type.to_vec());
26//!             frame.bytes.len()
27//!         }
28//!         Outcome::Garbled { skipped, .. } => skipped,
29//!         Outcome::Incomplete => break, // read more from the socket
30//!     };
31//!     buf = &buf[advance..];
32//! }
33//! assert_eq!(seen, vec![b"0".to_vec(), b"0".to_vec()]);
34//! ```
35//!
36//! # Scope
37//!
38//! Framing reads only the fields whose position the frame structure fixes:
39//! `BeginString`, `BodyLength`, `MsgType` and `CheckSum`, each checked
40//! positionally at its known offset. Every other header field has no guaranteed
41//! wire position and may sit behind a length-prefixed data field, so reading it
42//! needs the order-independent, data-field-aware decoding of the layer above.
43
44pub const SOH: u8 = 0x01;
45
46/// Longest BeginString field we'll frame: `8=` through the byte before its SOH.
47pub(crate) const MAX_BEGIN_STRING_LEN: usize = 16;
48
49/// Longest BodyLength value we'll frame, in digits.
50pub(crate) const MAX_BODY_LENGTH_DIGITS: usize = 10;
51
52/// `10=` + three checksum digits + SOH.
53const CHECKSUM_FIELD_LEN: usize = 7;
54
55/// The shortest prefix common to every BeginString: the FIX spec fixes every
56/// one to the form `FIX.x.y` or `FIXT.x.y`, so `8=FIX` marks the start of any frame.
57pub(crate) const BEGIN_STRING_PREFIX: &[u8] = b"8=FIX";
58
59/// A stateless framing scanner: each [`scan`](Scanner::scan) call attempts
60/// to delimit one checksum-verified frame from the start of a buffer.
61///
62/// The [`Default`] scanner caps frames at 1 MiB; use [`Scanner::new`] to
63/// choose a different cap.
64pub struct Scanner {
65    max_frame_size: usize,
66}
67
68impl Scanner {
69    /// Creates a scanner that reports frames longer than `max_frame_size`
70    /// bytes as [`GarbledReason::FrameTooLarge`].
71    pub fn new(max_frame_size: usize) -> Self {
72        Self { max_frame_size }
73    }
74
75    /// Scans one frame from the start of `buf`.
76    ///
77    /// `buf` must begin at a presumed message boundary: the start of the
78    /// stream, or the position reached by advancing past a previous outcome.
79    /// After [`Outcome::Frame`], advance by `frame.bytes.len()`; after
80    /// [`Outcome::Garbled`], advance by `skipped`; on
81    /// [`Outcome::Incomplete`], read more bytes and scan again from the
82    /// same position.
83    pub fn scan<'a>(&self, buf: &'a [u8]) -> Outcome<'a> {
84        match self.try_scan(buf) {
85            Ok(frame) => Outcome::Frame(frame),
86            Err(halt) => halt.into(),
87        }
88    }
89
90    fn try_scan<'a>(&self, buf: &'a [u8]) -> Result<Frame<'a>, Halt> {
91        if !buf.starts_with(BEGIN_STRING_PREFIX) {
92            // If `buf` is still a prefix of `8=FIX`, more bytes
93            // could complete it; otherwise it's garbage to resync past.
94            return if BEGIN_STRING_PREFIX.starts_with(buf) {
95                Err(Halt::Incomplete)
96            } else {
97                Err(structural_garble(GarbledReason::MissingBeginString, buf))
98            };
99        }
100
101        let (begin_string, body_length_start) = parse_begin_string(buf)?;
102        let (body_length, body_start) = parse_body_length(buf, body_length_start)?;
103
104        let frame_len = validated_frame_len(buf, body_start, body_length, self.max_frame_size)?;
105        let frame = &buf[..frame_len];
106        let checksum_start = body_start + body_length;
107
108        verify_trailer_start(buf, checksum_start)?;
109        verify_checksum(frame, checksum_start)?;
110
111        let msg_type = parse_msg_type(frame, body_start, body_length)?;
112        Ok(Frame {
113            bytes: frame,
114            begin_string,
115            body_length,
116            msg_type,
117        })
118    }
119}
120
121/// Bytes to skip to resynchronise onto the next frame start.
122///
123/// Returns the offset of the next `8=FIX` after offset 0. If none is present,
124/// preserves the longest partial `8=FIX` prefix hanging off the tail.
125/// Failing that, skips the whole buffer.
126fn find_next_begin_string(buf: &[u8]) -> usize {
127    debug_assert!(
128        !BEGIN_STRING_PREFIX.starts_with(buf),
129        "a partial `8=FIX` has no resync distance; it is Incomplete",
130    );
131
132    if let Some(skip) = buf[1..]
133        .windows(BEGIN_STRING_PREFIX.len())
134        .position(|b| b == BEGIN_STRING_PREFIX)
135    {
136        return skip + 1;
137    }
138
139    let max_k = (BEGIN_STRING_PREFIX.len() - 1).min(buf.len());
140    for k in (1..=max_k).rev() {
141        if buf[buf.len() - k..] == BEGIN_STRING_PREFIX[..k] {
142            return buf.len() - k;
143        }
144    }
145
146    buf.len()
147}
148
149/// Builds a structural garble - one whose extent isn't trustworthy, so the skip
150/// resyncs by searching for the next BeginString. For garbles found once the
151/// frame is checksum-verified, use [`post_structural_garble`] instead.
152fn structural_garble(reason: GarbledReason, buf: &[u8]) -> Halt {
153    Halt::Garbled {
154        reason,
155        skipped: find_next_begin_string(buf),
156    }
157}
158
159/// Builds a post-structural garble - one found after the frame's extent is
160/// trusted (checksum-verified), so the skip is the whole frame, not a resync.
161fn post_structural_garble(reason: GarbledReason, frame: &[u8]) -> Halt {
162    Halt::Garbled {
163        reason,
164        skipped: frame.len(),
165    }
166}
167
168/// Parses `BeginString(8)`, the first field of a message.
169fn parse_begin_string(buf: &'_ [u8]) -> Result<(BeginString<'_>, usize), Halt> {
170    let search_end = buf.len().min(MAX_BEGIN_STRING_LEN + 1);
171    let soh = match buf[2..search_end].iter().position(|&b| b == SOH) {
172        Some(rel) => rel + 2,
173        None if buf.len() <= MAX_BEGIN_STRING_LEN => return Err(Halt::Incomplete),
174        None => return Err(structural_garble(GarbledReason::MalformedBeginString, buf)),
175    };
176
177    let value = &buf[2..soh];
178    let begin_string = match value {
179        b"FIX.4.0" => BeginString::Fix40,
180        b"FIX.4.1" => BeginString::Fix41,
181        b"FIX.4.2" => BeginString::Fix42,
182        b"FIX.4.3" => BeginString::Fix43,
183        b"FIX.4.4" => BeginString::Fix44,
184        b"FIXT.1.1" => BeginString::Fixt11,
185        other => BeginString::Other(other),
186    };
187
188    Ok((begin_string, soh + 1)) // soh + 1 = start of the 9= field
189}
190
191/// Parses `BodyLength(9)`, the second field of a message (starting at `body_length_start`).
192///
193/// On success returns `(body_length, body_start)`, where `body_start` is the
194/// offset just past the BodyLength SOH.
195///
196/// Throughout this module, `body_start` and `body_length` describe the region
197/// BodyLength measures: from its own terminating SOH up to and including the SOH
198/// before `10=`. That region holds most of the StandardHeader, so it is not the
199/// FIX "body" of application fields.
200fn parse_body_length(buf: &[u8], body_length_start: usize) -> Result<(usize, usize), Halt> {
201    // Expect the `9=` tag. With fewer than 2 bytes we can't even test it yet.
202    let tag = &buf[body_length_start..];
203    if tag.len() < 2 {
204        return Err(Halt::Incomplete);
205    }
206    if &tag[..2] != b"9=" {
207        return Err(structural_garble(GarbledReason::MissingBodyLength, buf));
208    }
209
210    // Digits run from just after `9=` to the terminating SOH, bounded by the cap.
211    let digits_start = body_length_start + 2;
212    let search_end = buf.len().min(digits_start + MAX_BODY_LENGTH_DIGITS + 1);
213    let soh_rel = match buf[digits_start..search_end].iter().position(|&b| b == SOH) {
214        Some(rel) => rel,
215        // Out-of-buffer first, cap-exceeded second - same ordering as BeginString.
216        None if buf.len() <= digits_start + MAX_BODY_LENGTH_DIGITS => return Err(Halt::Incomplete),
217        None => return Err(structural_garble(GarbledReason::MalformedBodyLength, buf)),
218    };
219
220    let digits = &buf[digits_start..digits_start + soh_rel];
221    if digits.is_empty() || !digits.iter().all(|b| b.is_ascii_digit()) {
222        return Err(structural_garble(GarbledReason::MalformedBodyLength, buf));
223    }
224
225    let body_length = digits
226        .iter()
227        .try_fold(0usize, |acc, &b| {
228            acc.checked_mul(10)?.checked_add(usize::from(b - b'0'))
229        })
230        .ok_or_else(|| structural_garble(GarbledReason::MalformedBodyLength, buf))?;
231
232    let body_start = digits_start + soh_rel + 1; // just past the BodyLength SOH
233    Ok((body_length, body_start))
234}
235
236/// The total frame length implied by BodyLength, bounded and fully buffered.
237///
238/// `FrameTooLarge` if it exceeds `max_frame_size`; `Incomplete` if the frame
239/// hasn't fully arrived. The frame's *content* - the `10=` trailer and
240/// checksum - is not inspected here.
241fn validated_frame_len(
242    buf: &[u8],
243    body_start: usize,
244    body_length: usize,
245    max_frame_size: usize,
246) -> Result<usize, Halt> {
247    let frame_len = body_start
248        .saturating_add(body_length)
249        .saturating_add(CHECKSUM_FIELD_LEN);
250    if frame_len > max_frame_size {
251        return Err(structural_garble(GarbledReason::FrameTooLarge, buf));
252    }
253    if buf.len() < frame_len {
254        return Err(Halt::Incomplete);
255    }
256    Ok(frame_len)
257}
258
259/// Confirms BodyLength's jump landed on the CheckSum field: `10=` at a field
260/// boundary (SOH just before). A miss means BodyLength was wrong, so resync over
261/// the whole buffer.
262fn verify_trailer_start(buf: &[u8], checksum_start: usize) -> Result<(), Halt> {
263    if buf[checksum_start - 1] != SOH || &buf[checksum_start..checksum_start + 3] != b"10=" {
264        return Err(structural_garble(GarbledReason::BodyLengthMismatch, buf));
265    }
266    Ok(())
267}
268
269/// Verifies the `<CheckSum><SOH>` at `checksum_start`, the `10=` landing
270/// having already been confirmed.
271fn verify_checksum(frame: &[u8], checksum_start: usize) -> Result<(), Halt> {
272    let digits = &frame[checksum_start + 3..checksum_start + 6];
273    let trailing_soh = frame[checksum_start + 6];
274    if trailing_soh != SOH || !digits.iter().all(|b| b.is_ascii_digit()) {
275        return Err(post_structural_garble(
276            GarbledReason::MalformedChecksum,
277            frame,
278        ));
279    }
280
281    let stated = u16::from(digits[0] - b'0') * 100
282        + u16::from(digits[1] - b'0') * 10
283        + u16::from(digits[2] - b'0');
284    let computed = frame[..checksum_start]
285        .iter()
286        .fold(0u8, |acc, &b| acc.wrapping_add(b));
287
288    if u16::from(computed) != stated {
289        return Err(post_structural_garble(
290            GarbledReason::ChecksumMismatch,
291            frame,
292        ));
293    }
294
295    Ok(())
296}
297
298/// Parses `MsgType(35)`, the third field of a message.
299fn parse_msg_type(frame: &[u8], body_start: usize, body_length: usize) -> Result<&[u8], Halt> {
300    let region = &frame[body_start..body_start + body_length];
301    let Some(after_tag) = region.strip_prefix(b"35=") else {
302        return Err(post_structural_garble(GarbledReason::MissingMsgType, frame));
303    };
304    // The region's final byte is the SOH before `10=`,
305    // so a terminator is always present once the tag matched.
306    let Some(soh) = after_tag.iter().position(|&b| b == SOH) else {
307        return Err(post_structural_garble(GarbledReason::MissingMsgType, frame));
308    };
309    Ok(&after_tag[..soh])
310}
311
312impl Default for Scanner {
313    fn default() -> Self {
314        Self {
315            max_frame_size: 1 << 20,
316        }
317    }
318}
319
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum Outcome<'a> {
322    /// A well-framed message, checksum verified.
323    Frame(Frame<'a>),
324    /// The bytes don't represent a complete message.
325    Incomplete,
326    /// The message is garbled.
327    Garbled {
328        /// The reason for the supplied bytes being garbled.
329        reason: GarbledReason,
330        /// Number of bytes to skip.
331        ///
332        /// Always at least 1: the caller advances by this many bytes, so a
333        /// garbled frame never stalls the stream.
334        skipped: usize,
335    },
336}
337
338/// One well-framed, checksum-verified message.
339///
340/// Carries the raw frame bytes plus the three preamble fields whose position is
341/// guaranteed by the frame structure itself (`8`/`9`/`35`).
342#[derive(Debug, Clone, PartialEq, Eq)]
343pub struct Frame<'a> {
344    /// The full frame: 8= through the SOH after CheckSum.
345    pub bytes: &'a [u8],
346    /// `BeginString(8)`
347    pub begin_string: BeginString<'a>,
348    /// `BodyLength(9)`
349    pub body_length: usize,
350    /// `MsgType(35)`
351    pub msg_type: &'a [u8],
352}
353
354/// A scan that ended without a frame.
355enum Halt {
356    Incomplete,
357    Garbled {
358        reason: GarbledReason,
359        skipped: usize,
360    },
361}
362
363impl<'a> From<Halt> for Outcome<'a> {
364    fn from(halt: Halt) -> Self {
365        match halt {
366            Halt::Incomplete => Outcome::Incomplete,
367            Halt::Garbled { reason, skipped } => Outcome::Garbled { reason, skipped },
368        }
369    }
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub enum GarbledReason {
374    /// It does not start with `8=FIX` (so it is not a frame start).
375    MissingBeginString,
376    /// `8=FIX` present, but no SOH within MAX_BEGIN_STRING_LEN.
377    MalformedBeginString,
378    /// The second tag is not `9=`.
379    MissingBodyLength,
380    /// BodyLength is empty, contains a non-digit, exceeds the digit cap, or is
381    /// too large to represent.
382    MalformedBodyLength,
383    /// The BodyLength-implied offset is not a `10=` trailer at a field boundary
384    /// (i.e. not preceded by SOH, or not `10=`).
385    BodyLengthMismatch,
386    /// The third field is not `35=` (it must directly follow BodyLength).
387    MissingMsgType,
388    /// The CheckSum field is not three digits followed by SOH.
389    MalformedChecksum,
390    /// The calculated checksum does not match the value of CheckSum.
391    ChecksumMismatch,
392    /// The BodyLength-implied frame length exceeds max_frame_size.
393    FrameTooLarge,
394}
395
396impl std::fmt::Display for GarbledReason {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        f.write_str(match self {
399            GarbledReason::MissingBeginString => "missing BeginString",
400            GarbledReason::MalformedBeginString => "malformed BeginString",
401            GarbledReason::MissingBodyLength => "missing BodyLength",
402            GarbledReason::MalformedBodyLength => "malformed BodyLength",
403            GarbledReason::BodyLengthMismatch => "BodyLength mismatch",
404            GarbledReason::MissingMsgType => "missing MsgType",
405            GarbledReason::MalformedChecksum => "malformed CheckSum",
406            GarbledReason::ChecksumMismatch => "CheckSum mismatch",
407            GarbledReason::FrameTooLarge => "frame too large",
408        })
409    }
410}
411
412/// The value of `BeginString(8)`, with recognised protocol versions decoded.
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
414pub enum BeginString<'a> {
415    Fix40,
416    Fix41,
417    Fix42,
418    Fix43,
419    Fix44,
420    Fixt11,
421    /// An unrecognised BeginString, preserved as raw bytes.
422    Other(&'a [u8]),
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use crate::test_utils::{construct_valid_frame, to_wire};
429
430    fn scan(buf: &[u8]) -> Outcome<'_> {
431        Scanner::default().scan(buf)
432    }
433
434    #[track_caller]
435    fn assert_garbled(out: Outcome, reason: GarbledReason, skipped: usize) {
436        match out {
437            Outcome::Garbled {
438                reason: r,
439                skipped: s,
440            } => {
441                assert_eq!(r, reason, "reason");
442                assert_eq!(s, skipped, "skipped");
443            }
444            _ => panic!("expected Garbled({reason:?}), got a different outcome"),
445        }
446    }
447
448    #[track_caller]
449    fn assert_incomplete(out: Outcome) {
450        assert!(matches!(out, Outcome::Incomplete), "expected Incomplete");
451    }
452
453    /// Scans a buffer expected to be a well-formed frame and returns it.
454    #[track_caller]
455    fn frame(buf: &[u8]) -> Frame<'_> {
456        match scan(buf) {
457            Outcome::Frame(frame) => frame,
458            _ => panic!("expected Frame"),
459        }
460    }
461
462    /// The resync primitive on its own: pure, fiddly, and stable enough to test directly.
463    mod resync {
464        use super::*;
465
466        #[test]
467        fn finds_needle_after_offset_zero() {
468            assert_eq!(find_next_begin_string(b"XX8=FIX"), 2);
469        }
470
471        #[test]
472        fn finds_needle_at_offset_one() {
473            assert_eq!(find_next_begin_string(b"X8=FIX"), 1);
474        }
475
476        #[test]
477        fn no_match_skips_whole_buffer() {
478            assert_eq!(find_next_begin_string(b"XYZW"), 4);
479        }
480
481        #[test]
482        fn preserves_longest_partial_tail() {
483            // Ends in `8=FI`, a 4-byte partial the next read may complete.
484            assert_eq!(find_next_begin_string(b"garbage8=FI"), 7);
485        }
486
487        #[test]
488        fn preserves_short_partial_tail() {
489            assert_eq!(find_next_begin_string(b"xx8="), 2);
490        }
491
492        #[test]
493        fn skip_is_always_in_range() {
494            // Every in-domain buffer (i.e. not itself a partial `8=FIX`, which is
495            // Incomplete) must yield a skip that both progresses and stays inside
496            // the buffer. Short ones matter most: that is where a tail match could
497            // otherwise cover the whole buffer and report 0.
498            for buf in [
499                &b"x"[..],
500                b"9",
501                b"=8",
502                b"junk",
503                b"8=FIXX",
504                b"xx8=",
505                b"x8=FI",
506                b"garbage8=FI",
507                b"XX8=FIX",
508                b"8=NOTFIX",
509            ] {
510                let skipped = find_next_begin_string(buf);
511                assert!(
512                    (1..=buf.len()).contains(&skipped),
513                    "skip of {skipped} out of range 1..={} for {:?}",
514                    buf.len(),
515                    String::from_utf8_lossy(buf),
516                );
517            }
518        }
519    }
520
521    mod incomplete {
522        use super::*;
523
524        #[test]
525        fn empty() {
526            assert_incomplete(scan(b""));
527        }
528
529        #[test]
530        fn lone_8() {
531            assert_incomplete(scan(b"8"));
532        }
533
534        #[test]
535        fn begin_string_without_soh() {
536            assert_incomplete(scan(&to_wire("8=FIX.4.4")));
537        }
538
539        #[test]
540        fn body_not_yet_arrived() {
541            // BodyLength claims 100 bytes; only a handful are here.
542            assert_incomplete(scan(&to_wire("8=FIX.4.4|9=100|35=A")));
543        }
544    }
545
546    /// Extent untrustworthy: the skip resyncs by searching for the next BeginString.
547    mod structural {
548        use super::*;
549
550        #[test]
551        fn missing_begin_string() {
552            assert_garbled(scan(&to_wire("junk")), GarbledReason::MissingBeginString, 4);
553        }
554
555        #[test]
556        fn non_fix_prefix_is_missing_begin_string() {
557            // `8=` but not `8=FIX`: not a frame start at all, so resync past it.
558            assert_garbled(
559                scan(&to_wire("8=NOTFIX|9=5|")),
560                GarbledReason::MissingBeginString,
561                13,
562            );
563        }
564
565        #[test]
566        fn malformed_begin_string_overruns_bound() {
567            // Starts with `8=FIX` but the BeginString runs past the bound with no SOH.
568            let mut buf = b"8=FIX".to_vec();
569            buf.extend([b'X'; 18]); // 23 bytes, no SOH within MAX_BEGIN_STRING_LEN
570            assert_garbled(scan(&buf), GarbledReason::MalformedBeginString, 23);
571        }
572
573        #[test]
574        fn missing_body_length() {
575            assert_garbled(
576                scan(&to_wire("8=FIX.4.4|35=A|")),
577                GarbledReason::MissingBodyLength,
578                15,
579            );
580        }
581
582        #[test]
583        fn malformed_body_length_non_digit() {
584            assert_garbled(
585                scan(&to_wire("8=FIX.4.4|9=XY|")),
586                GarbledReason::MalformedBodyLength,
587                15,
588            );
589        }
590
591        #[test]
592        fn malformed_body_length_overruns_cap() {
593            // 15 digits, no SOH: exceeds MAX_BODY_LENGTH_DIGITS.
594            assert_garbled(
595                scan(&to_wire("8=FIX.4.4|9=123456789012345")),
596                GarbledReason::MalformedBodyLength,
597                27,
598            );
599        }
600
601        #[test]
602        fn max_digit_body_length_does_not_panic() {
603            // The largest cap-legal BodyLength. It fits usize on a 64-bit target
604            // (rejected as FrameTooLarge) but overruns it on a 32-bit one (rejected
605            // as malformed); either way it must garble, never panic or wrap.
606            let buf = to_wire("8=FIX.4.4|9=9999999999|35=A|");
607            assert!(matches!(scan(&buf), Outcome::Garbled { .. }));
608        }
609
610        #[test]
611        fn frame_too_large_rejected_before_waiting() {
612            // frame_len of ~123 exceeds the cap of 50, so it rejects rather than waits.
613            let buf = to_wire("8=FIX.4.4|9=100|");
614            assert_garbled(
615                Scanner::new(50).scan(&buf),
616                GarbledReason::FrameTooLarge,
617                16,
618            );
619        }
620
621        #[test]
622        fn body_length_mismatch() {
623            // BodyLength says 3, real body is longer, so the jump lands mid-field.
624            assert_garbled(
625                scan(&to_wire("8=FIX.4.4|9=3|35=A|10=000|")),
626                GarbledReason::BodyLengthMismatch,
627                26,
628            );
629        }
630
631        #[test]
632        fn resync_lands_on_next_message() {
633            // Garbage, then a real message start 6 bytes in: the skip must land
634            // exactly on the next BeginString, not the end of the buffer.
635            let mut buf = to_wire("junk|X");
636            buf.extend_from_slice(&construct_valid_frame("FIX.4.4", "35=A|"));
637            assert_garbled(scan(&buf), GarbledReason::MissingBeginString, 6);
638        }
639    }
640
641    /// Extent trusted: the skip is the whole frame, never a resync.
642    mod post_structural {
643        use super::*;
644
645        #[test]
646        fn checksum_mismatch() {
647            let mut buf = construct_valid_frame("FIX.4.4", "35=A|34=1|");
648            let len = buf.len();
649            let last_digit = &mut buf[len - 2]; // 3 digits then trailing SOH
650            *last_digit = if *last_digit == b'0' { b'1' } else { b'0' };
651            assert_garbled(scan(&buf), GarbledReason::ChecksumMismatch, len);
652        }
653
654        #[test]
655        fn malformed_checksum_non_digit() {
656            let mut buf = construct_valid_frame("FIX.4.4", "35=A|34=1|");
657            let len = buf.len();
658            buf[len - 2] = b'x'; // non-digit in the checksum value
659            assert_garbled(scan(&buf), GarbledReason::MalformedChecksum, len);
660        }
661
662        #[test]
663        fn missing_msg_type() {
664            let buf = construct_valid_frame("FIX.4.4", "34=1|");
665            let len = buf.len();
666            assert_garbled(scan(&buf), GarbledReason::MissingMsgType, len);
667        }
668
669        #[test]
670        fn missing_msg_type_on_empty_body() {
671            let buf = construct_valid_frame("FIX.4.4", "");
672            let len = buf.len();
673            assert_garbled(scan(&buf), GarbledReason::MissingMsgType, len);
674        }
675
676        #[test]
677        fn empty_first_field() {
678            // An empty field where MsgType belongs, so `35=` is only the fourth
679            // field: `8=FIX.4.4|9=6||35=A|10=182|`. BodyLength and CheckSum are
680            // both correct, so framing reaches the MsgType check, and requiring
681            // `35=` to sit exactly at the start of the region is what rejects it.
682            let buf = construct_valid_frame("FIX.4.4", "|35=A|");
683            let len = buf.len();
684            assert_garbled(scan(&buf), GarbledReason::MissingMsgType, len);
685        }
686
687        #[test]
688        fn skip_does_not_resync_into_body() {
689            // The body contains `8=FIX` inside a Text field. A checksum failure
690            // trusts the frame extent, so it must skip the whole frame rather
691            // than resync onto the embedded bytes.
692            let mut buf = construct_valid_frame("FIX.4.4", "35=A|58=8=FIX.4.4|");
693            let len = buf.len();
694            buf[len - 2] = b'x';
695            assert_garbled(scan(&buf), GarbledReason::MalformedChecksum, len);
696        }
697    }
698
699    mod happy_path {
700        use super::*;
701
702        #[test]
703        fn valid_frame_scans() {
704            let buf = construct_valid_frame("FIX.4.4", "35=A|34=1|49=ME|56=YOU|");
705            assert!(matches!(scan(&buf), Outcome::Frame(_)));
706        }
707    }
708
709    mod preamble {
710        use super::*;
711
712        #[test]
713        fn msg_type() {
714            let buf = construct_valid_frame("FIX.4.4", "35=D|");
715            assert_eq!(frame(&buf).msg_type, b"D".as_slice());
716        }
717
718        #[test]
719        fn begin_string_and_body_length() {
720            let buf = construct_valid_frame("FIX.4.4", "35=A|");
721            let h = frame(&buf);
722            assert_eq!(h.begin_string, BeginString::Fix44);
723            assert_eq!(h.body_length, 5); // "35=A" + SOH
724        }
725
726        #[test]
727        fn unknown_begin_string_is_other() {
728            let buf = construct_valid_frame("FIX.5.0", "35=A|");
729            assert_eq!(frame(&buf).begin_string, BeginString::Other(b"FIX.5.0"));
730        }
731
732        #[test]
733        fn fixt_begin_string() {
734            let buf = construct_valid_frame("FIXT.1.1", "35=A|");
735            assert_eq!(frame(&buf).begin_string, BeginString::Fixt11);
736        }
737
738        #[test]
739        fn msg_type_read_regardless_of_trailing_fields() {
740            // Only MsgType is surfaced; the fields after it are the tokenizer's
741            // concern and must not affect framing or the preamble.
742            let buf = construct_valid_frame("FIX.4.4", "35=A|34=42|49=ME|56=YOU|");
743            assert_eq!(frame(&buf).msg_type, b"A".as_slice());
744        }
745    }
746
747    mod truncation {
748        use super::*;
749
750        #[test]
751        fn every_prefix_of_a_valid_frame_is_incomplete() {
752            let frames = [
753                construct_valid_frame("FIX.4.4", "35=A|"),
754                construct_valid_frame("FIX.4.4", "35=D|34=2|49=SENDER|56=TARGET|"),
755                construct_valid_frame("FIXT.1.1", "35=A|1128=9|"),
756                construct_valid_frame("FIX.4.2", "35=0|"),
757            ];
758            for full in &frames {
759                for len in 0..full.len() {
760                    assert!(
761                        matches!(scan(&full[..len]), Outcome::Incomplete),
762                        "prefix of length {len} (of a {}-byte frame) should be Incomplete",
763                        full.len(),
764                    );
765                }
766            }
767        }
768    }
769
770    mod chunking {
771        use super::*;
772
773        /// Drives the scanner over `stream` delivered in `chunk_size`-byte pieces,
774        /// returning the frame byte-slices produced, in order. Models a caller that
775        /// accumulates bytes, consumes complete frames/garbles, waits on Incomplete.
776        fn drive(stream: &[u8], chunk_size: usize) -> Vec<Vec<u8>> {
777            let scanner = Scanner::default();
778            let mut frames = Vec::new();
779            let mut buf: Vec<u8> = Vec::new();
780            for chunk in stream.chunks(chunk_size) {
781                buf.extend_from_slice(chunk);
782                loop {
783                    let advance = match scanner.scan(&buf) {
784                        Outcome::Frame(f) => {
785                            frames.push(f.bytes.to_vec());
786                            f.bytes.len()
787                        }
788                        Outcome::Garbled { skipped, .. } => skipped,
789                        Outcome::Incomplete => break,
790                    };
791                    buf.drain(..advance);
792                }
793            }
794            frames
795        }
796
797        #[test]
798        fn clean_stream_is_chunk_invariant() {
799            let f1 = construct_valid_frame("FIX.4.4", "35=A|34=1|");
800            let f2 = construct_valid_frame("FIXT.1.1", "35=D|1128=9|");
801            let mut stream = f1.clone();
802            stream.extend_from_slice(&f2);
803
804            let whole = drive(&stream, stream.len());
805            assert_eq!(whole, vec![f1, f2]);
806            for chunk_size in 1..=stream.len() {
807                assert_eq!(
808                    drive(&stream, chunk_size),
809                    whole,
810                    "chunk_size = {chunk_size}"
811                );
812            }
813        }
814
815        #[test]
816        fn garbage_before_frame_is_chunk_invariant() {
817            // Regression: leading non-`8=` garbage, then `8=<non-FIX>` with no SOH
818            // before the real frame's BeginString SOH, then a valid frame. Under a
819            // weak `8=` start anchor, byte-by-byte delivery latched onto the `8=Z`,
820            // absorbed the real frame into a bogus BeginString, and skipped it on
821            // the checksum failure - losing a frame the whole-buffer scan kept. The
822            // `8=FIX` anchor makes both paths skip the garbage identically.
823            let f = construct_valid_frame("FIX.4.4", "35=0|");
824            let mut stream = b"YY8=Z".to_vec();
825            stream.extend_from_slice(&f);
826
827            let whole = drive(&stream, stream.len());
828            assert_eq!(whole, vec![f]);
829            for chunk_size in 1..=stream.len() {
830                assert_eq!(
831                    drive(&stream, chunk_size),
832                    whole,
833                    "chunk_size = {chunk_size}"
834                );
835            }
836        }
837    }
838}