1pub const SOH: u8 = 0x01;
45
46pub(crate) const MAX_BEGIN_STRING_LEN: usize = 16;
48
49pub(crate) const MAX_BODY_LENGTH_DIGITS: usize = 10;
51
52const CHECKSUM_FIELD_LEN: usize = 7;
54
55pub(crate) const BEGIN_STRING_PREFIX: &[u8] = b"8=FIX";
58
59pub struct Scanner {
65 max_frame_size: usize,
66}
67
68impl Scanner {
69 pub fn new(max_frame_size: usize) -> Self {
72 Self { max_frame_size }
73 }
74
75 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 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
121fn 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
149fn structural_garble(reason: GarbledReason, buf: &[u8]) -> Halt {
153 Halt::Garbled {
154 reason,
155 skipped: find_next_begin_string(buf),
156 }
157}
158
159fn post_structural_garble(reason: GarbledReason, frame: &[u8]) -> Halt {
162 Halt::Garbled {
163 reason,
164 skipped: frame.len(),
165 }
166}
167
168fn 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)) }
190
191fn parse_body_length(buf: &[u8], body_length_start: usize) -> Result<(usize, usize), Halt> {
201 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 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 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; Ok((body_length, body_start))
234}
235
236fn 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
259fn 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
269fn 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
298fn 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 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 Frame(Frame<'a>),
324 Incomplete,
326 Garbled {
328 reason: GarbledReason,
330 skipped: usize,
335 },
336}
337
338#[derive(Debug, Clone, PartialEq, Eq)]
343pub struct Frame<'a> {
344 pub bytes: &'a [u8],
346 pub begin_string: BeginString<'a>,
348 pub body_length: usize,
350 pub msg_type: &'a [u8],
352}
353
354enum 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 MissingBeginString,
376 MalformedBeginString,
378 MissingBodyLength,
380 MalformedBodyLength,
383 BodyLengthMismatch,
386 MissingMsgType,
388 MalformedChecksum,
390 ChecksumMismatch,
392 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
414pub enum BeginString<'a> {
415 Fix40,
416 Fix41,
417 Fix42,
418 Fix43,
419 Fix44,
420 Fixt11,
421 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 #[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 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 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 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 assert_incomplete(scan(&to_wire("8=FIX.4.4|9=100|35=A")));
543 }
544 }
545
546 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 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 let mut buf = b"8=FIX".to_vec();
569 buf.extend([b'X'; 18]); 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 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 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 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 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 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 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]; *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'; 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 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 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); }
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 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 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 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}