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
396/// The value of `BeginString(8)`, with recognised protocol versions decoded.
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub enum BeginString<'a> {
399    Fix40,
400    Fix41,
401    Fix42,
402    Fix43,
403    Fix44,
404    Fixt11,
405    /// An unrecognised BeginString, preserved as raw bytes.
406    Other(&'a [u8]),
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    use crate::test_utils::{construct_valid_frame, to_wire};
413
414    fn scan(buf: &[u8]) -> Outcome<'_> {
415        Scanner::default().scan(buf)
416    }
417
418    #[track_caller]
419    fn assert_garbled(out: Outcome, reason: GarbledReason, skipped: usize) {
420        match out {
421            Outcome::Garbled {
422                reason: r,
423                skipped: s,
424            } => {
425                assert_eq!(r, reason, "reason");
426                assert_eq!(s, skipped, "skipped");
427            }
428            _ => panic!("expected Garbled({reason:?}), got a different outcome"),
429        }
430    }
431
432    #[track_caller]
433    fn assert_incomplete(out: Outcome) {
434        assert!(matches!(out, Outcome::Incomplete), "expected Incomplete");
435    }
436
437    /// Scans a buffer expected to be a well-formed frame and returns it.
438    #[track_caller]
439    fn frame(buf: &[u8]) -> Frame<'_> {
440        match scan(buf) {
441            Outcome::Frame(frame) => frame,
442            _ => panic!("expected Frame"),
443        }
444    }
445
446    /// The resync primitive on its own: pure, fiddly, and stable enough to test directly.
447    mod resync {
448        use super::*;
449
450        #[test]
451        fn finds_needle_after_offset_zero() {
452            assert_eq!(find_next_begin_string(b"XX8=FIX"), 2);
453        }
454
455        #[test]
456        fn finds_needle_at_offset_one() {
457            assert_eq!(find_next_begin_string(b"X8=FIX"), 1);
458        }
459
460        #[test]
461        fn no_match_skips_whole_buffer() {
462            assert_eq!(find_next_begin_string(b"XYZW"), 4);
463        }
464
465        #[test]
466        fn preserves_longest_partial_tail() {
467            // Ends in `8=FI`, a 4-byte partial the next read may complete.
468            assert_eq!(find_next_begin_string(b"garbage8=FI"), 7);
469        }
470
471        #[test]
472        fn preserves_short_partial_tail() {
473            assert_eq!(find_next_begin_string(b"xx8="), 2);
474        }
475
476        #[test]
477        fn skip_is_always_in_range() {
478            // Every in-domain buffer (i.e. not itself a partial `8=FIX`, which is
479            // Incomplete) must yield a skip that both progresses and stays inside
480            // the buffer. Short ones matter most: that is where a tail match could
481            // otherwise cover the whole buffer and report 0.
482            for buf in [
483                &b"x"[..],
484                b"9",
485                b"=8",
486                b"junk",
487                b"8=FIXX",
488                b"xx8=",
489                b"x8=FI",
490                b"garbage8=FI",
491                b"XX8=FIX",
492                b"8=NOTFIX",
493            ] {
494                let skipped = find_next_begin_string(buf);
495                assert!(
496                    (1..=buf.len()).contains(&skipped),
497                    "skip of {skipped} out of range 1..={} for {:?}",
498                    buf.len(),
499                    String::from_utf8_lossy(buf),
500                );
501            }
502        }
503    }
504
505    mod incomplete {
506        use super::*;
507
508        #[test]
509        fn empty() {
510            assert_incomplete(scan(b""));
511        }
512
513        #[test]
514        fn lone_8() {
515            assert_incomplete(scan(b"8"));
516        }
517
518        #[test]
519        fn begin_string_without_soh() {
520            assert_incomplete(scan(&to_wire("8=FIX.4.4")));
521        }
522
523        #[test]
524        fn body_not_yet_arrived() {
525            // BodyLength claims 100 bytes; only a handful are here.
526            assert_incomplete(scan(&to_wire("8=FIX.4.4|9=100|35=A")));
527        }
528    }
529
530    /// Extent untrustworthy: the skip resyncs by searching for the next BeginString.
531    mod structural {
532        use super::*;
533
534        #[test]
535        fn missing_begin_string() {
536            assert_garbled(scan(&to_wire("junk")), GarbledReason::MissingBeginString, 4);
537        }
538
539        #[test]
540        fn non_fix_prefix_is_missing_begin_string() {
541            // `8=` but not `8=FIX`: not a frame start at all, so resync past it.
542            assert_garbled(
543                scan(&to_wire("8=NOTFIX|9=5|")),
544                GarbledReason::MissingBeginString,
545                13,
546            );
547        }
548
549        #[test]
550        fn malformed_begin_string_overruns_bound() {
551            // Starts with `8=FIX` but the BeginString runs past the bound with no SOH.
552            let mut buf = b"8=FIX".to_vec();
553            buf.extend([b'X'; 18]); // 23 bytes, no SOH within MAX_BEGIN_STRING_LEN
554            assert_garbled(scan(&buf), GarbledReason::MalformedBeginString, 23);
555        }
556
557        #[test]
558        fn missing_body_length() {
559            assert_garbled(
560                scan(&to_wire("8=FIX.4.4|35=A|")),
561                GarbledReason::MissingBodyLength,
562                15,
563            );
564        }
565
566        #[test]
567        fn malformed_body_length_non_digit() {
568            assert_garbled(
569                scan(&to_wire("8=FIX.4.4|9=XY|")),
570                GarbledReason::MalformedBodyLength,
571                15,
572            );
573        }
574
575        #[test]
576        fn malformed_body_length_overruns_cap() {
577            // 15 digits, no SOH: exceeds MAX_BODY_LENGTH_DIGITS.
578            assert_garbled(
579                scan(&to_wire("8=FIX.4.4|9=123456789012345")),
580                GarbledReason::MalformedBodyLength,
581                27,
582            );
583        }
584
585        #[test]
586        fn max_digit_body_length_does_not_panic() {
587            // The largest cap-legal BodyLength. It fits usize on a 64-bit target
588            // (rejected as FrameTooLarge) but overruns it on a 32-bit one (rejected
589            // as malformed); either way it must garble, never panic or wrap.
590            let buf = to_wire("8=FIX.4.4|9=9999999999|35=A|");
591            assert!(matches!(scan(&buf), Outcome::Garbled { .. }));
592        }
593
594        #[test]
595        fn frame_too_large_rejected_before_waiting() {
596            // frame_len of ~123 exceeds the cap of 50, so it rejects rather than waits.
597            let buf = to_wire("8=FIX.4.4|9=100|");
598            assert_garbled(
599                Scanner::new(50).scan(&buf),
600                GarbledReason::FrameTooLarge,
601                16,
602            );
603        }
604
605        #[test]
606        fn body_length_mismatch() {
607            // BodyLength says 3, real body is longer, so the jump lands mid-field.
608            assert_garbled(
609                scan(&to_wire("8=FIX.4.4|9=3|35=A|10=000|")),
610                GarbledReason::BodyLengthMismatch,
611                26,
612            );
613        }
614
615        #[test]
616        fn resync_lands_on_next_message() {
617            // Garbage, then a real message start 6 bytes in: the skip must land
618            // exactly on the next BeginString, not the end of the buffer.
619            let mut buf = to_wire("junk|X");
620            buf.extend_from_slice(&construct_valid_frame("FIX.4.4", "35=A|"));
621            assert_garbled(scan(&buf), GarbledReason::MissingBeginString, 6);
622        }
623    }
624
625    /// Extent trusted: the skip is the whole frame, never a resync.
626    mod post_structural {
627        use super::*;
628
629        #[test]
630        fn checksum_mismatch() {
631            let mut buf = construct_valid_frame("FIX.4.4", "35=A|34=1|");
632            let len = buf.len();
633            let last_digit = &mut buf[len - 2]; // 3 digits then trailing SOH
634            *last_digit = if *last_digit == b'0' { b'1' } else { b'0' };
635            assert_garbled(scan(&buf), GarbledReason::ChecksumMismatch, len);
636        }
637
638        #[test]
639        fn malformed_checksum_non_digit() {
640            let mut buf = construct_valid_frame("FIX.4.4", "35=A|34=1|");
641            let len = buf.len();
642            buf[len - 2] = b'x'; // non-digit in the checksum value
643            assert_garbled(scan(&buf), GarbledReason::MalformedChecksum, len);
644        }
645
646        #[test]
647        fn missing_msg_type() {
648            let buf = construct_valid_frame("FIX.4.4", "34=1|");
649            let len = buf.len();
650            assert_garbled(scan(&buf), GarbledReason::MissingMsgType, len);
651        }
652
653        #[test]
654        fn missing_msg_type_on_empty_body() {
655            let buf = construct_valid_frame("FIX.4.4", "");
656            let len = buf.len();
657            assert_garbled(scan(&buf), GarbledReason::MissingMsgType, len);
658        }
659
660        #[test]
661        fn empty_first_field() {
662            // An empty field where MsgType belongs, so `35=` is only the fourth
663            // field: `8=FIX.4.4|9=6||35=A|10=182|`. BodyLength and CheckSum are
664            // both correct, so framing reaches the MsgType check, and requiring
665            // `35=` to sit exactly at the start of the region is what rejects it.
666            let buf = construct_valid_frame("FIX.4.4", "|35=A|");
667            let len = buf.len();
668            assert_garbled(scan(&buf), GarbledReason::MissingMsgType, len);
669        }
670
671        #[test]
672        fn skip_does_not_resync_into_body() {
673            // The body contains `8=FIX` inside a Text field. A checksum failure
674            // trusts the frame extent, so it must skip the whole frame rather
675            // than resync onto the embedded bytes.
676            let mut buf = construct_valid_frame("FIX.4.4", "35=A|58=8=FIX.4.4|");
677            let len = buf.len();
678            buf[len - 2] = b'x';
679            assert_garbled(scan(&buf), GarbledReason::MalformedChecksum, len);
680        }
681    }
682
683    mod happy_path {
684        use super::*;
685
686        #[test]
687        fn valid_frame_scans() {
688            let buf = construct_valid_frame("FIX.4.4", "35=A|34=1|49=ME|56=YOU|");
689            assert!(matches!(scan(&buf), Outcome::Frame(_)));
690        }
691    }
692
693    mod preamble {
694        use super::*;
695
696        #[test]
697        fn msg_type() {
698            let buf = construct_valid_frame("FIX.4.4", "35=D|");
699            assert_eq!(frame(&buf).msg_type, b"D".as_slice());
700        }
701
702        #[test]
703        fn begin_string_and_body_length() {
704            let buf = construct_valid_frame("FIX.4.4", "35=A|");
705            let h = frame(&buf);
706            assert_eq!(h.begin_string, BeginString::Fix44);
707            assert_eq!(h.body_length, 5); // "35=A" + SOH
708        }
709
710        #[test]
711        fn unknown_begin_string_is_other() {
712            let buf = construct_valid_frame("FIX.5.0", "35=A|");
713            assert_eq!(frame(&buf).begin_string, BeginString::Other(b"FIX.5.0"));
714        }
715
716        #[test]
717        fn fixt_begin_string() {
718            let buf = construct_valid_frame("FIXT.1.1", "35=A|");
719            assert_eq!(frame(&buf).begin_string, BeginString::Fixt11);
720        }
721
722        #[test]
723        fn msg_type_read_regardless_of_trailing_fields() {
724            // Only MsgType is surfaced; the fields after it are the tokenizer's
725            // concern and must not affect framing or the preamble.
726            let buf = construct_valid_frame("FIX.4.4", "35=A|34=42|49=ME|56=YOU|");
727            assert_eq!(frame(&buf).msg_type, b"A".as_slice());
728        }
729    }
730
731    mod truncation {
732        use super::*;
733
734        #[test]
735        fn every_prefix_of_a_valid_frame_is_incomplete() {
736            let frames = [
737                construct_valid_frame("FIX.4.4", "35=A|"),
738                construct_valid_frame("FIX.4.4", "35=D|34=2|49=SENDER|56=TARGET|"),
739                construct_valid_frame("FIXT.1.1", "35=A|1128=9|"),
740                construct_valid_frame("FIX.4.2", "35=0|"),
741            ];
742            for full in &frames {
743                for len in 0..full.len() {
744                    assert!(
745                        matches!(scan(&full[..len]), Outcome::Incomplete),
746                        "prefix of length {len} (of a {}-byte frame) should be Incomplete",
747                        full.len(),
748                    );
749                }
750            }
751        }
752    }
753
754    mod chunking {
755        use super::*;
756
757        /// Drives the scanner over `stream` delivered in `chunk_size`-byte pieces,
758        /// returning the frame byte-slices produced, in order. Models a caller that
759        /// accumulates bytes, consumes complete frames/garbles, waits on Incomplete.
760        fn drive(stream: &[u8], chunk_size: usize) -> Vec<Vec<u8>> {
761            let scanner = Scanner::default();
762            let mut frames = Vec::new();
763            let mut buf: Vec<u8> = Vec::new();
764            for chunk in stream.chunks(chunk_size) {
765                buf.extend_from_slice(chunk);
766                loop {
767                    let advance = match scanner.scan(&buf) {
768                        Outcome::Frame(f) => {
769                            frames.push(f.bytes.to_vec());
770                            f.bytes.len()
771                        }
772                        Outcome::Garbled { skipped, .. } => skipped,
773                        Outcome::Incomplete => break,
774                    };
775                    buf.drain(..advance);
776                }
777            }
778            frames
779        }
780
781        #[test]
782        fn clean_stream_is_chunk_invariant() {
783            let f1 = construct_valid_frame("FIX.4.4", "35=A|34=1|");
784            let f2 = construct_valid_frame("FIXT.1.1", "35=D|1128=9|");
785            let mut stream = f1.clone();
786            stream.extend_from_slice(&f2);
787
788            let whole = drive(&stream, stream.len());
789            assert_eq!(whole, vec![f1, f2]);
790            for chunk_size in 1..=stream.len() {
791                assert_eq!(
792                    drive(&stream, chunk_size),
793                    whole,
794                    "chunk_size = {chunk_size}"
795                );
796            }
797        }
798
799        #[test]
800        fn garbage_before_frame_is_chunk_invariant() {
801            // Regression: leading non-`8=` garbage, then `8=<non-FIX>` with no SOH
802            // before the real frame's BeginString SOH, then a valid frame. Under a
803            // weak `8=` start anchor, byte-by-byte delivery latched onto the `8=Z`,
804            // absorbed the real frame into a bogus BeginString, and skipped it on
805            // the checksum failure - losing a frame the whole-buffer scan kept. The
806            // `8=FIX` anchor makes both paths skip the garbage identically.
807            let f = construct_valid_frame("FIX.4.4", "35=0|");
808            let mut stream = b"YY8=Z".to_vec();
809            stream.extend_from_slice(&f);
810
811            let whole = drive(&stream, stream.len());
812            assert_eq!(whole, vec![f]);
813            for chunk_size in 1..=stream.len() {
814                assert_eq!(
815                    drive(&stream, chunk_size),
816                    whole,
817                    "chunk_size = {chunk_size}"
818                );
819            }
820        }
821    }
822}