1pub const SOH: u8 = 0x01;
45
46const MAX_BEGIN_STRING_LEN: usize = 16;
48
49const MAX_BODY_LENGTH_DIGITS: usize = 10;
51
52const CHECKSUM_FIELD_LEN: usize = 7;
54
55const 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
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub enum BeginString<'a> {
399 Fix40,
400 Fix41,
401 Fix42,
402 Fix43,
403 Fix44,
404 Fixt11,
405 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 #[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 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 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 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 assert_incomplete(scan(&to_wire("8=FIX.4.4|9=100|35=A")));
527 }
528 }
529
530 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 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 let mut buf = b"8=FIX".to_vec();
553 buf.extend([b'X'; 18]); 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 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 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 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 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 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 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]; *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'; 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 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 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); }
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 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 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 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}