easyfix_core/deserializer.rs
1//! Reading FIX tag-value messages.
2//!
3//! Two stages: [`raw_message`] frames one message out of a byte stream,
4//! checking BeginString, BodyLength and CheckSum without looking inside;
5//! [`Deserializer`] then walks that frame's body, handing typed values to the
6//! generated message types. Both borrow from the input rather than copying it.
7//!
8//! Failures are classified by what the session must do about them - see
9//! [`DeserializeErrorKind`].
10
11use std::{error::Error as StdError, fmt, ops, sync::LazyLock};
12
13use memchr::{memchr, memmem};
14
15use crate::{
16 base_messages::SessionRejectReasonBase,
17 basic_types::{
18 Amt, Boolean, Char, Country, Currency, Data, DayOfMonth, Decimal, Exchange, FixStr,
19 FixString, FixedOffset, Float, Int, Language, Length, LocalMktDate, LocalMktTime,
20 MonthYear, MultipleCharValue, MultipleStringValue, NaiveDate, NaiveTime, NumInGroup,
21 Percentage, Price, PriceOffset, Qty, SeqNum, SessionRejectReasonField, TagNum, Tenor,
22 TenorUnit, TenorValue, TimePrecision, TimeZone, TzTimeOnly, TzTimestamp, Utc, UtcDateOnly,
23 UtcTimeOnly, UtcTimestamp, XmlData,
24 },
25 version::Version,
26};
27
28#[cfg(test)]
29mod tests;
30
31/// Why a message could not be framed or parsed as FIX at all.
32///
33/// A garbled message is logged and dropped without a reply - the session
34/// neither rejects it nor advances a sequence number (FIX Session Layer
35/// ยง4.5.2). The gap it leaves is recovered by the next well-formed message
36/// triggering a `ResendRequest`.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum GarbledReason {
39 /// The byte stream ended before a complete message could be parsed - either
40 /// at the framing level (`RawMessageError::Incomplete`) or inside a field
41 /// value whose terminating SOH never appeared.
42 IncompleteMessageData,
43 /// The bytes are present but don't match the expected framing or field
44 /// format (e.g. the byte where an SOH separator was expected is something
45 /// else).
46 MessageNotWellFormed,
47 /// Computed checksum does not match the Checksum(10) value.
48 InvalidChecksum,
49 /// BeginString(8) is not a recognized FIX version identifier (bad format
50 /// or an unknown version). A *recognized but wrong* version is not
51 /// garbled; it is a [`LogoutReason::BeginStringMismatch`].
52 InvalidBeginString,
53 /// The third tag of the message is not MsgType(35), as required by the
54 /// FIX framing rules.
55 MsgTypeNotThirdTag,
56}
57
58impl fmt::Display for GarbledReason {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 match self {
61 GarbledReason::IncompleteMessageData => f.write_str("incomplete message data"),
62 GarbledReason::MessageNotWellFormed => f.write_str("message not well formed"),
63 GarbledReason::InvalidChecksum => f.write_str("invalid checksum"),
64 GarbledReason::InvalidBeginString => f.write_str("invalid BeginString<8>"),
65 GarbledReason::MsgTypeNotThirdTag => f.write_str("MsgType<35> not third tag"),
66 }
67 }
68}
69
70/// Cause of a [`DeserializeErrorKind::Logout`] - a well-formed message that the
71/// session must answer with a Logout(35=5) and disconnect.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum LogoutReason {
74 /// MsgSeqNum(34) is missing.
75 MsgSeqNumMissing,
76 /// BeginString(8) is a recognized FIX version but not the one expected for
77 /// this session.
78 BeginStringMismatch,
79}
80
81impl fmt::Display for LogoutReason {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 LogoutReason::MsgSeqNumMissing => f.write_str("MsgSeqNum<34> missing"),
85 LogoutReason::BeginStringMismatch => f.write_str("invalid BeginString<8>"),
86 }
87 }
88}
89
90/// A failed deserialization, classified by what the session must do about it.
91///
92/// The three variants are three different reactions, not three severities.
93#[derive(Debug)]
94pub enum DeserializeErrorKind {
95 /// Not a FIX message. Log it and drop it silently; do not reply and do not
96 /// touch sequence numbers.
97 Garbled(GarbledReason),
98 /// Well-formed, but the session cannot continue. Send `Logout<5>` and
99 /// disconnect.
100 Logout(LogoutReason),
101 /// A field-level violation in an otherwise well-formed message. Send
102 /// `Reject<3>` and carry on.
103 Reject {
104 /// MsgType(35) of the failed message, when it was parsed.
105 msg_type: Option<FixString>,
106 /// MsgSeqNum(34) to quote as `RefSeqNum(45)` on the Reject.
107 seq_num: SeqNum,
108 /// Tag that failed, quoted as `RefTagID(371)`. `None` when no single
109 /// tag is to blame.
110 tag: Option<TagNum>,
111 /// Value for `SessionRejectReason(373)`.
112 reason: SessionRejectReasonField,
113 },
114}
115
116impl fmt::Display for DeserializeErrorKind {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 match self {
119 DeserializeErrorKind::Garbled(reason) => write!(f, "garbled message: {reason}"),
120 DeserializeErrorKind::Logout(reason) => write!(f, "logout: {reason}"),
121 DeserializeErrorKind::Reject {
122 tag: Some(tag),
123 reason,
124 ..
125 } => write!(f, "{reason} (tag={tag})"),
126 DeserializeErrorKind::Reject {
127 tag: None, reason, ..
128 } => write!(f, "{reason}"),
129 }
130 }
131}
132
133impl StdError for DeserializeErrorKind {}
134
135impl From<RawMessageError> for DeserializeErrorKind {
136 fn from(error: RawMessageError) -> Self {
137 match error {
138 RawMessageError::Incomplete => {
139 DeserializeErrorKind::Garbled(GarbledReason::IncompleteMessageData)
140 }
141 RawMessageError::Garbled => {
142 DeserializeErrorKind::Garbled(GarbledReason::MessageNotWellFormed)
143 }
144 RawMessageError::InvalidChecksum { .. } => {
145 DeserializeErrorKind::Garbled(GarbledReason::InvalidChecksum)
146 }
147 }
148 }
149}
150
151#[derive(Debug, thiserror::Error)]
152pub(crate) enum DeserializeErrorKindInternal {
153 /// The input ended at a point where a longer input could still have
154 /// parsed; only more bytes can tell truncation from malformation.
155 #[error("Incomplete")]
156 Incomplete,
157 /// The input is malformed regardless of any further bytes.
158 #[error("{0:?}")]
159 Error(SessionRejectReasonBase),
160}
161
162fn deserialize_tag<'a>(bytes: &'a [u8], tag: &'a [u8]) -> Result<&'a [u8], RawMessageError> {
163 if bytes.len() < tag.len() {
164 Err(RawMessageError::Incomplete)
165 } else if bytes.starts_with(tag) {
166 Ok(&bytes[tag.len()..])
167 } else {
168 Err(RawMessageError::Garbled)
169 }
170}
171
172/// Parse the `CheckSum(10)` value: exactly three digits and SOH. The value
173/// is returned as declared - `u16` because three digits reach 999, and
174/// whether it matches is for the caller to decide.
175//
176// Only the field's shape is judged here. A malformed field (`A23`, a
177// missing SOH) is `Garbled`: without the fixed three-digit-plus-SOH shape
178// the frame has no known end, so the caller must resynchronize rather than
179// skip it. `InvalidChecksum` is reserved for a well-shaped field whose value
180// disagrees, where the frame extent is certain - `raw_message` decides that,
181// as it alone knows the frame length to report.
182fn deserialize_checksum(bytes: &[u8]) -> Result<(&[u8], u16), RawMessageError> {
183 if bytes.len() < 4 {
184 return Err(RawMessageError::Incomplete);
185 }
186
187 let mut value: u16 = 0;
188 for b in &bytes[0..3] {
189 match b {
190 n @ b'0'..=b'9' => value = value * 10 + u16::from(n - b'0'),
191 _ => return Err(RawMessageError::Garbled),
192 }
193 }
194
195 if bytes[3] != b'\x01' {
196 return Err(RawMessageError::Garbled);
197 }
198
199 Ok((&bytes[4..], value))
200}
201
202/// Longest valid fractional-second width: 12 digits (picoseconds).
203const MAX_FRACTION_DIGITS: usize = 12;
204
205/// Parse the fixed-width `YYYYMMDD-HH:MM` prefix shared by UTC and TZ
206/// timestamps. Returns the date, hour, minute and the unconsumed tail.
207/// The month and day are shape-checked here and range-checked by the
208/// calendar (`ValueIsIncorrect` when out of range).
209///
210/// The seconds are left to the caller: UTC timestamps require them, TZ
211/// timestamps do not (TagValue Encoding section 6.2.2).
212fn parse_timestamp_head(
213 buf: &[u8],
214) -> Result<(NaiveDate, u32, u32, &[u8]), DeserializeErrorKindInternal> {
215 let [
216 // Year
217 y3 @ b'0'..=b'9',
218 y2 @ b'0'..=b'9',
219 y1 @ b'0'..=b'9',
220 y0 @ b'0'..=b'9',
221 // Month
222 m1 @ b'0'..=b'1',
223 m0 @ b'0'..=b'9',
224 // Day
225 d1 @ b'0'..=b'3',
226 d0 @ b'0'..=b'9',
227 b'-',
228 // Hour
229 h1 @ b'0'..=b'2',
230 h0 @ b'0'..=b'9',
231 b':',
232 // Minute
233 mm1 @ b'0'..=b'5',
234 mm0 @ b'0'..=b'9',
235 rest @ ..,
236 ] = buf
237 else {
238 // Too short to hold the prefix at all - only more bytes can tell
239 // truncation from malformation.
240 return if buf.len() < 14 {
241 Err(DeserializeErrorKindInternal::Incomplete)
242 } else {
243 Err(DeserializeErrorKindInternal::Error(
244 SessionRejectReasonBase::IncorrectDataFormatForValue,
245 ))
246 };
247 };
248
249 let year = (y3 - b'0') as i32 * 1000
250 + (y2 - b'0') as i32 * 100
251 + (y1 - b'0') as i32 * 10
252 + (y0 - b'0') as i32;
253 let month = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
254 let day = (d1 - b'0') as u32 * 10 + (d0 - b'0') as u32;
255 let naive_date = NaiveDate::from_ymd_opt(year, month, day).ok_or(
256 DeserializeErrorKindInternal::Error(SessionRejectReasonBase::ValueIsIncorrect),
257 )?;
258 let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
259 let min = (mm1 - b'0') as u32 * 10 + (mm0 - b'0') as u32;
260 Ok((naive_date, hour, min, rest))
261}
262
263/// Parse the seconds of a UTC time: 00-59, or 60 for a leap second.
264/// chrono represents a leap second as sec=59 with nanosecond >= 1_000_000_000,
265/// so the leap case reports 59 plus a whole second of nanosecond offset.
266/// Returns (seconds, leap nanosecond offset, rest).
267fn parse_utc_seconds(buf: &[u8]) -> Result<(u32, u32, &[u8]), DeserializeErrorKindInternal> {
268 match buf {
269 [s1 @ b'0'..=b'5', s0 @ b'0'..=b'9', rest @ ..] => {
270 Ok(((s1 - b'0') as u32 * 10 + (s0 - b'0') as u32, 0, rest))
271 }
272 [b'6', b'0', rest @ ..] => Ok((59, 1_000_000_000, rest)),
273 _ if buf.len() < 2 => Err(DeserializeErrorKindInternal::Incomplete),
274 _ => Err(DeserializeErrorKindInternal::Error(
275 SessionRejectReasonBase::IncorrectDataFormatForValue,
276 )),
277 }
278}
279
280/// Parse the optional fractional-second part of a timestamp: either absent
281/// (no leading period) or a period followed by exactly 3, 6, 9 or 12 digits.
282/// Stops at the first non-digit byte and leaves terminator handling to the
283/// caller. A 12-digit (picosecond) fraction is truncated to nanoseconds -
284/// chrono cannot hold picosecond resolution.
285/// Returns (nanoseconds, precision, rest).
286#[expect(
287 clippy::cast_possible_truncation,
288 reason = "the accumulator is reduced to nanoseconds below, so it is at most 999_999_999"
289)]
290fn parse_fraction_of_second(
291 buf: &[u8],
292) -> Result<(u32, TimePrecision, &[u8]), DeserializeErrorKindInternal> {
293 let [b'.', digits @ ..] = buf else {
294 return Ok((0, TimePrecision::Secs, buf));
295 };
296
297 let mut fraction_of_second: u64 = 0;
298 let mut count: usize = 0;
299 for &byte in digits {
300 match byte {
301 // One digit more than the longest valid width can never
302 // become valid, no matter how the value continues.
303 b'0'..=b'9' if count == MAX_FRACTION_DIGITS => {
304 return Err(DeserializeErrorKindInternal::Error(
305 SessionRejectReasonBase::IncorrectDataFormatForValue,
306 ));
307 }
308 n @ b'0'..=b'9' => {
309 // No overflow: at most 12 digits accumulate.
310 fraction_of_second = fraction_of_second * 10 + u64::from(n - b'0');
311 count += 1;
312 }
313 _ => break,
314 }
315 }
316
317 let rest = &digits[count..];
318 let (nanos, precision) = match count {
319 3 => (fraction_of_second * 1_000_000, TimePrecision::Millis),
320 6 => (fraction_of_second * 1_000, TimePrecision::Micros),
321 9 => (fraction_of_second, TimePrecision::Nanos),
322 // chrono can't hold picoseconds - truncate to nanoseconds
323 12 => (fraction_of_second / 1_000, TimePrecision::Nanos),
324 // The digits ran out at the end of the input; more bytes could
325 // still have completed a valid width.
326 _ if rest.is_empty() => return Err(DeserializeErrorKindInternal::Incomplete),
327 _ => {
328 return Err(DeserializeErrorKindInternal::Error(
329 SessionRejectReasonBase::IncorrectDataFormatForValue,
330 ));
331 }
332 };
333 // Bounded by construction: at most 999_999_999.
334 Ok((nanos as u32, precision, rest))
335}
336
337/// Parse a UtcTimestamp value from the start of `buf` without consuming any
338/// terminator. On success returns the parsed value and the unconsumed tail;
339/// the caller decides what must follow (SOH in tag-value streams, end of
340/// input for length-delimited values).
341///
342/// Accepted format is either YYYYMMDD-HH:MM:SS (whole seconds) or
343/// YYYYMMDD-HH:MM:SS.sss* with a 3, 6, 9 or 12 digit fraction (picoseconds
344/// truncated to nanoseconds); SS = 60 is accepted as a UTC leap second.
345pub(crate) fn parse_utc_timestamp(
346 buf: &[u8],
347) -> Result<(UtcTimestamp, &[u8]), DeserializeErrorKindInternal> {
348 let (naive_date, hour, min, rest) = parse_timestamp_head(buf)?;
349 // UTC timestamps always carry seconds.
350 let rest = match rest {
351 [b':', rest @ ..] => rest,
352 [] => return Err(DeserializeErrorKindInternal::Incomplete),
353 _ => {
354 return Err(DeserializeErrorKindInternal::Error(
355 SessionRejectReasonBase::IncorrectDataFormatForValue,
356 ));
357 }
358 };
359 let (sec, leap_offset, rest) = parse_utc_seconds(rest)?;
360 let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
361
362 let naive_date_time = naive_date
363 .and_hms_nano_opt(hour, min, sec, leap_offset + fraction_of_second)
364 .ok_or(DeserializeErrorKindInternal::Error(
365 SessionRejectReasonBase::ValueIsIncorrect,
366 ))?;
367 let timestamp = Utc.from_utc_datetime(&naive_date_time);
368 Ok((UtcTimestamp::with_precision(timestamp, precision), rest))
369}
370
371/// Parse a UtcTimeOnly value from the start of `buf` without consuming any
372/// terminator, mirroring the [`parse_utc_timestamp`] contract.
373///
374/// Accepted format is HH:MM:SS with the same optional fraction as
375/// UtcTimestamp; SS = 60 is accepted as a UTC leap second.
376pub(crate) fn parse_utc_time_only(
377 buf: &[u8],
378) -> Result<(UtcTimeOnly, &[u8]), DeserializeErrorKindInternal> {
379 let [
380 // Hour
381 h1 @ b'0'..=b'2',
382 h0 @ b'0'..=b'9',
383 b':',
384 // Minute
385 m1 @ b'0'..=b'5',
386 m0 @ b'0'..=b'9',
387 b':',
388 rest @ ..,
389 ] = buf
390 else {
391 return if buf.len() < 6 {
392 Err(DeserializeErrorKindInternal::Incomplete)
393 } else {
394 Err(DeserializeErrorKindInternal::Error(
395 SessionRejectReasonBase::IncorrectDataFormatForValue,
396 ))
397 };
398 };
399
400 let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
401 let min = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
402 let (sec, leap_offset, rest) = parse_utc_seconds(rest)?;
403 let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
404
405 let time = NaiveTime::from_hms_nano_opt(hour, min, sec, leap_offset + fraction_of_second)
406 .ok_or(DeserializeErrorKindInternal::Error(
407 SessionRejectReasonBase::ValueIsIncorrect,
408 ))?;
409 Ok((UtcTimeOnly::with_precision(time, precision), rest))
410}
411
412/// Parse a timezone offset from the start of `buf` without consuming any
413/// terminator, mirroring the [`parse_utc_timestamp`] contract.
414///
415/// Accepted format is `Z`, `+hh`, `-hh`, `+hh:mm` or `-hh:mm`, with
416/// `mm` = 00-59 (TagValue Encoding section 6.2.2).
417///
418/// The hour range is left to [`FixedOffset`], which bounds it to less than
419/// a day. The spec text says `hh` = 01-12, but offsets of +13 and +14 exist
420/// and a conforming counterparty may send them.
421//
422// The form with minutes is matched first, so an offset that carries them is
423// never truncated to whole hours; an out-of-range `mm` falls through to the
424// whole-hour form and is rejected by the caller, which finds the leftover
425// digits where a terminator or the end of the value should be.
426fn parse_tz_offset(buf: &[u8]) -> Result<(FixedOffset, &[u8]), DeserializeErrorKindInternal> {
427 let (total_secs, rest) = match buf {
428 [b'Z', rest @ ..] => (0, rest),
429 [
430 sign @ (b'+' | b'-'),
431 h1 @ b'0'..=b'9',
432 h0 @ b'0'..=b'9',
433 b':',
434 m1 @ b'0'..=b'5',
435 m0 @ b'0'..=b'9',
436 rest @ ..,
437 ] => {
438 let hours = (h1 - b'0') as i32 * 10 + (h0 - b'0') as i32;
439 let minutes = (m1 - b'0') as i32 * 10 + (m0 - b'0') as i32;
440 let total_secs = hours * 3600 + minutes * 60;
441 (
442 if *sign == b'-' {
443 -total_secs
444 } else {
445 total_secs
446 },
447 rest,
448 )
449 }
450 [
451 sign @ (b'+' | b'-'),
452 h1 @ b'0'..=b'9',
453 h0 @ b'0'..=b'9',
454 rest @ ..,
455 ] => {
456 let total_secs = ((h1 - b'0') as i32 * 10 + (h0 - b'0') as i32) * 3600;
457 (
458 if *sign == b'-' {
459 -total_secs
460 } else {
461 total_secs
462 },
463 rest,
464 )
465 }
466 [] => return Err(DeserializeErrorKindInternal::Incomplete),
467 _ => {
468 return Err(DeserializeErrorKindInternal::Error(
469 SessionRejectReasonBase::IncorrectDataFormatForValue,
470 ));
471 }
472 };
473
474 let offset = FixedOffset::east_opt(total_secs).ok_or(DeserializeErrorKindInternal::Error(
475 SessionRejectReasonBase::ValueIsIncorrect,
476 ))?;
477 Ok((offset, rest))
478}
479
480/// Parse a TzTimestamp value from the start of `buf` without consuming any
481/// terminator, mirroring the [`parse_utc_timestamp`] contract.
482///
483/// Accepted format is `YYYYMMDD-HH:MM[:SS][.sss*]` followed by a timezone
484/// offset. Unlike UTC timestamps there is no leap second here (SS = 00-59),
485/// and the seconds are optional: the grammar in TagValue Encoding section
486/// 6.2.2 shows them, but every example in that table omits them
487/// ("20060901-07:39Z", "20060901-13:09.123+05:30"). The offset, in contrast,
488/// is required - see [`TzTimestamp`] for why.
489pub(crate) fn parse_tz_timestamp(
490 buf: &[u8],
491) -> Result<(TzTimestamp, &[u8]), DeserializeErrorKindInternal> {
492 let (naive_date, hour, min, rest) = parse_timestamp_head(buf)?;
493 // Optional :SS, same shape as TzTimeOnly - a colon followed by anything
494 // else is left for the stages below to reject.
495 let (sec, rest) = match rest {
496 [b':', s1 @ b'0'..=b'5', s0 @ b'0'..=b'9', rest @ ..] => {
497 ((s1 - b'0') as u32 * 10 + (s0 - b'0') as u32, rest)
498 }
499 _ => (0, rest),
500 };
501 let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
502 let (offset, rest) = parse_tz_offset(rest)?;
503
504 let naive_date_time = naive_date
505 .and_hms_nano_opt(hour, min, sec, fraction_of_second)
506 .ok_or(DeserializeErrorKindInternal::Error(
507 SessionRejectReasonBase::ValueIsIncorrect,
508 ))?;
509 let timestamp = offset
510 .from_local_datetime(&naive_date_time)
511 .single()
512 .ok_or(DeserializeErrorKindInternal::Error(
513 SessionRejectReasonBase::ValueIsIncorrect,
514 ))?;
515 Ok((TzTimestamp::with_precision(timestamp, precision), rest))
516}
517
518/// Parse a TzTimeOnly value from the start of `buf` without consuming any
519/// terminator, mirroring the [`parse_utc_timestamp`] contract.
520///
521/// Accepted format is `HH:MM[:SS][.sss*]` followed by a timezone offset -
522/// the seconds are optional here, and default to zero when absent. The
523/// offset is required - see [`TzTimestamp`] for why.
524pub(crate) fn parse_tz_time_only(
525 buf: &[u8],
526) -> Result<(TzTimeOnly, &[u8]), DeserializeErrorKindInternal> {
527 let [
528 // Hour
529 h1 @ b'0'..=b'2',
530 h0 @ b'0'..=b'9',
531 b':',
532 // Minute
533 m1 @ b'0'..=b'5',
534 m0 @ b'0'..=b'9',
535 rest @ ..,
536 ] = buf
537 else {
538 return if buf.len() < 5 {
539 Err(DeserializeErrorKindInternal::Incomplete)
540 } else {
541 Err(DeserializeErrorKindInternal::Error(
542 SessionRejectReasonBase::IncorrectDataFormatForValue,
543 ))
544 };
545 };
546 let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
547 let min = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
548
549 // Optional :SS. A colon followed by anything else is left for the stages
550 // below to reject - treating it as truncation here would turn a framed
551 // but malformed value into a garbled message, which drops it without a
552 // Reject (FIX Session Test Cases Scenario 14, row f).
553 let (sec, rest) = match rest {
554 [b':', s1 @ b'0'..=b'5', s0 @ b'0'..=b'9', rest @ ..] => {
555 ((s1 - b'0') as u32 * 10 + (s0 - b'0') as u32, rest)
556 }
557 _ => (0, rest),
558 };
559 let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
560 let (offset, rest) = parse_tz_offset(rest)?;
561
562 let time = NaiveTime::from_hms_nano_opt(hour, min, sec, fraction_of_second).ok_or(
563 DeserializeErrorKindInternal::Error(SessionRejectReasonBase::ValueIsIncorrect),
564 )?;
565 Ok((TzTimeOnly::new(time, offset, precision), rest))
566}
567
568/// Parse a Tenor value from the start of `buf` without consuming any
569/// terminator, mirroring the [`parse_utc_timestamp`] contract.
570///
571/// Accepted format is a unit code (`D`, `M`, `W` or `Y`) followed by a
572/// non-zero decimal value, e.g. `M3`. Digits are consumed greedily, so a
573/// tag-value caller must still check that the tail starts with SOH.
574pub(crate) fn parse_tenor(buf: &[u8]) -> Result<(Tenor, &[u8]), DeserializeErrorKindInternal> {
575 let [unit, rest @ ..] = buf else {
576 return Err(DeserializeErrorKindInternal::Incomplete);
577 };
578 let unit = TenorUnit::from_byte(*unit).ok_or(DeserializeErrorKindInternal::Error(
579 SessionRejectReasonBase::IncorrectDataFormatForValue,
580 ))?;
581
582 let mut value: u16 = 0;
583 let mut digits = 0;
584 let mut rest = rest;
585 while let [d @ b'0'..=b'9', tail @ ..] = rest {
586 value = value
587 .checked_mul(10)
588 .and_then(|v| v.checked_add(u16::from(d - b'0')))
589 .ok_or(DeserializeErrorKindInternal::Error(
590 SessionRejectReasonBase::ValueIsIncorrect,
591 ))?;
592 digits += 1;
593 rest = tail;
594 }
595
596 // No digits leaves the value at zero, so one check covers both cases.
597 // With nothing but digits consumed so far, more input could still turn
598 // either of them into a valid value - only an exhausted buffer separates
599 // truncation from malformation.
600 let Some(value) = TenorValue::new(value) else {
601 return if rest.is_empty() {
602 Err(DeserializeErrorKindInternal::Incomplete)
603 } else if digits == 0 {
604 Err(DeserializeErrorKindInternal::Error(
605 SessionRejectReasonBase::IncorrectDataFormatForValue,
606 ))
607 } else {
608 Err(DeserializeErrorKindInternal::Error(
609 SessionRejectReasonBase::ValueIsIncorrect,
610 ))
611 };
612 };
613
614 Ok((Tenor { unit, value }, rest))
615}
616
617fn deserialize_str(bytes: &[u8]) -> Result<(&[u8], &FixStr), DeserializeErrorKindInternal> {
618 for (i, b) in bytes.iter().enumerate() {
619 match b {
620 // No control character is allowed
621 0x00 | 0x02..=0x1f | 0x7f..=0xff => {
622 return Err(DeserializeErrorKindInternal::Error(
623 SessionRejectReasonBase::ValueIsIncorrect,
624 ));
625 }
626 // Except SOH which marks end of tag
627 b'\x01' => {
628 if i == 0 {
629 return Err(DeserializeErrorKindInternal::Error(
630 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
631 ));
632 } else {
633 // SAFETY: Check for valid ASCII values just above
634 return Ok((&bytes[i + 1..], unsafe {
635 FixStr::from_ascii_unchecked(&bytes[..i])
636 }));
637 }
638 }
639 _ => {}
640 }
641 }
642
643 Err(DeserializeErrorKindInternal::Incomplete)
644}
645
646fn deserialize_tag_num(bytes: &[u8]) -> Result<(&[u8], TagNum), DeserializeErrorKindInternal> {
647 if matches!(bytes, [b'0' | b'=', ..]) {
648 return Err(DeserializeErrorKindInternal::Error(
649 SessionRejectReasonBase::InvalidTagNumber,
650 ));
651 }
652
653 let mut value: TagNum = 0;
654 for (i, &byte) in bytes.iter().enumerate() {
655 match byte {
656 n @ b'0'..=b'9' => {
657 value = value
658 .checked_mul(10)
659 .and_then(|v| v.checked_add(TagNum::from(n - b'0')))
660 .ok_or(DeserializeErrorKindInternal::Error(
661 SessionRejectReasonBase::InvalidTagNumber,
662 ))?;
663 }
664 b'=' => return Ok((&bytes[i + 1..], value)),
665 _ => {
666 return Err(DeserializeErrorKindInternal::Error(
667 SessionRejectReasonBase::InvalidTagNumber,
668 ));
669 }
670 }
671 }
672 Err(DeserializeErrorKindInternal::Incomplete)
673}
674
675fn deserialize_length(bytes: &[u8]) -> Result<(&[u8], Length), DeserializeErrorKindInternal> {
676 let mut value: Length = 0;
677 for (i, b) in bytes.iter().enumerate() {
678 match b {
679 n @ b'0'..=b'9' => {
680 value = value
681 .checked_mul(10)
682 .and_then(|v| v.checked_add(Length::from(n - b'0')))
683 .ok_or(DeserializeErrorKindInternal::Error(
684 SessionRejectReasonBase::ValueIsIncorrect,
685 ))?;
686 }
687 b'\x01' => {
688 if i == 0 {
689 return Err(DeserializeErrorKindInternal::Error(
690 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
691 ));
692 } else if value == 0 {
693 return Err(DeserializeErrorKindInternal::Error(
694 SessionRejectReasonBase::ValueIsIncorrect,
695 ));
696 } else {
697 return Ok((&bytes[i + 1..], value));
698 }
699 }
700 _ => {
701 return Err(DeserializeErrorKindInternal::Error(
702 SessionRejectReasonBase::IncorrectDataFormatForValue,
703 ));
704 }
705 }
706 }
707
708 Err(DeserializeErrorKindInternal::Incomplete)
709}
710
711/// One structurally valid FIX message framed out of a byte stream by
712/// [`raw_message`], borrowing from that stream - no bytes are copied.
713///
714/// Framing proves only that BeginString(8), BodyLength(9) and CheckSum(10)
715/// are present and consistent. The body is still unparsed.
716#[derive(Debug)]
717pub struct RawMessage<'a> {
718 /// BeginString(8) value, e.g. `FIXT.1.1`.
719 pub begin_string: &'a FixStr,
720 /// Everything between BodyLength(9) and CheckSum(10), the length that
721 /// tag 9 declared.
722 pub body: &'a [u8],
723 /// CheckSum(10) value, already verified against the framed bytes.
724 pub checksum: u8,
725}
726
727/// Why [`raw_message`] could not frame a message.
728///
729/// The split tells a caller reading from a socket what to do with its buffer;
730/// see [`raw_message`] for how it bounds that buffer.
731#[derive(Debug, thiserror::Error)]
732pub enum RawMessageError {
733 /// A well-formed prefix that stops short. Keep the bytes and read more.
734 #[error("Incomplete")]
735 Incomplete,
736 /// The bytes are not a message and no further input can make them one.
737 /// Drop them and resynchronize.
738 #[error("Garbled")]
739 Garbled,
740 /// Framing held, but CheckSum(10) disagrees with the bytes it covers.
741 /// The frame is complete and its extent is known: skip `frame_len`
742 /// bytes and resume parsing right behind it - no need to scan for the
743 /// next message start.
744 #[error("Invalid checksum")]
745 InvalidChecksum {
746 /// Length of the whole rejected frame, `BeginString(8)` through the
747 /// SOH after `CheckSum(10)`.
748 frame_len: usize,
749 },
750}
751
752impl From<DeserializeErrorKindInternal> for RawMessageError {
753 fn from(d: DeserializeErrorKindInternal) -> RawMessageError {
754 match d {
755 DeserializeErrorKindInternal::Incomplete => RawMessageError::Incomplete,
756 DeserializeErrorKindInternal::Error(_) => RawMessageError::Garbled,
757 }
758 }
759}
760
761/// Frame one message out of `bytes`, returning the unconsumed remainder
762/// alongside it. Zero-copy: the [`RawMessage`] borrows from `bytes`.
763///
764/// The error tells the caller what to do with its buffer, and the
765/// distinction is load-bearing for anything reading from a socket:
766///
767/// - [`Incomplete`] - a well-formed prefix, keep the bytes and read more.
768/// - [`Garbled`] - the bytes are not a message and never will be; drop
769/// them and resynchronize.
770/// - [`InvalidChecksum`] - a complete frame whose `CheckSum(10)` does not
771/// match; its length is known, so skip exactly that many bytes.
772///
773/// That split is what bounds the caller's buffer. `BodyLength<9>` is parsed
774/// into a [`Length`], so a value beyond what that type holds is *out of
775/// range* rather than merely unsatisfied, and comes back as [`Garbled`] -
776/// not [`Incomplete`] - as soon as the length field itself has arrived,
777/// long before a body of that size could be buffered. The two fields
778/// before it are bounded the same way: a `BeginString<8>` value with no SOH
779/// within [`Version::MAX_BEGIN_STRING_LEN`] bytes is [`Garbled`], and so is
780/// a `BodyLength<9>` with more digits than a [`Length`] holds. A caller
781/// that keeps calling this before each read therefore never holds more
782/// than one message's worth of bytes, as [`Length`] bounds it - and
783/// [`frame_len`] lets it stop at a tighter limit of its own.
784///
785/// [`Incomplete`]: RawMessageError::Incomplete
786/// [`Garbled`]: RawMessageError::Garbled
787/// [`InvalidChecksum`]: RawMessageError::InvalidChecksum
788/// [`Length`]: crate::basic_types::Length
789//
790// Widening Length would silently turn a hostile `9=99999999` into an
791// unbounded read.
792pub fn raw_message(bytes: &[u8]) -> Result<(&[u8], RawMessage<'_>), RawMessageError> {
793 let orig_bytes = bytes;
794
795 let (bytes, begin_string, body_length) = frame_prefix(bytes)?;
796
797 const CHECKSUM_LEN: usize = 4;
798 if bytes.len() < body_length + CHECKSUM_LEN {
799 return Err(RawMessageError::Incomplete);
800 }
801
802 let body = &bytes[..body_length];
803 let bytes = &bytes[body_length..];
804
805 let calculated_checksum = orig_bytes[0..orig_bytes.len() - bytes.len()]
806 .iter()
807 .fold(0, |acc: u8, x| acc.wrapping_add(*x));
808
809 let bytes = deserialize_tag(bytes, b"10=")?;
810 let (bytes, checksum) = deserialize_checksum(bytes)?;
811 if u16::from(calculated_checksum) != checksum {
812 return Err(RawMessageError::InvalidChecksum {
813 frame_len: orig_bytes.len() - bytes.len(),
814 });
815 }
816 Ok((
817 bytes,
818 RawMessage {
819 begin_string,
820 body,
821 checksum: calculated_checksum,
822 },
823 ))
824}
825
826/// Parses the framing prefix - `BeginString(8)` and `BodyLength(9)` - and
827/// returns the bytes after it, the BeginString and the declared body length.
828fn frame_prefix(bytes: &[u8]) -> Result<(&[u8], &FixStr, usize), RawMessageError> {
829 let bytes = deserialize_tag(bytes, b"8=")?;
830 // The value scan stops at SOH, so without one it would stay `Incomplete`
831 // for as long as printable bytes keep coming - an unbounded read. No
832 // known version's BeginString is longer than `MAX_BEGIN_STRING_LEN`, so
833 // once that many bytes are in without a SOH the prefix is not a frame.
834 let (bytes, begin_string) = match deserialize_str(bytes) {
835 Err(DeserializeErrorKindInternal::Incomplete)
836 if bytes.len() > Version::MAX_BEGIN_STRING_LEN =>
837 {
838 return Err(RawMessageError::Garbled);
839 }
840 result => result?,
841 };
842 let bytes = deserialize_tag(bytes, b"9=")?;
843 let (bytes, body_length) = deserialize_length(bytes)?;
844 Ok((bytes, begin_string, usize::from(body_length)))
845}
846
847/// Length of the `CheckSum(10)` trailer: `10=`, three digits, SOH.
848const TRAILER_LEN: usize = 7;
849
850/// Total length of the frame starting at `bytes[0]`, known as soon as its
851/// `BeginString(8)` and `BodyLength(9)` have arrived: the two framing
852/// fields, `BodyLength(9)` bytes of body and the `CheckSum(10)` trailer.
853///
854/// A reader that must not buffer more than a limit asks this before
855/// [`raw_message`]: the verdict comes from the length field alone, long
856/// before a body of that size could arrive. Errors are those of
857/// [`raw_message`] on the same bytes - [`Incomplete`] while the framing
858/// fields themselves are still arriving, [`Garbled`] when they are
859/// malformed. Whether the body and trailer are present, or the checksum
860/// holds, is not judged here.
861///
862/// [`Incomplete`]: RawMessageError::Incomplete
863/// [`Garbled`]: RawMessageError::Garbled
864pub fn frame_len(bytes: &[u8]) -> Result<usize, RawMessageError> {
865 let (rest, _, body_length) = frame_prefix(bytes)?;
866 Ok(bytes.len() - rest.len() + body_length + TRAILER_LEN)
867}
868
869/// An independent, borrowed cursor over field tags and values.
870///
871/// At a field boundary, read a tag with [`next_tag`](Self::next_tag), then
872/// consume its value with the appropriate read method. Value reads require
873/// the cursor to be at the start of a value. The caller determines each
874/// field's encoding; the cursor does not detect calls from mid-value.
875/// Copies advance independently and never consume the original deserializer.
876/// A read returns `None` when input is exhausted, malformed, or truncated;
877/// stop scanning when that happens.
878#[derive(Debug, Clone, Copy)]
879pub struct FieldCursor<'de> {
880 buf: &'de [u8],
881 tmp_tag: Option<TagNum>,
882}
883
884impl<'de> FieldCursor<'de> {
885 /// Read the next tag, including any tag pushed back before this cursor
886 /// was created. Call only at a field boundary, after consuming the
887 /// preceding value. Returns `None` at EOF or for malformed tag syntax.
888 pub fn next_tag(&mut self) -> Option<TagNum> {
889 if let Some(tag) = self.tmp_tag.take() {
890 return Some(tag);
891 }
892 let (rest, tag) = deserialize_tag_num(self.buf).ok()?;
893 self.buf = rest;
894 Some(tag)
895 }
896
897 /// Read bytes up to SOH without validating their contents. Returns `None`
898 /// if the delimiter is absent; an empty delimited value is valid here.
899 pub fn read_delimited(&mut self) -> Option<&'de [u8]> {
900 let end = memchr(b'\x01', self.buf)?;
901 let value = &self.buf[..end];
902 self.buf = &self.buf[end + 1..];
903 Some(value)
904 }
905
906 /// Read a positive `Length` and its SOH delimiter. Returns `None` for
907 /// zero, overflow, malformed contents, or a missing delimiter.
908 pub fn read_length(&mut self) -> Option<Length> {
909 let (rest, length) = deserialize_length(self.buf).ok()?;
910 self.buf = rest;
911 Some(length)
912 }
913
914 /// Read exactly `len` bytes and their following SOH without interpreting
915 /// the data. Returns `None` if the data or delimiter is missing or the
916 /// byte after the data is not SOH.
917 pub fn read_data(&mut self, len: Length) -> Option<&'de [u8]> {
918 let len = usize::from(len);
919 let rest = self.buf.get(len..)?.strip_prefix(b"\x01")?;
920 let value = &self.buf[..len];
921 self.buf = rest;
922 Some(value)
923 }
924}
925
926/// Reads typed FIX values out of a framed [`RawMessage`], field by field.
927///
928/// A cursor walks the body: [`deserialize_tag_num`](Self::deserialize_tag_num)
929/// yields the next tag, and the matching `deserialize_*` call consumes that
930/// tag's value together with its SOH. String-valued reads borrow from the
931/// original bytes, so parsing a message copies nothing that is not owned.
932///
933/// Generated code drives this in three phases - declare an `Option` per
934/// field, loop over tags dispatching to `deserialize_*`, then build the
935/// struct - and hands a tag back with [`put_tag`](Self::put_tag) when it
936/// belongs to the next message section.
937#[derive(Debug)]
938pub struct Deserializer<'de> {
939 raw_message: RawMessage<'de>,
940 buf: &'de [u8],
941 msg_type: Option<ops::Range<usize>>,
942 seq_num: Option<SeqNum>,
943 current_tag: Option<TagNum>,
944 // Used to put tag back to deserializer, when switching to deserialization
945 // another message section.
946 tmp_tag: Option<TagNum>,
947}
948
949impl<'de> Deserializer<'de> {
950 /// Start reading `raw_message`'s body from its first tag.
951 pub fn from_raw_message(raw_message: RawMessage) -> Deserializer {
952 let buf = raw_message.body;
953 Deserializer {
954 raw_message,
955 buf,
956 msg_type: None,
957 seq_num: None,
958 current_tag: None,
959 tmp_tag: None,
960 }
961 }
962
963 /// BeginString(8), as an owned copy. Consumed by the framing, so it is
964 /// read from here rather than from the tag stream.
965 pub fn begin_string(&self) -> FixString {
966 self.raw_message.begin_string.to_owned()
967 }
968
969 /// BodyLength(9). Consumed by the framing, so it is read from here rather
970 /// than from the tag stream.
971 #[expect(
972 clippy::cast_possible_truncation,
973 reason = "`raw_message` cuts the body to a `Length`-typed BodyLength(9), so it never exceeds `Length::MAX`"
974 )]
975 pub fn body_length(&self) -> Length {
976 self.raw_message.body.len() as Length
977 }
978
979 /// CheckSum(10), zero-padded to three digits. Consumed by the framing, so
980 /// it is read from here rather than from the tag stream.
981 pub fn check_sum(&self) -> FixString {
982 FixString::from_ascii_lossy(format!("{:03}", self.raw_message.checksum).into_bytes())
983 }
984
985 /// Record MsgSeqNum(34) so a later [`reject`](Self::reject) can quote it.
986 ///
987 /// Call once, right after reading tag 34; a second call is a bug and trips
988 /// a debug assertion. Without it a reject falls back to scanning the body
989 /// for `34=`, which a binary field can defeat.
990 pub fn set_seq_num(&mut self, seq_num: SeqNum) {
991 debug_assert!(self.seq_num.is_none());
992
993 self.seq_num = Some(seq_num);
994 }
995
996 // This may fail when RawData or XmlData fields (or other binary fields)
997 // are located before MsgSeqNum and has value `34=` inside
998 fn try_find_msg_seq_num(&mut self) -> Result<SeqNum, DeserializeErrorKind> {
999 static FINDER: LazyLock<memmem::Finder<'static>> =
1000 LazyLock::new(|| memmem::Finder::new(b"34="));
1001
1002 let start_index = FINDER
1003 .find(self.buf)
1004 .ok_or(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing))?;
1005 let saved_buf = self.buf;
1006 self.buf = &self.buf[start_index + FINDER.needle().len()..];
1007
1008 // Error diagnostics may still need to inspect the original input,
1009 // including a pushed-back tag whose value starts at saved_buf.
1010 let result = self.deserialize_seq_num();
1011 self.buf = saved_buf;
1012 result
1013 }
1014
1015 /// Build a [`DeserializeErrorKind::Reject`] blaming `tag` for `reason`,
1016 /// quoting the MsgSeqNum and MsgType read so far.
1017 ///
1018 /// Returns [`DeserializeErrorKind::Logout`] instead when MsgSeqNum(34) was
1019 /// neither recorded nor recoverable - a message without tag 34 is a logout
1020 /// offence, not a reject (FIX Session Layer ยง4.5.3).
1021 pub fn reject(
1022 &mut self,
1023 tag: Option<TagNum>,
1024 reason: SessionRejectReasonBase,
1025 ) -> DeserializeErrorKind {
1026 let seq_num = if let Some(seq_num) = self.seq_num {
1027 seq_num
1028 } else {
1029 match self.try_find_msg_seq_num() {
1030 Ok(seq_num) => seq_num,
1031 Err(err) => return err,
1032 }
1033 };
1034
1035 DeserializeErrorKind::Reject {
1036 msg_type: self.msg_type.clone().map(|msg_type| {
1037 FixString::from_ascii_lossy(self.raw_message.body[msg_type].to_vec())
1038 }),
1039 seq_num,
1040 tag,
1041 reason: reason.into(),
1042 }
1043 }
1044
1045 /// Build a `RepeatingGroupFieldsOutOfOrder` reject, blaming whichever tag
1046 /// the group's declared order says is misplaced.
1047 ///
1048 /// `expected_tags` is the group's field order from the dictionary,
1049 /// `processed_tags` those already seen in this group instance, and
1050 /// `current_tag` the one that triggered the check. When an earlier
1051 /// processed tag should have come after `current_tag`, that tag is quoted
1052 /// as `RefTagID(371)`; otherwise `current_tag` is.
1053 pub fn repeating_group_fields_out_of_order(
1054 &mut self,
1055 expected_tags: &[u16],
1056 processed_tags: &[u16],
1057 current_tag: u16,
1058 ) -> DeserializeErrorKind {
1059 let mut current_tag_found = false;
1060 'outer: for processed_tag in processed_tags {
1061 for expected_tag in expected_tags {
1062 if expected_tag == processed_tag {
1063 if current_tag_found {
1064 return self.reject(
1065 Some(*processed_tag),
1066 SessionRejectReasonBase::RepeatingGroupFieldsOutOfOrder,
1067 );
1068 } else {
1069 continue 'outer;
1070 }
1071 } else if *expected_tag == current_tag {
1072 current_tag_found = true;
1073 }
1074 }
1075 }
1076 // No earlier processed tag is misplaced relative to `current_tag`
1077 // (or `current_tag` is not part of this group at all) - blame the
1078 // tag that triggered the check.
1079 self.reject(
1080 Some(current_tag),
1081 SessionRejectReasonBase::RepeatingGroupFieldsOutOfOrder,
1082 )
1083 }
1084
1085 /// Push `tag` back so the next
1086 /// [`deserialize_tag_num`](Self::deserialize_tag_num) returns it again.
1087 ///
1088 /// One tag of lookahead, used when a section's parser reads a tag that
1089 /// belongs to the next section - a trailer tag surfacing while the body is
1090 /// still being read, say. A second push before the tag is taken overwrites
1091 /// the first.
1092 pub fn put_tag(&mut self, tag: TagNum) {
1093 self.tmp_tag = Some(tag);
1094 }
1095
1096 /// Copy the current read position, including any pushed-back tag, into
1097 /// an independent cursor. Creating or advancing it leaves this
1098 /// deserializer unchanged. If a tag was already consumed without being
1099 /// pushed back, the cursor starts at that tag's value.
1100 pub fn field_cursor(&self) -> FieldCursor<'de> {
1101 FieldCursor {
1102 buf: self.buf,
1103 tmp_tag: self.tmp_tag,
1104 }
1105 }
1106
1107 // Build a Reject for a malformed field value, skipping the remainder of
1108 // the current field first so the fallback MsgSeqNum scan inside `reject`
1109 // cannot match bytes of the malformed value itself.
1110 fn reject_value(&mut self, reason: SessionRejectReasonBase) -> DeserializeErrorKind {
1111 match memchr(b'\x01', self.buf) {
1112 Some(i) => self.buf = &self.buf[i + 1..],
1113 None => self.buf = &[],
1114 }
1115 self.reject(self.current_tag, reason)
1116 }
1117
1118 // Map a value-parser error: exhausted input is a garbled message, a
1119 // format violation is a Reject (built after skipping the field).
1120 fn garbled_or_reject_value(
1121 &mut self,
1122 error: DeserializeErrorKindInternal,
1123 ) -> DeserializeErrorKind {
1124 match error {
1125 DeserializeErrorKindInternal::Incomplete => {
1126 DeserializeErrorKind::Garbled(GarbledReason::IncompleteMessageData)
1127 }
1128 DeserializeErrorKindInternal::Error(reason) => self.reject_value(reason),
1129 }
1130 }
1131
1132 // Consume the SOH terminating a just-parsed value whose unconsumed tail
1133 // is `rest`, advancing the buffer past it.
1134 fn finish_value<T>(&mut self, value: T, rest: &'de [u8]) -> Result<T, DeserializeErrorKind> {
1135 match rest {
1136 [b'\x01', tail @ ..] => {
1137 self.buf = tail;
1138 Ok(value)
1139 }
1140 // Buffer ended before the terminating SOH
1141 [] => Err(DeserializeErrorKind::Garbled(
1142 GarbledReason::IncompleteMessageData,
1143 )),
1144 // Value bytes not followed by SOH
1145 _ => Err(self.reject_value(SessionRejectReasonBase::IncorrectDataFormatForValue)),
1146 }
1147 }
1148
1149 /// Resolve a range handed out by
1150 /// [`deserialize_msg_type`](Self::deserialize_msg_type) back into the
1151 /// bytes it names, borrowed from the message.
1152 ///
1153 /// Only pass ranges this deserializer produced. A range from anywhere else
1154 /// names bytes this deserializer never checked - a message body may hold
1155 /// arbitrary bytes inside a `Data` field - and is rejected rather than
1156 /// trusted.
1157 ///
1158 /// # Panics
1159 ///
1160 /// If `range` is out of the message body's bounds, or names bytes that are
1161 /// not printable ASCII. Either means the range did not come from here.
1162 pub fn range_to_fixstr(&self, range: ops::Range<usize>) -> &FixStr {
1163 // A range from `deserialize_msg_type` cannot fail this check:
1164 // `deserialize_str` already rejected every byte outside 0x20..=0x7e.
1165 // Validating anyway costs two comparisons for a 1-2 byte MsgType, and
1166 // buys the difference between a panic and undefined behavior - the
1167 // unchecked construction would hand out a `FixStr` breaking its
1168 // printable-ASCII invariant, on which `as_utf8` skips UTF-8 validation.
1169 FixStr::from_ascii(&self.raw_message.body[range])
1170 .expect("range does not name a printable-ASCII value")
1171 }
1172
1173 /// Read MsgType(35) and remember it for later rejects.
1174 ///
1175 /// Returns the value's range within the message body rather than the
1176 /// bytes, so the borrow ends here and the deserializer stays mutably
1177 /// usable; resolve it with
1178 /// [`range_to_fixstr`](Self::range_to_fixstr) when the bytes are needed.
1179 pub fn deserialize_msg_type(&mut self) -> Result<ops::Range<usize>, DeserializeErrorKind> {
1180 let raw_message_pointer = self.raw_message.body.as_ptr();
1181
1182 let msg_type_range = {
1183 let Ok(deser_str) = self.deserialize_str() else {
1184 return Err(self.reject(Some(35), SessionRejectReasonBase::InvalidMsgType));
1185 };
1186 let msg_type_pointer = deser_str.as_bytes().as_ptr();
1187 // SAFETY: `deserialize_str` returns a subslice of `self.buf`,
1188 // which is always a subslice of `raw_message.body`, so both
1189 // pointers point into the same allocation.
1190 let msg_type_start_index =
1191 unsafe { msg_type_pointer.offset_from_unsigned(raw_message_pointer) };
1192 let msg_type_len = deser_str.len();
1193 msg_type_start_index..(msg_type_start_index + msg_type_len)
1194 };
1195
1196 self.msg_type = Some(msg_type_range.clone());
1197 Ok(msg_type_range)
1198 }
1199
1200 /// Deserialize sequence of character digits without commas or decimals.
1201 /// Value must be positive and may not contain leading zeros.
1202 pub fn deserialize_tag_num(&mut self) -> Result<Option<TagNum>, DeserializeErrorKind> {
1203 if self.tmp_tag.is_some() {
1204 return Ok(self.tmp_tag.take());
1205 }
1206
1207 if self.buf.is_empty() {
1208 return Ok(None);
1209 }
1210
1211 match deserialize_tag_num(self.buf) {
1212 Ok((rest, tag)) => {
1213 self.buf = rest;
1214 self.current_tag = Some(tag);
1215 Ok(Some(tag))
1216 }
1217 Err(DeserializeErrorKindInternal::Incomplete) => Err(DeserializeErrorKind::Garbled(
1218 GarbledReason::IncompleteMessageData,
1219 )),
1220 Err(DeserializeErrorKindInternal::Error(reason)) => Err(self.reject(None, reason)),
1221 }
1222 }
1223
1224 /// Deserialize sequence of character digits without commas or decimals
1225 /// and optional sign character (characters `-` and `0` - `9`).
1226 /// The sign character utilizes one octet (i.e., positive int is `99999`
1227 /// while negative int is `-99999`).
1228 ///
1229 /// Note that int values may contain leading zeros (e.g. `00023` = `23`).
1230 pub fn deserialize_int(&mut self) -> Result<Int, DeserializeErrorKind> {
1231 let negative = match self.buf {
1232 // MSG Garbled
1233 [] => {
1234 return Err(DeserializeErrorKind::Garbled(
1235 GarbledReason::IncompleteMessageData,
1236 ));
1237 }
1238 [b'\x01', ..] => {
1239 return Err(self.reject(
1240 self.current_tag,
1241 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1242 ));
1243 }
1244 [b'-', b'\x01', ..] => {
1245 return Err(self.reject(
1246 self.current_tag,
1247 SessionRejectReasonBase::IncorrectDataFormatForValue,
1248 ));
1249 }
1250 [b'-', buf @ ..] => {
1251 self.buf = buf;
1252 true
1253 }
1254 _ => false,
1255 };
1256
1257 let mut value: Int = 0;
1258 for (i, &byte) in self.buf.iter().enumerate() {
1259 match byte {
1260 n @ b'0'..=b'9' => {
1261 value = value
1262 .checked_mul(10)
1263 .and_then(|v| v.checked_add((n - b'0') as Int))
1264 .ok_or_else(|| {
1265 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1266 })?;
1267 }
1268 b'\x01' => {
1269 // SAFETY: i is from iterating self.buf, so i + 1 <= self.buf.len()
1270 let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
1271 self.buf = rest;
1272 return Ok(if negative { -value } else { value });
1273 }
1274 _ => {
1275 return Err(self.reject(
1276 self.current_tag,
1277 SessionRejectReasonBase::IncorrectDataFormatForValue,
1278 ));
1279 }
1280 }
1281 }
1282
1283 Err(DeserializeErrorKind::Garbled(
1284 GarbledReason::IncompleteMessageData,
1285 ))
1286 }
1287
1288 /// Deserialize sequence of character digits without commas or decimals.
1289 /// Value must be positive.
1290 pub fn deserialize_seq_num(&mut self) -> Result<SeqNum, DeserializeErrorKind> {
1291 match self.buf {
1292 // No more data, MSG Garbled
1293 [] => {
1294 return Err(DeserializeErrorKind::Garbled(
1295 GarbledReason::IncompleteMessageData,
1296 ));
1297 }
1298 [b'\x01', ..] => {
1299 return Err(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing));
1300 }
1301 _ => {}
1302 }
1303
1304 let mut value: SeqNum = 0;
1305 for (i, &byte) in self.buf.iter().enumerate() {
1306 match byte {
1307 n @ b'0'..=b'9' => {
1308 value = value
1309 .checked_mul(10)
1310 .and_then(|v| v.checked_add((n - b'0') as SeqNum))
1311 .ok_or(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing))?;
1312 }
1313 b'\x01' => {
1314 // SAFETY: i is from iterating self.buf, so i + 1 <= self.buf.len()
1315 let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
1316 self.buf = rest;
1317 // Zero passes through: `EndSeqNo(16)` uses it for "no
1318 // upper bound" and other SeqNum-typed fields give it
1319 // meanings of their own. `Serializer::serialize_seq_num`
1320 // accepts it for the same reason - which zeros are legal
1321 // is the session layer's call, not the codec's.
1322 return Ok(value);
1323 }
1324 _ => return Err(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing)),
1325 }
1326 }
1327
1328 Err(DeserializeErrorKind::Garbled(
1329 GarbledReason::IncompleteMessageData,
1330 ))
1331 }
1332
1333 /// Deserialize sequence of character digits without commas or decimals.
1334 /// Value must be positive.
1335 pub fn deserialize_num_in_group(&mut self) -> Result<NumInGroup, DeserializeErrorKind> {
1336 match self.buf {
1337 // MSG Garbled
1338 [] => {
1339 return Err(DeserializeErrorKind::Garbled(
1340 GarbledReason::IncompleteMessageData,
1341 ));
1342 }
1343 [b'\x01', ..] => {
1344 return Err(self.reject(
1345 self.current_tag,
1346 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1347 ));
1348 }
1349 _ => {}
1350 }
1351
1352 let mut value: NumInGroup = 0;
1353 for (i, &byte) in self.buf.iter().enumerate() {
1354 match byte {
1355 n @ b'0'..=b'9' => {
1356 value = value
1357 .checked_mul(10)
1358 .and_then(|v| v.checked_add((n - b'0') as NumInGroup))
1359 .ok_or_else(|| {
1360 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1361 })?;
1362 }
1363 b'\x01' => {
1364 if value == 0 {
1365 return Err(self
1366 .reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect));
1367 } else {
1368 // SAFETY: i is from iterating self.buf, so i + 1 <= self.buf.len()
1369 let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
1370 self.buf = rest;
1371 return Ok(value);
1372 }
1373 }
1374 _ => {
1375 return Err(self.reject(
1376 self.current_tag,
1377 SessionRejectReasonBase::IncorrectDataFormatForValue,
1378 ));
1379 }
1380 }
1381 }
1382
1383 Err(DeserializeErrorKind::Garbled(
1384 GarbledReason::IncompleteMessageData,
1385 ))
1386 }
1387
1388 /// Deserialize sequence of character digits without commas or decimals
1389 /// (values 1 to 31).
1390 pub fn deserialize_day_of_month(&mut self) -> Result<DayOfMonth, DeserializeErrorKind> {
1391 match self.buf {
1392 // MSG Garbled
1393 [] => {
1394 return Err(DeserializeErrorKind::Garbled(
1395 GarbledReason::IncompleteMessageData,
1396 ));
1397 }
1398 [b'\x01', ..] => {
1399 return Err(self.reject(
1400 self.current_tag,
1401 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1402 ));
1403 }
1404 [b'0', ..] => {
1405 return Err(
1406 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1407 );
1408 }
1409 _ => {}
1410 };
1411
1412 let mut value: NumInGroup = 0;
1413 for (i, &byte) in self.buf.iter().enumerate() {
1414 match byte {
1415 n @ b'0'..=b'9' => {
1416 value = value
1417 .checked_mul(10)
1418 .and_then(|v| v.checked_add((n - b'0') as NumInGroup))
1419 .ok_or_else(|| {
1420 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1421 })?;
1422 }
1423 b'\x01' => {
1424 // SAFETY: i is from iterating self.buf, so i + 1 <= self.buf.len()
1425 let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
1426 self.buf = rest;
1427 break;
1428 }
1429 _ => {
1430 return Err(self.reject(
1431 self.current_tag,
1432 SessionRejectReasonBase::IncorrectDataFormatForValue,
1433 ));
1434 }
1435 }
1436 }
1437
1438 match value {
1439 1..=31 => Ok(value),
1440 _ => Err(self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)),
1441 }
1442 }
1443
1444 /// Deserialize sequence of character digits with optional decimal point
1445 /// and sign character (characters `-`, `0` - `9` and `.`);
1446 /// the absence of the decimal point within the string will be interpreted
1447 /// as the float representation of an integer value. Note that float values
1448 /// may contain leading zeros (e.g. `00023.23` = `23.23`) and may contain
1449 /// or omit trailing zeros after the decimal point
1450 /// (e.g. `23.0` = `23.0000` = `23` = `23.`).
1451 ///
1452 /// All float fields must accommodate up to fifteen significant digits.
1453 /// The number of decimal places used should be a factor of business/market
1454 /// needs and mutual agreement between counterparties.
1455 pub fn deserialize_float(&mut self) -> Result<Float, DeserializeErrorKind> {
1456 let (negative, buf) = match self.buf {
1457 [] => {
1458 return Err(DeserializeErrorKind::Garbled(
1459 GarbledReason::IncompleteMessageData,
1460 ));
1461 }
1462 [b'\x01', ..] => {
1463 return Err(self.reject(
1464 self.current_tag,
1465 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1466 ));
1467 }
1468 [b'-', b'\x01', ..] => {
1469 return Err(self.reject(
1470 self.current_tag,
1471 SessionRejectReasonBase::IncorrectDataFormatForValue,
1472 ));
1473 }
1474 [b'-', buf @ ..] => (true, buf),
1475 _ => (false, self.buf),
1476 };
1477
1478 let mut num: i64 = 0;
1479 let mut scale = None;
1480 for (i, &byte) in buf.iter().enumerate() {
1481 match byte {
1482 n @ b'0'..=b'9' => {
1483 num = num
1484 .checked_mul(10)
1485 .and_then(|v| v.checked_add((n - b'0') as i64))
1486 .ok_or_else(|| {
1487 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1488 })?;
1489 if let Some(scale) = scale.as_mut() {
1490 *scale += 1;
1491 }
1492 }
1493 b'.' => {
1494 if scale.is_some() {
1495 return Err(self.reject(
1496 self.current_tag,
1497 SessionRejectReasonBase::IncorrectDataFormatForValue,
1498 ));
1499 }
1500 scale = Some(0);
1501 }
1502 b'\x01' => {
1503 // SAFETY: i is from iterating buf, so i + 1 <= buf.len()
1504 let (_, rest) = unsafe { buf.split_at_unchecked(i + 1) };
1505 self.buf = rest;
1506 let scale = scale.unwrap_or(0);
1507 return Decimal::try_new(if negative { -num } else { num }, scale).map_err(
1508 |_| {
1509 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1510 },
1511 );
1512 }
1513 _ => {
1514 return Err(self.reject(
1515 self.current_tag,
1516 SessionRejectReasonBase::IncorrectDataFormatForValue,
1517 ));
1518 }
1519 }
1520 }
1521
1522 Err(DeserializeErrorKind::Garbled(
1523 GarbledReason::IncompleteMessageData,
1524 ))
1525 }
1526
1527 /// Deserialize a `Qty` - the `Float` grammar under a different name.
1528 #[inline(always)]
1529 pub fn deserialize_qty(&mut self) -> Result<Qty, DeserializeErrorKind> {
1530 self.deserialize_float()
1531 }
1532
1533 /// Deserialize a `Price` - the `Float` grammar under a different name.
1534 #[inline(always)]
1535 pub fn deserialize_price(&mut self) -> Result<Price, DeserializeErrorKind> {
1536 self.deserialize_float()
1537 }
1538
1539 /// Deserialize a `PriceOffset` - the `Float` grammar under a different
1540 /// name.
1541 #[inline(always)]
1542 pub fn deserialize_price_offset(&mut self) -> Result<PriceOffset, DeserializeErrorKind> {
1543 self.deserialize_float()
1544 }
1545
1546 /// Deserialize an `Amt` - the `Float` grammar under a different name.
1547 #[inline(always)]
1548 pub fn deserialize_amt(&mut self) -> Result<Amt, DeserializeErrorKind> {
1549 self.deserialize_float()
1550 }
1551
1552 /// Deserialize a `Percentage` - the `Float` grammar under a different
1553 /// name.
1554 #[inline(always)]
1555 pub fn deserialize_percentage(&mut self) -> Result<Percentage, DeserializeErrorKind> {
1556 self.deserialize_float()
1557 }
1558
1559 /// Deserialize a single-character boolean: `Y` for true, `N` for false.
1560 pub fn deserialize_boolean(&mut self) -> Result<Boolean, DeserializeErrorKind> {
1561 match self.buf {
1562 // Empty or missing separator at the end
1563 [] => Err(DeserializeErrorKind::Garbled(
1564 GarbledReason::IncompleteMessageData,
1565 )),
1566 [b'Y'] | [b'N'] => Err(DeserializeErrorKind::Garbled(
1567 GarbledReason::IncompleteMessageData,
1568 )),
1569 [b'\x01', ..] => Err(self.reject(
1570 self.current_tag,
1571 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1572 )),
1573 [b'Y', b'\x01', buf @ ..] => {
1574 self.buf = buf;
1575 Ok(true)
1576 }
1577 [b'N', b'\x01', buf @ ..] => {
1578 self.buf = buf;
1579 Ok(false)
1580 }
1581 _ => Err(self.reject(
1582 self.current_tag,
1583 SessionRejectReasonBase::IncorrectDataFormatForValue,
1584 )),
1585 }
1586 }
1587
1588 /// Deserialize any ASCII character except control characters.
1589 pub fn deserialize_char(&mut self) -> Result<Char, DeserializeErrorKind> {
1590 match self.buf {
1591 [] => Err(DeserializeErrorKind::Garbled(
1592 GarbledReason::IncompleteMessageData,
1593 )),
1594 [b'\x01', ..] => Err(self.reject(
1595 self.current_tag,
1596 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1597 )),
1598 // ASCII control characters range (including DEL) + unused range
1599 [0x00..=0x1f | 0x7f..=0xff, ..] => {
1600 Err(self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect))
1601 }
1602 [n, b'\x01', buf @ ..] => {
1603 self.buf = buf;
1604 Ok(*n)
1605 }
1606 // Missing separator at the end
1607 [_, byte] if *byte != b'\x01' => Err(DeserializeErrorKind::Garbled(
1608 GarbledReason::MessageNotWellFormed,
1609 )),
1610 _ => Err(self.reject(
1611 self.current_tag,
1612 SessionRejectReasonBase::IncorrectDataFormatForValue,
1613 )),
1614 }
1615 }
1616
1617 /// Deserialize string containing one or more space-delimited single
1618 /// character values, e.g. `2 A F`.
1619 pub fn deserialize_multiple_char_value(
1620 &mut self,
1621 ) -> Result<MultipleCharValue, DeserializeErrorKind> {
1622 match self.buf {
1623 [] => {
1624 return Err(DeserializeErrorKind::Garbled(
1625 GarbledReason::IncompleteMessageData,
1626 ));
1627 }
1628 [b'\x01', ..] => {
1629 return Err(self.reject(
1630 self.current_tag,
1631 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1632 ));
1633 }
1634 _ => {}
1635 }
1636
1637 let i = memchr(b'\x01', self.buf).ok_or(DeserializeErrorKind::Garbled(
1638 GarbledReason::IncompleteMessageData,
1639 ))?;
1640
1641 // SAFETY: i is from memchr on self.buf, so i < self.buf.len(),
1642 // thus i + 1 <= self.buf.len()
1643 let (data, rest) = unsafe { self.buf.split_at_unchecked(i) };
1644 // SAFETY: rest is self.buf[i..] and i < self.buf.len(), so rest still
1645 // holds the separator memchr found - rest.len() >= 1
1646 let (_, rest) = unsafe { rest.split_at_unchecked(1) };
1647 self.buf = rest;
1648 let mut result = MultipleCharValue::with_capacity(data.len() / 2 + 1);
1649 for chunk in data.chunks(2) {
1650 match chunk {
1651 [b' '] | [b' ', _] => {
1652 return Err(self.reject(
1653 self.current_tag,
1654 SessionRejectReasonBase::IncorrectDataFormatForValue,
1655 ));
1656 }
1657 // Latin-1 controll characters ranges
1658 // [0x00..=0x1f] | [0x80..=0x9f] | [0x00..=0x1f, _] | [0x80..=0x9f, _] => {
1659
1660 // ASCII controll character range + unused range. The two-byte
1661 // arms are what every character but the last one hits - a
1662 // chunk is only one byte long when `data` has an odd length.
1663 [0x00..=0x1f] | [0x7f..=0xff] | [0x00..=0x1f, _] | [0x7f..=0xff, _] => {
1664 return Err(
1665 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1666 );
1667 }
1668 [n] | [n, b' '] => result.push(*n),
1669 _ => {
1670 return Err(self.reject(
1671 self.current_tag,
1672 SessionRejectReasonBase::IncorrectDataFormatForValue,
1673 ));
1674 }
1675 }
1676 }
1677 Ok(result)
1678 }
1679
1680 /// Deserialize alphanumeric free-format strings can include any character
1681 /// except control characters.
1682 pub fn deserialize_str(&mut self) -> Result<&FixStr, DeserializeErrorKind> {
1683 match deserialize_str(self.buf) {
1684 Ok((leftover, fix_str)) => {
1685 self.buf = leftover;
1686 Ok(fix_str)
1687 }
1688 Err(DeserializeErrorKindInternal::Incomplete) => Err(DeserializeErrorKind::Garbled(
1689 GarbledReason::IncompleteMessageData,
1690 )),
1691 Err(DeserializeErrorKindInternal::Error(reason)) => {
1692 Err(self.reject(self.current_tag, reason))
1693 }
1694 }
1695 }
1696
1697 /// Deserialize alphanumeric free-format strings can include any character
1698 /// except control characters.
1699 #[inline(always)]
1700 pub fn deserialize_string(&mut self) -> Result<FixString, DeserializeErrorKind> {
1701 self.deserialize_str().map(FixString::from)
1702 }
1703
1704 /// Deserialize string containing one or more space-delimited multiple
1705 /// character values, e.g. `AV AN A`.
1706 pub fn deserialize_multiple_string_value(
1707 &mut self,
1708 ) -> Result<MultipleStringValue, DeserializeErrorKind> {
1709 match self.buf {
1710 [] => {
1711 return Err(DeserializeErrorKind::Garbled(
1712 GarbledReason::IncompleteMessageData,
1713 ));
1714 }
1715 [b'\x01', ..] => {
1716 return Err(self.reject(
1717 self.current_tag,
1718 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1719 ));
1720 }
1721 _ => {}
1722 }
1723
1724 let i = memchr(b'\x01', self.buf).ok_or(DeserializeErrorKind::Garbled(
1725 GarbledReason::IncompleteMessageData,
1726 ))?;
1727
1728 // SAFETY: i is from memchr on self.buf, so i < self.buf.len(),
1729 // thus i + 1 <= self.buf.len()
1730 let (data, rest) = unsafe { self.buf.split_at_unchecked(i) };
1731 // SAFETY: rest is self.buf[i..] and i < self.buf.len(), so rest still
1732 // holds the separator memchr found - rest.len() >= 1
1733 let (_, rest) = unsafe { rest.split_at_unchecked(1) };
1734 self.buf = rest;
1735 const DEFAULT_CAPACITY: usize = 4;
1736 let mut result = MultipleStringValue::with_capacity(DEFAULT_CAPACITY);
1737 for part in data.split(|p| *p == b' ') {
1738 let mut sub_result = Vec::with_capacity(part.len());
1739 for byte in part {
1740 match byte {
1741 // ASCII control characters range (including DEL) + unused range
1742 0x00..=0x1f | 0x7f..=0xff => {
1743 return Err(self
1744 .reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect));
1745 }
1746 n => sub_result.push(*n),
1747 }
1748 }
1749 // SAFETY: string validity checked above
1750 result.push(unsafe { FixString::from_ascii_unchecked(sub_result) });
1751 }
1752 Ok(result)
1753 }
1754
1755 /// Deserialize ISO 3166-1:2013 Codes for the representation of names of
1756 /// countries and their subdivision (2-character code).
1757 pub fn deserialize_country(&mut self) -> Result<Country, DeserializeErrorKind> {
1758 match self.buf {
1759 [] => Err(DeserializeErrorKind::Garbled(
1760 GarbledReason::IncompleteMessageData,
1761 )),
1762 [b'\x01', ..] => Err(self.reject(
1763 self.current_tag,
1764 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1765 )),
1766 [_, b'\x01', ..] => Err(self.reject(
1767 self.current_tag,
1768 SessionRejectReasonBase::IncorrectDataFormatForValue,
1769 )),
1770 bytes @ [_, _, b'\x01', buf @ ..] => {
1771 self.buf = buf;
1772 Country::from_bytes(&bytes[0..2]).ok_or_else(|| {
1773 self.reject(
1774 self.current_tag,
1775 SessionRejectReasonBase::IncorrectDataFormatForValue,
1776 )
1777 })
1778 }
1779 // TODO: add the same for [a, b] and [a] cases
1780 // TODO: and do it in every deserialize_* function without loop
1781 // TODO: or maybe better just check if len < expected message size
1782 &[a, b, c] if a != b'\x01' && b != b'\x01' && c != b'\x01' => Err(
1783 DeserializeErrorKind::Garbled(GarbledReason::MessageNotWellFormed),
1784 ),
1785 _ => Err(self.reject(
1786 self.current_tag,
1787 SessionRejectReasonBase::IncorrectDataFormatForValue,
1788 )),
1789 }
1790 }
1791
1792 /// Deserialize ISO 4217:2015 Codes for the representation of currencies
1793 /// and funds (3-character code).
1794 pub fn deserialize_currency(&mut self) -> Result<Currency, DeserializeErrorKind> {
1795 match self.buf {
1796 [] => Err(DeserializeErrorKind::Garbled(
1797 GarbledReason::IncompleteMessageData,
1798 )),
1799 [b'\x01', ..] => Err(self.reject(
1800 self.current_tag,
1801 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1802 )),
1803 bytes @ [_, _, _, b'\x01', buf @ ..] => {
1804 self.buf = buf;
1805 Currency::from_bytes(&bytes[0..3]).ok_or_else(|| {
1806 self.reject(
1807 self.current_tag,
1808 SessionRejectReasonBase::IncorrectDataFormatForValue,
1809 )
1810 })
1811 }
1812 _ => Err(self.reject(
1813 self.current_tag,
1814 SessionRejectReasonBase::IncorrectDataFormatForValue,
1815 )),
1816 }
1817 }
1818
1819 /// Deserialize ISO 10383:2012 Securities and related financial
1820 /// instruments - Codes for exchanges and market identification (MIC)
1821 /// (4-character code).
1822 pub fn deserialize_exchange(&mut self) -> Result<Exchange, DeserializeErrorKind> {
1823 match self.buf {
1824 [] => Err(DeserializeErrorKind::Garbled(
1825 GarbledReason::IncompleteMessageData,
1826 )),
1827 [b'\x01', ..] => Err(self.reject(
1828 self.current_tag,
1829 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1830 )),
1831 [a, b, c, d, b'\x01', buf @ ..] => {
1832 let exchange = Exchange::from_bytes([*a, *b, *c, *d]).map_err(|_| {
1833 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1834 })?;
1835 self.buf = buf;
1836 Ok(exchange)
1837 }
1838 _ => Err(self.reject(
1839 self.current_tag,
1840 SessionRejectReasonBase::IncorrectDataFormatForValue,
1841 )),
1842 }
1843 }
1844
1845 /// Deserialize string representing month of a year.
1846 /// An optional day of the month can be appended or an optional week code.
1847 ///
1848 /// # Valid formats:
1849 /// - `YYYYMM`
1850 /// - `YYYYMMDD`
1851 /// - `YYYYMMWW`
1852 ///
1853 /// # Valid values:
1854 /// - YYYY = 0000-9999
1855 /// - MM = 01-12
1856 /// - DD = 01-31
1857 /// - WW = w1, w2, w3, w4, w5
1858 ///
1859 /// The format is not enforced: the value is accepted as a plain string,
1860 /// and format conformance is left to the application.
1861 #[inline(always)]
1862 pub fn deserialize_month_year(&mut self) -> Result<MonthYear, DeserializeErrorKind> {
1863 self.deserialize_string()
1864 }
1865
1866 /// Deserialize ISO 639-1:2002 Codes for the representation of names
1867 /// of languages (2-character code).
1868 pub fn deserialize_language(&mut self) -> Result<Language, DeserializeErrorKind> {
1869 match self.buf {
1870 [] => Err(DeserializeErrorKind::Garbled(
1871 GarbledReason::IncompleteMessageData,
1872 )),
1873 [b'\x01', ..] => Err(self.reject(
1874 self.current_tag,
1875 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1876 )),
1877 [a, b, b'\x01', buf @ ..] => {
1878 let language = Language::from_bytes(&[*a, *b]).ok_or_else(|| {
1879 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
1880 })?;
1881 self.buf = buf;
1882 Ok(language)
1883 }
1884 _ => Err(self.reject(
1885 self.current_tag,
1886 SessionRejectReasonBase::IncorrectDataFormatForValue,
1887 )),
1888 }
1889 }
1890
1891 /// Deserialize string representing time/date combination represented
1892 /// in UTC (Universal Time Coordinated) in either YYYYMMDD-HH:MM:SS
1893 /// (whole seconds) or YYYYMMDD-HH:MM:SS.sss* format, colons, dash,
1894 /// and period required.
1895 ///
1896 /// # Valid values:
1897 /// - YYYY = 0000-9999,
1898 /// - MM = 01-12,
1899 /// - DD = 01-31,
1900 /// - HH = 00-23,
1901 /// - MM = 00-59,
1902 /// - SS = 00-60 (60 only if UTC leap second),
1903 /// - sss* fractions of seconds. The fractions of seconds may be empty when
1904 /// no fractions of seconds are conveyed (in such a case the period
1905 /// is not conveyed), it may include 3 digits to convey
1906 /// milliseconds, 6 digits to convey microseconds, 9 digits
1907 /// to convey nanoseconds, 12 digits to convey picoseconds
1908 /// (truncated to nanosecond resolution);
1909 pub fn deserialize_utc_timestamp(&mut self) -> Result<UtcTimestamp, DeserializeErrorKind> {
1910 match self.buf {
1911 [] => {
1912 return Err(DeserializeErrorKind::Garbled(
1913 GarbledReason::IncompleteMessageData,
1914 ));
1915 }
1916 [b'\x01', ..] => {
1917 return Err(self.reject(
1918 self.current_tag,
1919 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1920 ));
1921 }
1922 _ => {}
1923 }
1924
1925 match parse_utc_timestamp(self.buf) {
1926 Ok((timestamp, rest)) => self.finish_value(timestamp, rest),
1927 Err(error) => Err(self.garbled_or_reject_value(error)),
1928 }
1929 }
1930
1931 /// Deserialize string representing time-only represented in UTC
1932 /// (Universal Time Coordinated) in either HH:MM:SS (whole seconds)
1933 /// or HH:MM:SS.sss* (milliseconds) format, colons, and period required.
1934 ///
1935 /// This special-purpose field is paired with UTCDateOnly to form a proper
1936 /// UTCTimestamp for bandwidth-sensitive messages.
1937 ///
1938 /// # Valid values:
1939 /// - HH = 00-23,
1940 /// - MM = 00-59,
1941 /// - SS = 00-60 (60 only if UTC leap second),
1942 /// - sss* fractions of seconds. The fractions of seconds may be empty when
1943 /// no fractions of seconds are conveyed (in such a case the period
1944 /// is not conveyed), it may include 3 digits to convey
1945 /// milliseconds, 6 digits to convey microseconds, 9 digits
1946 /// to convey nanoseconds, 12 digits to convey picoseconds
1947 /// (truncated to nanosecond resolution);
1948 pub fn deserialize_utc_time_only(&mut self) -> Result<UtcTimeOnly, DeserializeErrorKind> {
1949 match self.buf {
1950 [] => {
1951 return Err(DeserializeErrorKind::Garbled(
1952 GarbledReason::IncompleteMessageData,
1953 ));
1954 }
1955 [b'\x01', ..] => {
1956 return Err(self.reject(
1957 self.current_tag,
1958 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1959 ));
1960 }
1961 _ => {}
1962 }
1963
1964 match parse_utc_time_only(self.buf) {
1965 Ok((time, rest)) => self.finish_value(time, rest),
1966 Err(error) => Err(self.garbled_or_reject_value(error)),
1967 }
1968 }
1969
1970 /// Deserialize date represented in UTC (Universal Time Coordinated)
1971 /// in YYYYMMDD format.
1972 ///
1973 /// # Valid values:
1974 /// - YYYY = 0000-9999,
1975 /// - MM = 01-12,
1976 /// - DD = 01-31.
1977 pub fn deserialize_utc_date_only(&mut self) -> Result<UtcDateOnly, DeserializeErrorKind> {
1978 match self.buf {
1979 [] => Err(DeserializeErrorKind::Garbled(
1980 GarbledReason::IncompleteMessageData,
1981 )),
1982 [b'\x01', ..] => Err(self.reject(
1983 self.current_tag,
1984 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
1985 )),
1986 // Missing separator at the end
1987 [_] => Err(DeserializeErrorKind::Garbled(
1988 GarbledReason::IncompleteMessageData,
1989 )),
1990 [
1991 // Year
1992 y3 @ b'0'..=b'9',
1993 y2 @ b'0'..=b'9',
1994 y1 @ b'0'..=b'9',
1995 y0 @ b'0'..=b'9',
1996 // Month
1997 m1 @ b'0'..=b'1',
1998 m0 @ b'0'..=b'9',
1999 // Day
2000 d1 @ b'0'..=b'3',
2001 d0 @ b'0'..=b'9',
2002 // Separator
2003 b'\x01',
2004 rest @ ..,
2005 ] => {
2006 let year = (y3 - b'0') as u16 * 1000
2007 + (y2 - b'0') as u16 * 100
2008 + (y1 - b'0') as u16 * 10
2009 + (y0 - b'0') as u16;
2010 let month = (m1 - b'0') * 10 + (m0 - b'0');
2011 let day = (d1 - b'0') * 10 + (d0 - b'0');
2012 self.buf = rest;
2013 UtcDateOnly::from_ymd_opt(year.into(), month.into(), day.into()).ok_or_else(|| {
2014 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
2015 })
2016 }
2017 _ => Err(self.reject(
2018 self.current_tag,
2019 SessionRejectReasonBase::IncorrectDataFormatForValue,
2020 )),
2021 }
2022 }
2023
2024 /// Deserialize time local to a market center. Used where offset to UTC
2025 /// varies throughout the year and the defining market center is identified
2026 /// in a corresponding field.
2027 ///
2028 /// Format is HH:MM:SS where:
2029 /// - HH = 00-23 hours,
2030 /// - MM = 00-59 minutes,
2031 /// - SS = 00-59 seconds.
2032 ///
2033 /// In general only the hour token is non-zero.
2034 pub fn deserialize_local_mkt_time(&mut self) -> Result<LocalMktTime, DeserializeErrorKind> {
2035 match self.buf {
2036 [] => Err(DeserializeErrorKind::Garbled(
2037 GarbledReason::IncompleteMessageData,
2038 )),
2039 [b'\x01', ..] => Err(self.reject(
2040 self.current_tag,
2041 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
2042 )),
2043 // Missing separator at the end
2044 [_] => Err(DeserializeErrorKind::Garbled(
2045 GarbledReason::IncompleteMessageData,
2046 )),
2047
2048 [
2049 // Hour
2050 h1 @ b'0'..=b'2',
2051 h0 @ b'0'..=b'9',
2052 b':',
2053 // Minute
2054 m1 @ b'0'..=b'5',
2055 m0 @ b'0'..=b'9',
2056 b':',
2057 // Second
2058 s1 @ b'0'..=b'5',
2059 s0 @ b'0'..=b'9',
2060 b'\x01',
2061 rest @ ..,
2062 ] => {
2063 let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
2064 let minute = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
2065 let second = (s1 - b'0') as u32 * 10 + (s0 - b'0') as u32;
2066 self.buf = rest;
2067 LocalMktTime::from_hms_opt(hour, minute, second).ok_or_else(|| {
2068 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
2069 })
2070 }
2071 _ => Err(self.reject(
2072 self.current_tag,
2073 SessionRejectReasonBase::IncorrectDataFormatForValue,
2074 )),
2075 }
2076 }
2077
2078 /// Deserialize date of local market (as opposed to UTC) in YYYYMMDD
2079 /// format.
2080 ///
2081 /// # Valid values:
2082 /// - YYYY = 0000-9999,
2083 /// - MM = 01-12,
2084 /// - DD = 01-31.
2085 pub fn deserialize_local_mkt_date(&mut self) -> Result<LocalMktDate, DeserializeErrorKind> {
2086 match self.buf {
2087 [] => Err(DeserializeErrorKind::Garbled(
2088 GarbledReason::IncompleteMessageData,
2089 )),
2090 [b'\x01', ..] => Err(self.reject(
2091 self.current_tag,
2092 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
2093 )),
2094 // Missing separator at the end
2095 [_] => Err(DeserializeErrorKind::Garbled(
2096 GarbledReason::IncompleteMessageData,
2097 )),
2098 [
2099 // Year
2100 y3 @ b'0'..=b'9',
2101 y2 @ b'0'..=b'9',
2102 y1 @ b'0'..=b'9',
2103 y0 @ b'0'..=b'9',
2104 // Month
2105 m1 @ b'0'..=b'1',
2106 m0 @ b'0'..=b'9',
2107 // Day
2108 d1 @ b'0'..=b'3',
2109 d0 @ b'0'..=b'9',
2110 // Separator
2111 b'\x01',
2112 rest @ ..,
2113 ] => {
2114 let year = (y3 - b'0') as u16 * 1000
2115 + (y2 - b'0') as u16 * 100
2116 + (y1 - b'0') as u16 * 10
2117 + (y0 - b'0') as u16;
2118 let month = (m1 - b'0') * 10 + (m0 - b'0');
2119 let day = (d1 - b'0') * 10 + (d0 - b'0');
2120 self.buf = rest;
2121 LocalMktDate::from_ymd_opt(year.into(), month.into(), day.into()).ok_or_else(|| {
2122 self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
2123 })
2124 }
2125 _ => Err(self.reject(
2126 self.current_tag,
2127 SessionRejectReasonBase::IncorrectDataFormatForValue,
2128 )),
2129 }
2130 }
2131
2132 /// Deserialize string representing a time/date combination representing
2133 /// local time with an offset to UTC to allow identification of local time
2134 /// and time zone offset of that time.
2135 ///
2136 /// The representation is based on ISO 8601.
2137 ///
2138 /// Format is `YYYYMMDD-HH:MM[:SS][.sss*][Z | [ + | - hh[:mm]]]` where:
2139 /// - YYYY = 0000 to 9999,
2140 /// - MM = 01-12,
2141 /// - DD = 01-31,
2142 /// - HH = 00-23 hours,
2143 /// - MM = 00-59 minutes,
2144 /// - SS = 00-59 seconds, optional on input (the spec's own examples omit
2145 /// them) and taken as `00` when absent,
2146 /// - hh = 01-12 offset hours,
2147 /// - mm = 00-59 offset minutes,
2148 /// - sss* fractions of seconds. The fractions of seconds may be empty when
2149 /// no fractions of seconds are conveyed (in such a case the period
2150 /// is not conveyed), it may include 3 digits to convey
2151 /// milliseconds, 6 digits to convey microseconds, 9 digits
2152 /// to convey nanoseconds, 12 digits to convey picoseconds
2153 /// (truncated to nanosecond resolution);
2154 pub fn deserialize_tz_timestamp(&mut self) -> Result<TzTimestamp, DeserializeErrorKind> {
2155 match self.buf {
2156 [] => {
2157 return Err(DeserializeErrorKind::Garbled(
2158 GarbledReason::IncompleteMessageData,
2159 ));
2160 }
2161 [b'\x01', ..] => {
2162 return Err(self.reject(
2163 self.current_tag,
2164 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
2165 ));
2166 }
2167 _ => {}
2168 }
2169
2170 match parse_tz_timestamp(self.buf) {
2171 Ok((timestamp, rest)) => self.finish_value(timestamp, rest),
2172 Err(error) => Err(self.garbled_or_reject_value(error)),
2173 }
2174 }
2175
2176 /// Deserialize time of day with timezone. Time represented based on
2177 /// ISO 8601. This is the time with a UTC offset to allow identification of
2178 /// local time and time zone of that time.
2179 ///
2180 /// Format is `HH:MM[:SS][Z | [ + | - hh[:mm]]]` where:
2181 /// - HH = 00-23 hours,
2182 /// - MM = 00-59 minutes,
2183 /// - SS = 00-59 seconds,
2184 /// - hh = 01-12 offset hours,
2185 /// - mm = 00-59 offset minutes.
2186 pub fn deserialize_tz_timeonly(&mut self) -> Result<TzTimeOnly, DeserializeErrorKind> {
2187 match self.buf {
2188 [] => {
2189 return Err(DeserializeErrorKind::Garbled(
2190 GarbledReason::IncompleteMessageData,
2191 ));
2192 }
2193 [b'\x01', ..] => {
2194 return Err(self.reject(
2195 self.current_tag,
2196 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
2197 ));
2198 }
2199 _ => {}
2200 }
2201
2202 match parse_tz_time_only(self.buf) {
2203 Ok((time, rest)) => self.finish_value(time, rest),
2204 Err(error) => Err(self.garbled_or_reject_value(error)),
2205 }
2206 }
2207
2208 /// Deserialize sequence of character digits without commas or decimals.
2209 /// Value must be positive. Fields of datatype Length are referred to as
2210 /// Length fields.
2211 ///
2212 /// The Length field must be associated with a field of datatype data.
2213 ///
2214 /// The Length field must specify the number of octets of the value
2215 /// contained in the associated data field up to but not including
2216 /// the terminating `<SOH>`.
2217 pub fn deserialize_length(&mut self) -> Result<Length, DeserializeErrorKind> {
2218 match deserialize_length(self.buf) {
2219 Ok((leftover, len)) => {
2220 self.buf = leftover;
2221 Ok(len)
2222 }
2223 Err(DeserializeErrorKindInternal::Incomplete) => Err(DeserializeErrorKind::Garbled(
2224 GarbledReason::IncompleteMessageData,
2225 )),
2226 Err(DeserializeErrorKindInternal::Error(reject)) => {
2227 Err(self.reject(self.current_tag, reject))
2228 }
2229 }
2230 }
2231
2232 /// Deserialize raw data with no format or content restrictions,
2233 /// or a character string encoded as specified by MessageEncoding(347).
2234 /// Fields of datatype data must have an associated field of type Length.
2235 /// Fields of datatype data must be immediately preceded by their
2236 /// associated Length field.
2237 pub fn deserialize_data(&mut self, len: usize) -> Result<Data, DeserializeErrorKind> {
2238 // Data length + separator (SOH). Phrased as `len >= self.buf.len()`
2239 // and not as `self.buf.len() < len + 1`: the latter wraps for
2240 // `len == usize::MAX` and waves the unchecked accesses below through.
2241 // An empty buffer needs no separate guard - it fails this one for
2242 // every `len`, with the same error.
2243 if len >= self.buf.len() {
2244 return Err(DeserializeErrorKind::Garbled(
2245 GarbledReason::IncompleteMessageData,
2246 ));
2247 }
2248
2249 // SAFETY: guard above ensures len < self.buf.len(), so index len is valid
2250 if unsafe { *self.buf.get_unchecked(len) } != b'\x01' {
2251 return Err(DeserializeErrorKind::Garbled(
2252 GarbledReason::MessageNotWellFormed,
2253 ));
2254 }
2255
2256 // SAFETY: guard ensures len < self.buf.len()
2257 let (data, rest) = unsafe { self.buf.split_at_unchecked(len) };
2258 // SAFETY: rest is self.buf[len..] and len < self.buf.len(), so rest
2259 // still holds the separator checked above - rest.len() >= 1
2260 let (_, rest) = unsafe { rest.split_at_unchecked(1) };
2261 self.buf = rest;
2262 Ok(data.into())
2263 }
2264
2265 /// Deserialize XML document with characterstring repertoire specified
2266 /// as value of XML encoding declaration.
2267 ///
2268 /// # Requirements
2269 /// - A field of datatype XMLData must contain a well-formed document,
2270 /// as defined by the W3C XML recommendation.
2271 /// - Fields of datatype XMLData must have an associated field of type
2272 /// Length.
2273 /// - Fields of datatype XMLData must be immediately preceded by their
2274 /// associated Length field.
2275 pub fn deserialize_xml(&mut self, len: usize) -> Result<XmlData, DeserializeErrorKind> {
2276 match self.buf {
2277 [] => {
2278 return Err(DeserializeErrorKind::Garbled(
2279 GarbledReason::IncompleteMessageData,
2280 ));
2281 }
2282 [b'\x01', ..] => {
2283 return Err(self.reject(
2284 self.current_tag,
2285 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
2286 ));
2287 }
2288 _ => {}
2289 }
2290
2291 // XML length + separator (SOH). Phrased as `len >= self.buf.len()` and
2292 // not as `self.buf.len() < len + 1`: the latter wraps for
2293 // `len == usize::MAX` and waves the unchecked accesses below through.
2294 if len >= self.buf.len() {
2295 return Err(DeserializeErrorKind::Garbled(
2296 GarbledReason::IncompleteMessageData,
2297 ));
2298 }
2299
2300 // SAFETY: guard above ensures len < self.buf.len(), so index len is valid
2301 if unsafe { *self.buf.get_unchecked(len) } != b'\x01' {
2302 return Err(DeserializeErrorKind::Garbled(
2303 GarbledReason::MessageNotWellFormed,
2304 ));
2305 }
2306
2307 // TODO: XML validation, SessionRejectReasonBase::XmlValidationError when invalid
2308 // SAFETY: guard ensures len < self.buf.len()
2309 let (xml, rest) = unsafe { self.buf.split_at_unchecked(len) };
2310 // SAFETY: rest is self.buf[len..] and len < self.buf.len(), so rest
2311 // still holds the separator checked above - rest.len() >= 1
2312 let (_, rest) = unsafe { rest.split_at_unchecked(1) };
2313 self.buf = rest;
2314 Ok(xml.into())
2315 }
2316
2317 /// Deserialize a tenor: a unit code (`D`, `M`, `W` or `Y`) followed by
2318 /// a non-zero value, e.g. `M3` for three months.
2319 pub fn deserialize_tenor(&mut self) -> Result<Tenor, DeserializeErrorKind> {
2320 match self.buf {
2321 [] => {
2322 return Err(DeserializeErrorKind::Garbled(
2323 GarbledReason::IncompleteMessageData,
2324 ));
2325 }
2326 [b'\x01', ..] => {
2327 return Err(self.reject(
2328 self.current_tag,
2329 SessionRejectReasonBase::TagSpecifiedWithoutAValue,
2330 ));
2331 }
2332 _ => {}
2333 }
2334
2335 match parse_tenor(self.buf) {
2336 Ok((tenor, rest)) => self.finish_value(tenor, rest),
2337 Err(error) => Err(self.garbled_or_reject_value(error)),
2338 }
2339 }
2340
2341 /// Deserialize an `Int` and convert it into the enum `T`.
2342 ///
2343 /// A value outside `T`'s variants is a `Reject` carrying the reason
2344 /// `T` chose, blamed on the tag currently being read.
2345 pub fn deserialize_int_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
2346 where
2347 T: TryFrom<Int, Error = SessionRejectReasonBase>,
2348 {
2349 T::try_from(self.deserialize_int()?).map_err(|reason| self.reject(self.current_tag, reason))
2350 }
2351
2352 /// Deserialize a `NumInGroup` and convert it into the enum `T`, with the
2353 /// same reject behavior as
2354 /// [`deserialize_int_enum`](Self::deserialize_int_enum).
2355 pub fn deserialize_num_in_group_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
2356 where
2357 T: TryFrom<NumInGroup, Error = SessionRejectReasonBase>,
2358 {
2359 T::try_from(self.deserialize_num_in_group()?)
2360 .map_err(|reason| self.reject(self.current_tag, reason))
2361 }
2362
2363 /// Deserialize a `Char` and convert it into the enum `T`, with the same
2364 /// reject behavior as
2365 /// [`deserialize_int_enum`](Self::deserialize_int_enum).
2366 pub fn deserialize_char_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
2367 where
2368 T: TryFrom<Char, Error = SessionRejectReasonBase>,
2369 {
2370 let value = self.deserialize_char()?;
2371 T::try_from(value).map_err(|reason| self.reject(self.current_tag, reason))
2372 }
2373
2374 /// Deserialize a `FixStr` and convert it into the enum `T`, with the same
2375 /// reject behavior as
2376 /// [`deserialize_int_enum`](Self::deserialize_int_enum).
2377 pub fn deserialize_string_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
2378 where
2379 for<'a> T: TryFrom<&'a FixStr, Error = SessionRejectReasonBase>,
2380 {
2381 let value = self.deserialize_str()?;
2382 T::try_from(value).map_err(|reason| self.reject(self.current_tag, reason))
2383 }
2384
2385 /// Deserialize a space-delimited `MultipleCharValue` and convert every
2386 /// element into the enum `T`. The first element outside `T`'s variants
2387 /// rejects the whole field.
2388 pub fn deserialize_multiple_char_value_enum<T>(
2389 &mut self,
2390 ) -> Result<Vec<T>, DeserializeErrorKind>
2391 where
2392 T: TryFrom<Char, Error = SessionRejectReasonBase>,
2393 {
2394 let values = self.deserialize_multiple_char_value()?;
2395 let mut result = Vec::with_capacity(values.len());
2396 for value in values {
2397 result
2398 .push(T::try_from(value).map_err(|reason| self.reject(self.current_tag, reason))?);
2399 }
2400 Ok(result)
2401 }
2402
2403 /// Deserialize a space-delimited `MultipleStringValue` and convert every
2404 /// element into the enum `T`. The first element outside `T`'s variants
2405 /// rejects the whole field.
2406 pub fn deserialize_multiple_string_value_enum<T>(
2407 &mut self,
2408 ) -> Result<Vec<T>, DeserializeErrorKind>
2409 where
2410 for<'a> T: TryFrom<&'a FixStr, Error = SessionRejectReasonBase>,
2411 {
2412 let values = self.deserialize_multiple_string_value()?;
2413 let mut result = Vec::with_capacity(values.len());
2414 for value in values {
2415 result
2416 .push(T::try_from(&value).map_err(|reason| self.reject(self.current_tag, reason))?);
2417 }
2418 Ok(result)
2419 }
2420}