use std::{error::Error as StdError, fmt, ops, sync::LazyLock};
use memchr::{memchr, memmem};
use crate::{
base_messages::SessionRejectReasonBase,
basic_types::{
Amt, Boolean, Char, Country, Currency, Data, DayOfMonth, Decimal, Exchange, FixStr,
FixString, FixedOffset, Float, Int, Language, Length, LocalMktDate, LocalMktTime,
MonthYear, MultipleCharValue, MultipleStringValue, NaiveDate, NaiveTime, NumInGroup,
Percentage, Price, PriceOffset, Qty, SeqNum, SessionRejectReasonField, TagNum, Tenor,
TenorUnit, TenorValue, TimePrecision, TimeZone, TzTimeOnly, TzTimestamp, Utc, UtcDateOnly,
UtcTimeOnly, UtcTimestamp, XmlData,
},
version::Version,
};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GarbledReason {
IncompleteMessageData,
MessageNotWellFormed,
InvalidChecksum,
InvalidBeginString,
MsgTypeNotThirdTag,
}
impl fmt::Display for GarbledReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GarbledReason::IncompleteMessageData => f.write_str("incomplete message data"),
GarbledReason::MessageNotWellFormed => f.write_str("message not well formed"),
GarbledReason::InvalidChecksum => f.write_str("invalid checksum"),
GarbledReason::InvalidBeginString => f.write_str("invalid BeginString<8>"),
GarbledReason::MsgTypeNotThirdTag => f.write_str("MsgType<35> not third tag"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogoutReason {
MsgSeqNumMissing,
BeginStringMismatch,
}
impl fmt::Display for LogoutReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LogoutReason::MsgSeqNumMissing => f.write_str("MsgSeqNum<34> missing"),
LogoutReason::BeginStringMismatch => f.write_str("invalid BeginString<8>"),
}
}
}
#[derive(Debug)]
pub enum DeserializeErrorKind {
Garbled(GarbledReason),
Logout(LogoutReason),
Reject {
msg_type: Option<FixString>,
seq_num: SeqNum,
tag: Option<TagNum>,
reason: SessionRejectReasonField,
},
}
impl fmt::Display for DeserializeErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DeserializeErrorKind::Garbled(reason) => write!(f, "garbled message: {reason}"),
DeserializeErrorKind::Logout(reason) => write!(f, "logout: {reason}"),
DeserializeErrorKind::Reject {
tag: Some(tag),
reason,
..
} => write!(f, "{reason} (tag={tag})"),
DeserializeErrorKind::Reject {
tag: None, reason, ..
} => write!(f, "{reason}"),
}
}
}
impl StdError for DeserializeErrorKind {}
impl From<RawMessageError> for DeserializeErrorKind {
fn from(error: RawMessageError) -> Self {
match error {
RawMessageError::Incomplete => {
DeserializeErrorKind::Garbled(GarbledReason::IncompleteMessageData)
}
RawMessageError::Garbled => {
DeserializeErrorKind::Garbled(GarbledReason::MessageNotWellFormed)
}
RawMessageError::InvalidChecksum { .. } => {
DeserializeErrorKind::Garbled(GarbledReason::InvalidChecksum)
}
}
}
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum DeserializeErrorKindInternal {
#[error("Incomplete")]
Incomplete,
#[error("{0:?}")]
Error(SessionRejectReasonBase),
}
fn deserialize_tag<'a>(bytes: &'a [u8], tag: &'a [u8]) -> Result<&'a [u8], RawMessageError> {
if bytes.len() < tag.len() {
Err(RawMessageError::Incomplete)
} else if bytes.starts_with(tag) {
Ok(&bytes[tag.len()..])
} else {
Err(RawMessageError::Garbled)
}
}
fn deserialize_checksum(bytes: &[u8]) -> Result<(&[u8], u16), RawMessageError> {
if bytes.len() < 4 {
return Err(RawMessageError::Incomplete);
}
let mut value: u16 = 0;
for b in &bytes[0..3] {
match b {
n @ b'0'..=b'9' => value = value * 10 + u16::from(n - b'0'),
_ => return Err(RawMessageError::Garbled),
}
}
if bytes[3] != b'\x01' {
return Err(RawMessageError::Garbled);
}
Ok((&bytes[4..], value))
}
const MAX_FRACTION_DIGITS: usize = 12;
fn parse_timestamp_head(
buf: &[u8],
) -> Result<(NaiveDate, u32, u32, &[u8]), DeserializeErrorKindInternal> {
let [
y3 @ b'0'..=b'9',
y2 @ b'0'..=b'9',
y1 @ b'0'..=b'9',
y0 @ b'0'..=b'9',
m1 @ b'0'..=b'1',
m0 @ b'0'..=b'9',
d1 @ b'0'..=b'3',
d0 @ b'0'..=b'9',
b'-',
h1 @ b'0'..=b'2',
h0 @ b'0'..=b'9',
b':',
mm1 @ b'0'..=b'5',
mm0 @ b'0'..=b'9',
rest @ ..,
] = buf
else {
return if buf.len() < 14 {
Err(DeserializeErrorKindInternal::Incomplete)
} else {
Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
))
};
};
let year = (y3 - b'0') as i32 * 1000
+ (y2 - b'0') as i32 * 100
+ (y1 - b'0') as i32 * 10
+ (y0 - b'0') as i32;
let month = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
let day = (d1 - b'0') as u32 * 10 + (d0 - b'0') as u32;
let naive_date = NaiveDate::from_ymd_opt(year, month, day).ok_or(
DeserializeErrorKindInternal::Error(SessionRejectReasonBase::ValueIsIncorrect),
)?;
let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
let min = (mm1 - b'0') as u32 * 10 + (mm0 - b'0') as u32;
Ok((naive_date, hour, min, rest))
}
fn parse_utc_seconds(buf: &[u8]) -> Result<(u32, u32, &[u8]), DeserializeErrorKindInternal> {
match buf {
[s1 @ b'0'..=b'5', s0 @ b'0'..=b'9', rest @ ..] => {
Ok(((s1 - b'0') as u32 * 10 + (s0 - b'0') as u32, 0, rest))
}
[b'6', b'0', rest @ ..] => Ok((59, 1_000_000_000, rest)),
_ if buf.len() < 2 => Err(DeserializeErrorKindInternal::Incomplete),
_ => Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "the accumulator is reduced to nanoseconds below, so it is at most 999_999_999"
)]
fn parse_fraction_of_second(
buf: &[u8],
) -> Result<(u32, TimePrecision, &[u8]), DeserializeErrorKindInternal> {
let [b'.', digits @ ..] = buf else {
return Ok((0, TimePrecision::Secs, buf));
};
let mut fraction_of_second: u64 = 0;
let mut count: usize = 0;
for &byte in digits {
match byte {
b'0'..=b'9' if count == MAX_FRACTION_DIGITS => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
n @ b'0'..=b'9' => {
fraction_of_second = fraction_of_second * 10 + u64::from(n - b'0');
count += 1;
}
_ => break,
}
}
let rest = &digits[count..];
let (nanos, precision) = match count {
3 => (fraction_of_second * 1_000_000, TimePrecision::Millis),
6 => (fraction_of_second * 1_000, TimePrecision::Micros),
9 => (fraction_of_second, TimePrecision::Nanos),
12 => (fraction_of_second / 1_000, TimePrecision::Nanos),
_ if rest.is_empty() => return Err(DeserializeErrorKindInternal::Incomplete),
_ => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
};
Ok((nanos as u32, precision, rest))
}
pub(crate) fn parse_utc_timestamp(
buf: &[u8],
) -> Result<(UtcTimestamp, &[u8]), DeserializeErrorKindInternal> {
let (naive_date, hour, min, rest) = parse_timestamp_head(buf)?;
let rest = match rest {
[b':', rest @ ..] => rest,
[] => return Err(DeserializeErrorKindInternal::Incomplete),
_ => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
};
let (sec, leap_offset, rest) = parse_utc_seconds(rest)?;
let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
let naive_date_time = naive_date
.and_hms_nano_opt(hour, min, sec, leap_offset + fraction_of_second)
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
let timestamp = Utc.from_utc_datetime(&naive_date_time);
Ok((UtcTimestamp::with_precision(timestamp, precision), rest))
}
pub(crate) fn parse_utc_time_only(
buf: &[u8],
) -> Result<(UtcTimeOnly, &[u8]), DeserializeErrorKindInternal> {
let [
h1 @ b'0'..=b'2',
h0 @ b'0'..=b'9',
b':',
m1 @ b'0'..=b'5',
m0 @ b'0'..=b'9',
b':',
rest @ ..,
] = buf
else {
return if buf.len() < 6 {
Err(DeserializeErrorKindInternal::Incomplete)
} else {
Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
))
};
};
let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
let min = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
let (sec, leap_offset, rest) = parse_utc_seconds(rest)?;
let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
let time = NaiveTime::from_hms_nano_opt(hour, min, sec, leap_offset + fraction_of_second)
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
Ok((UtcTimeOnly::with_precision(time, precision), rest))
}
fn parse_tz_offset(buf: &[u8]) -> Result<(FixedOffset, &[u8]), DeserializeErrorKindInternal> {
let (total_secs, rest) = match buf {
[b'Z', rest @ ..] => (0, rest),
[
sign @ (b'+' | b'-'),
h1 @ b'0'..=b'9',
h0 @ b'0'..=b'9',
b':',
m1 @ b'0'..=b'5',
m0 @ b'0'..=b'9',
rest @ ..,
] => {
let hours = (h1 - b'0') as i32 * 10 + (h0 - b'0') as i32;
let minutes = (m1 - b'0') as i32 * 10 + (m0 - b'0') as i32;
let total_secs = hours * 3600 + minutes * 60;
(
if *sign == b'-' {
-total_secs
} else {
total_secs
},
rest,
)
}
[
sign @ (b'+' | b'-'),
h1 @ b'0'..=b'9',
h0 @ b'0'..=b'9',
rest @ ..,
] => {
let total_secs = ((h1 - b'0') as i32 * 10 + (h0 - b'0') as i32) * 3600;
(
if *sign == b'-' {
-total_secs
} else {
total_secs
},
rest,
)
}
[] => return Err(DeserializeErrorKindInternal::Incomplete),
_ => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
};
let offset = FixedOffset::east_opt(total_secs).ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
Ok((offset, rest))
}
pub(crate) fn parse_tz_timestamp(
buf: &[u8],
) -> Result<(TzTimestamp, &[u8]), DeserializeErrorKindInternal> {
let (naive_date, hour, min, rest) = parse_timestamp_head(buf)?;
let (sec, rest) = match rest {
[b':', s1 @ b'0'..=b'5', s0 @ b'0'..=b'9', rest @ ..] => {
((s1 - b'0') as u32 * 10 + (s0 - b'0') as u32, rest)
}
_ => (0, rest),
};
let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
let (offset, rest) = parse_tz_offset(rest)?;
let naive_date_time = naive_date
.and_hms_nano_opt(hour, min, sec, fraction_of_second)
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
let timestamp = offset
.from_local_datetime(&naive_date_time)
.single()
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
Ok((TzTimestamp::with_precision(timestamp, precision), rest))
}
pub(crate) fn parse_tz_time_only(
buf: &[u8],
) -> Result<(TzTimeOnly, &[u8]), DeserializeErrorKindInternal> {
let [
h1 @ b'0'..=b'2',
h0 @ b'0'..=b'9',
b':',
m1 @ b'0'..=b'5',
m0 @ b'0'..=b'9',
rest @ ..,
] = buf
else {
return if buf.len() < 5 {
Err(DeserializeErrorKindInternal::Incomplete)
} else {
Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
))
};
};
let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
let min = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
let (sec, rest) = match rest {
[b':', s1 @ b'0'..=b'5', s0 @ b'0'..=b'9', rest @ ..] => {
((s1 - b'0') as u32 * 10 + (s0 - b'0') as u32, rest)
}
_ => (0, rest),
};
let (fraction_of_second, precision, rest) = parse_fraction_of_second(rest)?;
let (offset, rest) = parse_tz_offset(rest)?;
let time = NaiveTime::from_hms_nano_opt(hour, min, sec, fraction_of_second).ok_or(
DeserializeErrorKindInternal::Error(SessionRejectReasonBase::ValueIsIncorrect),
)?;
Ok((TzTimeOnly::new(time, offset, precision), rest))
}
pub(crate) fn parse_tenor(buf: &[u8]) -> Result<(Tenor, &[u8]), DeserializeErrorKindInternal> {
let [unit, rest @ ..] = buf else {
return Err(DeserializeErrorKindInternal::Incomplete);
};
let unit = TenorUnit::from_byte(*unit).ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
))?;
let mut value: u16 = 0;
let mut digits = 0;
let mut rest = rest;
while let [d @ b'0'..=b'9', tail @ ..] = rest {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add(u16::from(d - b'0')))
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
digits += 1;
rest = tail;
}
let Some(value) = TenorValue::new(value) else {
return if rest.is_empty() {
Err(DeserializeErrorKindInternal::Incomplete)
} else if digits == 0 {
Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
))
} else {
Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))
};
};
Ok((Tenor { unit, value }, rest))
}
fn deserialize_str(bytes: &[u8]) -> Result<(&[u8], &FixStr), DeserializeErrorKindInternal> {
for (i, b) in bytes.iter().enumerate() {
match b {
0x00 | 0x02..=0x1f | 0x7f..=0xff => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
));
}
b'\x01' => {
if i == 0 {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
} else {
return Ok((&bytes[i + 1..], unsafe {
FixStr::from_ascii_unchecked(&bytes[..i])
}));
}
}
_ => {}
}
}
Err(DeserializeErrorKindInternal::Incomplete)
}
fn deserialize_tag_num(bytes: &[u8]) -> Result<(&[u8], TagNum), DeserializeErrorKindInternal> {
if matches!(bytes, [b'0' | b'=', ..]) {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::InvalidTagNumber,
));
}
let mut value: TagNum = 0;
for (i, &byte) in bytes.iter().enumerate() {
match byte {
n @ b'0'..=b'9' => {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add(TagNum::from(n - b'0')))
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::InvalidTagNumber,
))?;
}
b'=' => return Ok((&bytes[i + 1..], value)),
_ => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::InvalidTagNumber,
));
}
}
}
Err(DeserializeErrorKindInternal::Incomplete)
}
fn deserialize_length(bytes: &[u8]) -> Result<(&[u8], Length), DeserializeErrorKindInternal> {
let mut value: Length = 0;
for (i, b) in bytes.iter().enumerate() {
match b {
n @ b'0'..=b'9' => {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add(Length::from(n - b'0')))
.ok_or(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
))?;
}
b'\x01' => {
if i == 0 {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
} else if value == 0 {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::ValueIsIncorrect,
));
} else {
return Ok((&bytes[i + 1..], value));
}
}
_ => {
return Err(DeserializeErrorKindInternal::Error(
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
}
}
Err(DeserializeErrorKindInternal::Incomplete)
}
#[derive(Debug)]
pub struct RawMessage<'a> {
pub begin_string: &'a FixStr,
pub body: &'a [u8],
pub checksum: u8,
}
#[derive(Debug, thiserror::Error)]
pub enum RawMessageError {
#[error("Incomplete")]
Incomplete,
#[error("Garbled")]
Garbled,
#[error("Invalid checksum")]
InvalidChecksum {
frame_len: usize,
},
}
impl From<DeserializeErrorKindInternal> for RawMessageError {
fn from(d: DeserializeErrorKindInternal) -> RawMessageError {
match d {
DeserializeErrorKindInternal::Incomplete => RawMessageError::Incomplete,
DeserializeErrorKindInternal::Error(_) => RawMessageError::Garbled,
}
}
}
pub fn raw_message(bytes: &[u8]) -> Result<(&[u8], RawMessage<'_>), RawMessageError> {
let orig_bytes = bytes;
let (bytes, begin_string, body_length) = frame_prefix(bytes)?;
const CHECKSUM_LEN: usize = 4;
if bytes.len() < body_length + CHECKSUM_LEN {
return Err(RawMessageError::Incomplete);
}
let body = &bytes[..body_length];
let bytes = &bytes[body_length..];
let calculated_checksum = orig_bytes[0..orig_bytes.len() - bytes.len()]
.iter()
.fold(0, |acc: u8, x| acc.wrapping_add(*x));
let bytes = deserialize_tag(bytes, b"10=")?;
let (bytes, checksum) = deserialize_checksum(bytes)?;
if u16::from(calculated_checksum) != checksum {
return Err(RawMessageError::InvalidChecksum {
frame_len: orig_bytes.len() - bytes.len(),
});
}
Ok((
bytes,
RawMessage {
begin_string,
body,
checksum: calculated_checksum,
},
))
}
fn frame_prefix(bytes: &[u8]) -> Result<(&[u8], &FixStr, usize), RawMessageError> {
let bytes = deserialize_tag(bytes, b"8=")?;
let (bytes, begin_string) = match deserialize_str(bytes) {
Err(DeserializeErrorKindInternal::Incomplete)
if bytes.len() > Version::MAX_BEGIN_STRING_LEN =>
{
return Err(RawMessageError::Garbled);
}
result => result?,
};
let bytes = deserialize_tag(bytes, b"9=")?;
let (bytes, body_length) = deserialize_length(bytes)?;
Ok((bytes, begin_string, usize::from(body_length)))
}
const TRAILER_LEN: usize = 7;
pub fn frame_len(bytes: &[u8]) -> Result<usize, RawMessageError> {
let (rest, _, body_length) = frame_prefix(bytes)?;
Ok(bytes.len() - rest.len() + body_length + TRAILER_LEN)
}
#[derive(Debug, Clone, Copy)]
pub struct FieldCursor<'de> {
buf: &'de [u8],
tmp_tag: Option<TagNum>,
}
impl<'de> FieldCursor<'de> {
pub fn next_tag(&mut self) -> Option<TagNum> {
if let Some(tag) = self.tmp_tag.take() {
return Some(tag);
}
let (rest, tag) = deserialize_tag_num(self.buf).ok()?;
self.buf = rest;
Some(tag)
}
pub fn read_delimited(&mut self) -> Option<&'de [u8]> {
let end = memchr(b'\x01', self.buf)?;
let value = &self.buf[..end];
self.buf = &self.buf[end + 1..];
Some(value)
}
pub fn read_length(&mut self) -> Option<Length> {
let (rest, length) = deserialize_length(self.buf).ok()?;
self.buf = rest;
Some(length)
}
pub fn read_data(&mut self, len: Length) -> Option<&'de [u8]> {
let len = usize::from(len);
let rest = self.buf.get(len..)?.strip_prefix(b"\x01")?;
let value = &self.buf[..len];
self.buf = rest;
Some(value)
}
}
#[derive(Debug)]
pub struct Deserializer<'de> {
raw_message: RawMessage<'de>,
buf: &'de [u8],
msg_type: Option<ops::Range<usize>>,
seq_num: Option<SeqNum>,
current_tag: Option<TagNum>,
tmp_tag: Option<TagNum>,
}
impl<'de> Deserializer<'de> {
pub fn from_raw_message(raw_message: RawMessage) -> Deserializer {
let buf = raw_message.body;
Deserializer {
raw_message,
buf,
msg_type: None,
seq_num: None,
current_tag: None,
tmp_tag: None,
}
}
pub fn begin_string(&self) -> FixString {
self.raw_message.begin_string.to_owned()
}
#[expect(
clippy::cast_possible_truncation,
reason = "`raw_message` cuts the body to a `Length`-typed BodyLength(9), so it never exceeds `Length::MAX`"
)]
pub fn body_length(&self) -> Length {
self.raw_message.body.len() as Length
}
pub fn check_sum(&self) -> FixString {
FixString::from_ascii_lossy(format!("{:03}", self.raw_message.checksum).into_bytes())
}
pub fn set_seq_num(&mut self, seq_num: SeqNum) {
debug_assert!(self.seq_num.is_none());
self.seq_num = Some(seq_num);
}
fn try_find_msg_seq_num(&mut self) -> Result<SeqNum, DeserializeErrorKind> {
static FINDER: LazyLock<memmem::Finder<'static>> =
LazyLock::new(|| memmem::Finder::new(b"34="));
let start_index = FINDER
.find(self.buf)
.ok_or(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing))?;
let saved_buf = self.buf;
self.buf = &self.buf[start_index + FINDER.needle().len()..];
let result = self.deserialize_seq_num();
self.buf = saved_buf;
result
}
pub fn reject(
&mut self,
tag: Option<TagNum>,
reason: SessionRejectReasonBase,
) -> DeserializeErrorKind {
let seq_num = if let Some(seq_num) = self.seq_num {
seq_num
} else {
match self.try_find_msg_seq_num() {
Ok(seq_num) => seq_num,
Err(err) => return err,
}
};
DeserializeErrorKind::Reject {
msg_type: self.msg_type.clone().map(|msg_type| {
FixString::from_ascii_lossy(self.raw_message.body[msg_type].to_vec())
}),
seq_num,
tag,
reason: reason.into(),
}
}
pub fn repeating_group_fields_out_of_order(
&mut self,
expected_tags: &[u16],
processed_tags: &[u16],
current_tag: u16,
) -> DeserializeErrorKind {
let mut current_tag_found = false;
'outer: for processed_tag in processed_tags {
for expected_tag in expected_tags {
if expected_tag == processed_tag {
if current_tag_found {
return self.reject(
Some(*processed_tag),
SessionRejectReasonBase::RepeatingGroupFieldsOutOfOrder,
);
} else {
continue 'outer;
}
} else if *expected_tag == current_tag {
current_tag_found = true;
}
}
}
self.reject(
Some(current_tag),
SessionRejectReasonBase::RepeatingGroupFieldsOutOfOrder,
)
}
pub fn put_tag(&mut self, tag: TagNum) {
self.tmp_tag = Some(tag);
}
pub fn field_cursor(&self) -> FieldCursor<'de> {
FieldCursor {
buf: self.buf,
tmp_tag: self.tmp_tag,
}
}
fn reject_value(&mut self, reason: SessionRejectReasonBase) -> DeserializeErrorKind {
match memchr(b'\x01', self.buf) {
Some(i) => self.buf = &self.buf[i + 1..],
None => self.buf = &[],
}
self.reject(self.current_tag, reason)
}
fn garbled_or_reject_value(
&mut self,
error: DeserializeErrorKindInternal,
) -> DeserializeErrorKind {
match error {
DeserializeErrorKindInternal::Incomplete => {
DeserializeErrorKind::Garbled(GarbledReason::IncompleteMessageData)
}
DeserializeErrorKindInternal::Error(reason) => self.reject_value(reason),
}
}
fn finish_value<T>(&mut self, value: T, rest: &'de [u8]) -> Result<T, DeserializeErrorKind> {
match rest {
[b'\x01', tail @ ..] => {
self.buf = tail;
Ok(value)
}
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
_ => Err(self.reject_value(SessionRejectReasonBase::IncorrectDataFormatForValue)),
}
}
pub fn range_to_fixstr(&self, range: ops::Range<usize>) -> &FixStr {
FixStr::from_ascii(&self.raw_message.body[range])
.expect("range does not name a printable-ASCII value")
}
pub fn deserialize_msg_type(&mut self) -> Result<ops::Range<usize>, DeserializeErrorKind> {
let raw_message_pointer = self.raw_message.body.as_ptr();
let msg_type_range = {
let Ok(deser_str) = self.deserialize_str() else {
return Err(self.reject(Some(35), SessionRejectReasonBase::InvalidMsgType));
};
let msg_type_pointer = deser_str.as_bytes().as_ptr();
let msg_type_start_index =
unsafe { msg_type_pointer.offset_from_unsigned(raw_message_pointer) };
let msg_type_len = deser_str.len();
msg_type_start_index..(msg_type_start_index + msg_type_len)
};
self.msg_type = Some(msg_type_range.clone());
Ok(msg_type_range)
}
pub fn deserialize_tag_num(&mut self) -> Result<Option<TagNum>, DeserializeErrorKind> {
if self.tmp_tag.is_some() {
return Ok(self.tmp_tag.take());
}
if self.buf.is_empty() {
return Ok(None);
}
match deserialize_tag_num(self.buf) {
Ok((rest, tag)) => {
self.buf = rest;
self.current_tag = Some(tag);
Ok(Some(tag))
}
Err(DeserializeErrorKindInternal::Incomplete) => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
Err(DeserializeErrorKindInternal::Error(reason)) => Err(self.reject(None, reason)),
}
}
pub fn deserialize_int(&mut self) -> Result<Int, DeserializeErrorKind> {
let negative = match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
[b'-', b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
[b'-', buf @ ..] => {
self.buf = buf;
true
}
_ => false,
};
let mut value: Int = 0;
for (i, &byte) in self.buf.iter().enumerate() {
match byte {
n @ b'0'..=b'9' => {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add((n - b'0') as Int))
.ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})?;
}
b'\x01' => {
let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
self.buf = rest;
return Ok(if negative { -value } else { value });
}
_ => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
}
}
Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
))
}
pub fn deserialize_seq_num(&mut self) -> Result<SeqNum, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing));
}
_ => {}
}
let mut value: SeqNum = 0;
for (i, &byte) in self.buf.iter().enumerate() {
match byte {
n @ b'0'..=b'9' => {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add((n - b'0') as SeqNum))
.ok_or(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing))?;
}
b'\x01' => {
let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
self.buf = rest;
return Ok(value);
}
_ => return Err(DeserializeErrorKind::Logout(LogoutReason::MsgSeqNumMissing)),
}
}
Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
))
}
pub fn deserialize_num_in_group(&mut self) -> Result<NumInGroup, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
let mut value: NumInGroup = 0;
for (i, &byte) in self.buf.iter().enumerate() {
match byte {
n @ b'0'..=b'9' => {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add((n - b'0') as NumInGroup))
.ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})?;
}
b'\x01' => {
if value == 0 {
return Err(self
.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect));
} else {
let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
self.buf = rest;
return Ok(value);
}
}
_ => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
}
}
Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
))
}
pub fn deserialize_day_of_month(&mut self) -> Result<DayOfMonth, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
[b'0', ..] => {
return Err(
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
);
}
_ => {}
};
let mut value: NumInGroup = 0;
for (i, &byte) in self.buf.iter().enumerate() {
match byte {
n @ b'0'..=b'9' => {
value = value
.checked_mul(10)
.and_then(|v| v.checked_add((n - b'0') as NumInGroup))
.ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})?;
}
b'\x01' => {
let (_, rest) = unsafe { self.buf.split_at_unchecked(i + 1) };
self.buf = rest;
break;
}
_ => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
}
}
match value {
1..=31 => Ok(value),
_ => Err(self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)),
}
}
pub fn deserialize_float(&mut self) -> Result<Float, DeserializeErrorKind> {
let (negative, buf) = match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
[b'-', b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
[b'-', buf @ ..] => (true, buf),
_ => (false, self.buf),
};
let mut num: i64 = 0;
let mut scale = None;
for (i, &byte) in buf.iter().enumerate() {
match byte {
n @ b'0'..=b'9' => {
num = num
.checked_mul(10)
.and_then(|v| v.checked_add((n - b'0') as i64))
.ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})?;
if let Some(scale) = scale.as_mut() {
*scale += 1;
}
}
b'.' => {
if scale.is_some() {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
scale = Some(0);
}
b'\x01' => {
let (_, rest) = unsafe { buf.split_at_unchecked(i + 1) };
self.buf = rest;
let scale = scale.unwrap_or(0);
return Decimal::try_new(if negative { -num } else { num }, scale).map_err(
|_| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
},
);
}
_ => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
}
}
Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
))
}
#[inline(always)]
pub fn deserialize_qty(&mut self) -> Result<Qty, DeserializeErrorKind> {
self.deserialize_float()
}
#[inline(always)]
pub fn deserialize_price(&mut self) -> Result<Price, DeserializeErrorKind> {
self.deserialize_float()
}
#[inline(always)]
pub fn deserialize_price_offset(&mut self) -> Result<PriceOffset, DeserializeErrorKind> {
self.deserialize_float()
}
#[inline(always)]
pub fn deserialize_amt(&mut self) -> Result<Amt, DeserializeErrorKind> {
self.deserialize_float()
}
#[inline(always)]
pub fn deserialize_percentage(&mut self) -> Result<Percentage, DeserializeErrorKind> {
self.deserialize_float()
}
pub fn deserialize_boolean(&mut self) -> Result<Boolean, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'Y'] | [b'N'] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[b'Y', b'\x01', buf @ ..] => {
self.buf = buf;
Ok(true)
}
[b'N', b'\x01', buf @ ..] => {
self.buf = buf;
Ok(false)
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_char(&mut self) -> Result<Char, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[0x00..=0x1f | 0x7f..=0xff, ..] => {
Err(self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect))
}
[n, b'\x01', buf @ ..] => {
self.buf = buf;
Ok(*n)
}
[_, byte] if *byte != b'\x01' => Err(DeserializeErrorKind::Garbled(
GarbledReason::MessageNotWellFormed,
)),
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_multiple_char_value(
&mut self,
) -> Result<MultipleCharValue, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
let i = memchr(b'\x01', self.buf).ok_or(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
))?;
let (data, rest) = unsafe { self.buf.split_at_unchecked(i) };
let (_, rest) = unsafe { rest.split_at_unchecked(1) };
self.buf = rest;
let mut result = MultipleCharValue::with_capacity(data.len() / 2 + 1);
for chunk in data.chunks(2) {
match chunk {
[b' '] | [b' ', _] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
[0x00..=0x1f] | [0x7f..=0xff] | [0x00..=0x1f, _] | [0x7f..=0xff, _] => {
return Err(
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
);
}
[n] | [n, b' '] => result.push(*n),
_ => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
));
}
}
}
Ok(result)
}
pub fn deserialize_str(&mut self) -> Result<&FixStr, DeserializeErrorKind> {
match deserialize_str(self.buf) {
Ok((leftover, fix_str)) => {
self.buf = leftover;
Ok(fix_str)
}
Err(DeserializeErrorKindInternal::Incomplete) => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
Err(DeserializeErrorKindInternal::Error(reason)) => {
Err(self.reject(self.current_tag, reason))
}
}
}
#[inline(always)]
pub fn deserialize_string(&mut self) -> Result<FixString, DeserializeErrorKind> {
self.deserialize_str().map(FixString::from)
}
pub fn deserialize_multiple_string_value(
&mut self,
) -> Result<MultipleStringValue, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
let i = memchr(b'\x01', self.buf).ok_or(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
))?;
let (data, rest) = unsafe { self.buf.split_at_unchecked(i) };
let (_, rest) = unsafe { rest.split_at_unchecked(1) };
self.buf = rest;
const DEFAULT_CAPACITY: usize = 4;
let mut result = MultipleStringValue::with_capacity(DEFAULT_CAPACITY);
for part in data.split(|p| *p == b' ') {
let mut sub_result = Vec::with_capacity(part.len());
for byte in part {
match byte {
0x00..=0x1f | 0x7f..=0xff => {
return Err(self
.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect));
}
n => sub_result.push(*n),
}
}
result.push(unsafe { FixString::from_ascii_unchecked(sub_result) });
}
Ok(result)
}
pub fn deserialize_country(&mut self) -> Result<Country, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[_, b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
bytes @ [_, _, b'\x01', buf @ ..] => {
self.buf = buf;
Country::from_bytes(&bytes[0..2]).ok_or_else(|| {
self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)
})
}
&[a, b, c] if a != b'\x01' && b != b'\x01' && c != b'\x01' => Err(
DeserializeErrorKind::Garbled(GarbledReason::MessageNotWellFormed),
),
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_currency(&mut self) -> Result<Currency, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
bytes @ [_, _, _, b'\x01', buf @ ..] => {
self.buf = buf;
Currency::from_bytes(&bytes[0..3]).ok_or_else(|| {
self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)
})
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_exchange(&mut self) -> Result<Exchange, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[a, b, c, d, b'\x01', buf @ ..] => {
let exchange = Exchange::from_bytes([*a, *b, *c, *d]).map_err(|_| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})?;
self.buf = buf;
Ok(exchange)
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
#[inline(always)]
pub fn deserialize_month_year(&mut self) -> Result<MonthYear, DeserializeErrorKind> {
self.deserialize_string()
}
pub fn deserialize_language(&mut self) -> Result<Language, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[a, b, b'\x01', buf @ ..] => {
let language = Language::from_bytes(&[*a, *b]).ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})?;
self.buf = buf;
Ok(language)
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_utc_timestamp(&mut self) -> Result<UtcTimestamp, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
match parse_utc_timestamp(self.buf) {
Ok((timestamp, rest)) => self.finish_value(timestamp, rest),
Err(error) => Err(self.garbled_or_reject_value(error)),
}
}
pub fn deserialize_utc_time_only(&mut self) -> Result<UtcTimeOnly, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
match parse_utc_time_only(self.buf) {
Ok((time, rest)) => self.finish_value(time, rest),
Err(error) => Err(self.garbled_or_reject_value(error)),
}
}
pub fn deserialize_utc_date_only(&mut self) -> Result<UtcDateOnly, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[_] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[
y3 @ b'0'..=b'9',
y2 @ b'0'..=b'9',
y1 @ b'0'..=b'9',
y0 @ b'0'..=b'9',
m1 @ b'0'..=b'1',
m0 @ b'0'..=b'9',
d1 @ b'0'..=b'3',
d0 @ b'0'..=b'9',
b'\x01',
rest @ ..,
] => {
let year = (y3 - b'0') as u16 * 1000
+ (y2 - b'0') as u16 * 100
+ (y1 - b'0') as u16 * 10
+ (y0 - b'0') as u16;
let month = (m1 - b'0') * 10 + (m0 - b'0');
let day = (d1 - b'0') * 10 + (d0 - b'0');
self.buf = rest;
UtcDateOnly::from_ymd_opt(year.into(), month.into(), day.into()).ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_local_mkt_time(&mut self) -> Result<LocalMktTime, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[_] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[
h1 @ b'0'..=b'2',
h0 @ b'0'..=b'9',
b':',
m1 @ b'0'..=b'5',
m0 @ b'0'..=b'9',
b':',
s1 @ b'0'..=b'5',
s0 @ b'0'..=b'9',
b'\x01',
rest @ ..,
] => {
let hour = (h1 - b'0') as u32 * 10 + (h0 - b'0') as u32;
let minute = (m1 - b'0') as u32 * 10 + (m0 - b'0') as u32;
let second = (s1 - b'0') as u32 * 10 + (s0 - b'0') as u32;
self.buf = rest;
LocalMktTime::from_hms_opt(hour, minute, second).ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_local_mkt_date(&mut self) -> Result<LocalMktDate, DeserializeErrorKind> {
match self.buf {
[] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[b'\x01', ..] => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
)),
[_] => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
[
y3 @ b'0'..=b'9',
y2 @ b'0'..=b'9',
y1 @ b'0'..=b'9',
y0 @ b'0'..=b'9',
m1 @ b'0'..=b'1',
m0 @ b'0'..=b'9',
d1 @ b'0'..=b'3',
d0 @ b'0'..=b'9',
b'\x01',
rest @ ..,
] => {
let year = (y3 - b'0') as u16 * 1000
+ (y2 - b'0') as u16 * 100
+ (y1 - b'0') as u16 * 10
+ (y0 - b'0') as u16;
let month = (m1 - b'0') * 10 + (m0 - b'0');
let day = (d1 - b'0') * 10 + (d0 - b'0');
self.buf = rest;
LocalMktDate::from_ymd_opt(year.into(), month.into(), day.into()).ok_or_else(|| {
self.reject(self.current_tag, SessionRejectReasonBase::ValueIsIncorrect)
})
}
_ => Err(self.reject(
self.current_tag,
SessionRejectReasonBase::IncorrectDataFormatForValue,
)),
}
}
pub fn deserialize_tz_timestamp(&mut self) -> Result<TzTimestamp, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
match parse_tz_timestamp(self.buf) {
Ok((timestamp, rest)) => self.finish_value(timestamp, rest),
Err(error) => Err(self.garbled_or_reject_value(error)),
}
}
pub fn deserialize_tz_timeonly(&mut self) -> Result<TzTimeOnly, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
match parse_tz_time_only(self.buf) {
Ok((time, rest)) => self.finish_value(time, rest),
Err(error) => Err(self.garbled_or_reject_value(error)),
}
}
pub fn deserialize_length(&mut self) -> Result<Length, DeserializeErrorKind> {
match deserialize_length(self.buf) {
Ok((leftover, len)) => {
self.buf = leftover;
Ok(len)
}
Err(DeserializeErrorKindInternal::Incomplete) => Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
)),
Err(DeserializeErrorKindInternal::Error(reject)) => {
Err(self.reject(self.current_tag, reject))
}
}
}
pub fn deserialize_data(&mut self, len: usize) -> Result<Data, DeserializeErrorKind> {
if len >= self.buf.len() {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
if unsafe { *self.buf.get_unchecked(len) } != b'\x01' {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::MessageNotWellFormed,
));
}
let (data, rest) = unsafe { self.buf.split_at_unchecked(len) };
let (_, rest) = unsafe { rest.split_at_unchecked(1) };
self.buf = rest;
Ok(data.into())
}
pub fn deserialize_xml(&mut self, len: usize) -> Result<XmlData, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
if len >= self.buf.len() {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
if unsafe { *self.buf.get_unchecked(len) } != b'\x01' {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::MessageNotWellFormed,
));
}
let (xml, rest) = unsafe { self.buf.split_at_unchecked(len) };
let (_, rest) = unsafe { rest.split_at_unchecked(1) };
self.buf = rest;
Ok(xml.into())
}
pub fn deserialize_tenor(&mut self) -> Result<Tenor, DeserializeErrorKind> {
match self.buf {
[] => {
return Err(DeserializeErrorKind::Garbled(
GarbledReason::IncompleteMessageData,
));
}
[b'\x01', ..] => {
return Err(self.reject(
self.current_tag,
SessionRejectReasonBase::TagSpecifiedWithoutAValue,
));
}
_ => {}
}
match parse_tenor(self.buf) {
Ok((tenor, rest)) => self.finish_value(tenor, rest),
Err(error) => Err(self.garbled_or_reject_value(error)),
}
}
pub fn deserialize_int_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
where
T: TryFrom<Int, Error = SessionRejectReasonBase>,
{
T::try_from(self.deserialize_int()?).map_err(|reason| self.reject(self.current_tag, reason))
}
pub fn deserialize_num_in_group_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
where
T: TryFrom<NumInGroup, Error = SessionRejectReasonBase>,
{
T::try_from(self.deserialize_num_in_group()?)
.map_err(|reason| self.reject(self.current_tag, reason))
}
pub fn deserialize_char_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
where
T: TryFrom<Char, Error = SessionRejectReasonBase>,
{
let value = self.deserialize_char()?;
T::try_from(value).map_err(|reason| self.reject(self.current_tag, reason))
}
pub fn deserialize_string_enum<T>(&mut self) -> Result<T, DeserializeErrorKind>
where
for<'a> T: TryFrom<&'a FixStr, Error = SessionRejectReasonBase>,
{
let value = self.deserialize_str()?;
T::try_from(value).map_err(|reason| self.reject(self.current_tag, reason))
}
pub fn deserialize_multiple_char_value_enum<T>(
&mut self,
) -> Result<Vec<T>, DeserializeErrorKind>
where
T: TryFrom<Char, Error = SessionRejectReasonBase>,
{
let values = self.deserialize_multiple_char_value()?;
let mut result = Vec::with_capacity(values.len());
for value in values {
result
.push(T::try_from(value).map_err(|reason| self.reject(self.current_tag, reason))?);
}
Ok(result)
}
pub fn deserialize_multiple_string_value_enum<T>(
&mut self,
) -> Result<Vec<T>, DeserializeErrorKind>
where
for<'a> T: TryFrom<&'a FixStr, Error = SessionRejectReasonBase>,
{
let values = self.deserialize_multiple_string_value()?;
let mut result = Vec::with_capacity(values.len());
for value in values {
result
.push(T::try_from(&value).map_err(|reason| self.reject(self.current_tag, reason))?);
}
Ok(result)
}
}