use crate::{
charset::Charset,
error::EdifactError,
model::{Element, OwnedSegment, Segment, Span},
parser::ReaderConfig,
};
use std::io::{Chain, Cursor, Read};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SyntaxVersion {
V1,
V2,
V3,
V4,
}
impl SyntaxVersion {
#[must_use]
pub const fn number(self) -> u8 {
match self {
Self::V1 => 1,
Self::V2 => 2,
Self::V3 => 3,
Self::V4 => 4,
}
}
pub(crate) const fn from_number(number: u8) -> Option<Self> {
match number {
1 => Some(Self::V1),
2 => Some(Self::V2),
3 => Some(Self::V3),
4 => Some(Self::V4),
_ => None,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Year {
TwoDigit(u8),
Full(u16),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "RawDateTime", into = "RawDateTime")
)]
pub struct PreparationDateTime {
year: Year,
month: u8,
day: u8,
hour: u8,
minute: u8,
}
#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
struct RawDateTime {
year: Year,
month: u8,
day: u8,
hour: u8,
minute: u8,
}
#[cfg(feature = "serde")]
impl TryFrom<RawDateTime> for PreparationDateTime {
type Error = EdifactError;
fn try_from(raw: RawDateTime) -> Result<Self, EdifactError> {
Self::checked(raw.year, raw.month, raw.day, raw.hour, raw.minute)
}
}
#[cfg(feature = "serde")]
impl From<PreparationDateTime> for RawDateTime {
fn from(value: PreparationDateTime) -> Self {
Self {
year: value.year,
month: value.month,
day: value.day,
hour: value.hour,
minute: value.minute,
}
}
}
fn invalid_date_time(component: usize, value: String) -> EdifactError {
EdifactError::InvalidDateTime {
tag: "UNB".to_owned(),
element_index: 3,
component_index: component,
value,
span: Span::default(),
}
}
impl PreparationDateTime {
pub fn new(year: u16, month: u8, day: u8, hour: u8, minute: u8) -> Result<Self, EdifactError> {
Self::checked(Year::Full(year), month, day, hour, minute)
}
pub fn from_two_digit_year(
yy: u8,
month: u8,
day: u8,
hour: u8,
minute: u8,
) -> Result<Self, EdifactError> {
Self::checked(Year::TwoDigit(yy), month, day, hour, minute)
}
fn checked(year: Year, month: u8, day: u8, hour: u8, minute: u8) -> Result<Self, EdifactError> {
let (leap, year_ok) = match year {
Year::TwoDigit(yy) => (yy % 4 == 0, yy <= 99),
Year::Full(y) => (crate::envelope::is_leap_year(y), y <= 9999),
};
let date_ok = year_ok && day >= 1 && day <= crate::envelope::days_in_month(month, leap);
let value = Self {
year,
month,
day,
hour,
minute,
};
if !date_ok {
return Err(invalid_date_time(0, value.date_text()));
}
if !crate::envelope::is_valid_time(u16::from(hour), u16::from(minute)) {
return Err(invalid_date_time(1, value.time_text()));
}
Ok(value)
}
#[must_use]
pub const fn year(self) -> Year {
self.year
}
#[must_use]
pub const fn month(self) -> u8 {
self.month
}
#[must_use]
pub const fn day(self) -> u8 {
self.day
}
#[must_use]
pub const fn hour(self) -> u8 {
self.hour
}
#[must_use]
pub const fn minute(self) -> u8 {
self.minute
}
pub fn with_century(self, century: u16) -> Result<Self, EdifactError> {
match self.year {
Year::Full(_) => Ok(self),
Year::TwoDigit(yy) => Self::checked(
Year::Full(century.saturating_mul(100).saturating_add(u16::from(yy))),
self.month,
self.day,
self.hour,
self.minute,
),
}
}
fn date_text(self) -> String {
match self.year {
Year::TwoDigit(yy) => format!("{yy:02}{:02}{:02}", self.month, self.day),
Year::Full(y) => format!("{y:04}{:02}{:02}", self.month, self.day),
}
}
fn time_text(self) -> String {
format!("{:02}{:02}", self.hour, self.minute)
}
pub(crate) fn format_for(self, version: SyntaxVersion) -> Result<[String; 2], EdifactError> {
let date = match (version, self.year) {
(SyntaxVersion::V4, Year::Full(y)) => {
format!("{y:04}{:02}{:02}", self.month, self.day)
}
(SyntaxVersion::V4, Year::TwoDigit(_)) => {
return Err(invalid_date_time(0, self.date_text()));
}
(_, Year::Full(y)) => format!("{:02}{:02}{:02}", y % 100, self.month, self.day),
(_, Year::TwoDigit(yy)) => format!("{yy:02}{:02}{:02}", self.month, self.day),
};
Ok([date, self.time_text()])
}
fn parse(date: &str, time: &str) -> Option<Self> {
let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
if !digits(date) || !digits(time) || time.len() != 4 {
return None;
}
let num = |s: &str| s.parse::<u16>().ok();
let (year, rest) = match date.len() {
6 => (Year::TwoDigit(num(&date[..2])? as u8), &date[2..]),
8 => (Year::Full(num(&date[..4])?), &date[4..]),
_ => return None,
};
let (month, day) = (num(&rest[..2])? as u8, num(&rest[2..])? as u8);
let (hour, minute) = (num(&time[..2])? as u8, num(&time[2..])? as u8);
Self::checked(year, month, day, hour, minute).ok()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Party {
pub id: String,
pub qualifier: Option<String>,
pub internal_id: Option<String>,
pub internal_sub_id: Option<String>,
}
impl Party {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
qualifier: None,
internal_id: None,
internal_sub_id: None,
}
}
#[must_use]
pub fn with_qualifier(mut self, qualifier: impl Into<String>) -> Self {
self.qualifier = Some(qualifier.into());
self
}
#[must_use]
pub fn with_internal_id(mut self, id: impl Into<String>) -> Self {
self.internal_id = Some(id.into());
self
}
#[must_use]
pub fn with_internal_sub_id(mut self, id: impl Into<String>) -> Self {
self.internal_sub_id = Some(id.into());
self
}
fn components(&self) -> Vec<String> {
vec![
self.id.clone(),
opt(&self.qualifier),
opt(&self.internal_id),
opt(&self.internal_sub_id),
]
}
fn from_element(seg: &Segment<'_>, element: usize) -> Self {
Self {
id: text(seg, element, 0),
qualifier: optional(seg, element, 1),
internal_id: optional(seg, element, 2),
internal_sub_id: optional(seg, element, 3),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InterchangeHeader {
pub charset: Charset,
pub syntax_version: SyntaxVersion,
pub service_code_list_version: Option<String>,
pub character_encoding: Option<String>,
pub syntax_release: Option<String>,
pub sender: Party,
pub recipient: Party,
pub prepared: PreparationDateTime,
pub control_ref: String,
pub recipient_password: Option<String>,
pub recipient_password_qualifier: Option<String>,
pub application_ref: Option<String>,
pub processing_priority: Option<String>,
pub acknowledgement_requested: bool,
pub communications_agreement_id: Option<String>,
pub test_indicator: bool,
}
impl InterchangeHeader {
#[must_use]
pub fn new(
charset: Charset,
syntax_version: SyntaxVersion,
sender: Party,
recipient: Party,
prepared: PreparationDateTime,
control_ref: impl Into<String>,
) -> Self {
Self {
charset,
syntax_version,
service_code_list_version: None,
character_encoding: None,
syntax_release: None,
sender,
recipient,
prepared,
control_ref: control_ref.into(),
recipient_password: None,
recipient_password_qualifier: None,
application_ref: None,
processing_priority: None,
acknowledgement_requested: false,
communications_agreement_id: None,
test_indicator: false,
}
}
#[must_use]
pub fn with_recipient_password(
mut self,
password: impl Into<String>,
qualifier: Option<String>,
) -> Self {
self.recipient_password = Some(password.into());
self.recipient_password_qualifier = qualifier;
self
}
#[must_use]
pub fn with_application_ref(mut self, reference: impl Into<String>) -> Self {
self.application_ref = Some(reference.into());
self
}
#[must_use]
pub fn with_processing_priority(mut self, priority: impl Into<String>) -> Self {
self.processing_priority = Some(priority.into());
self
}
#[must_use]
pub fn with_acknowledgement_requested(mut self, requested: bool) -> Self {
self.acknowledgement_requested = requested;
self
}
#[must_use]
pub fn with_communications_agreement_id(mut self, id: impl Into<String>) -> Self {
self.communications_agreement_id = Some(id.into());
self
}
#[must_use]
pub fn with_test_indicator(mut self, test: bool) -> Self {
self.test_indicator = test;
self
}
#[must_use]
pub fn with_service_code_list_version(mut self, version: impl Into<String>) -> Self {
self.service_code_list_version = Some(version.into());
self
}
#[must_use]
pub fn with_character_encoding(mut self, encoding: impl Into<String>) -> Self {
self.character_encoding = Some(encoding.into());
self
}
#[must_use]
pub fn with_syntax_release(mut self, release: impl Into<String>) -> Self {
self.syntax_release = Some(release.into());
self
}
#[must_use]
pub fn is_test(&self) -> bool {
self.test_indicator
}
#[must_use]
pub fn ack_requested(&self) -> bool {
self.acknowledgement_requested
}
pub fn parse(unb: &Segment<'_>) -> Result<Self, EdifactError> {
if unb.tag() != "UNB" {
return Err(not_unb(unb));
}
let mut findings = Vec::new();
let version = crate::envelope::syntax_version(unb)?;
crate::directory_validator::check_service_segment(unb, version, &mut findings);
crate::envelope::check_s004(unb, version, &mut findings);
check_flags(unb, &mut findings);
if let Some(first) = findings.into_iter().next() {
return Err(first);
}
Self::build(unb)
}
pub(crate) fn from_unb_lenient(unb: &Segment<'_>) -> Option<Self> {
Self::build(unb).ok()
}
fn build(unb: &Segment<'_>) -> Result<Self, EdifactError> {
let missing = |element_index: usize| EdifactError::MissingRequiredElement {
tag: "UNB".to_owned(),
element_index,
};
let charset = Charset::from_syntax_identifier(&text(unb, 0, 0))?;
let syntax_version = crate::envelope::syntax_version(unb)?
.and_then(SyntaxVersion::from_number)
.ok_or_else(|| missing(0))?;
let sender = Party::from_element(unb, 1);
let recipient = Party::from_element(unb, 2);
if sender.id.is_empty() {
return Err(missing(1));
}
if recipient.id.is_empty() {
return Err(missing(2));
}
let (date, time) = (text(unb, 3, 0), text(unb, 3, 1));
let prepared =
PreparationDateTime::parse(&date, &time).ok_or_else(|| invalid_date_time(0, date))?;
let control_ref = text(unb, 4, 0);
if control_ref.is_empty() {
return Err(missing(4));
}
Ok(Self {
charset,
syntax_version,
service_code_list_version: optional(unb, 0, 2),
character_encoding: optional(unb, 0, 3),
syntax_release: optional(unb, 0, 4),
sender,
recipient,
prepared,
control_ref,
recipient_password: optional(unb, 5, 0),
recipient_password_qualifier: optional(unb, 5, 1),
application_ref: optional(unb, 6, 0),
processing_priority: optional(unb, 7, 0),
acknowledgement_requested: unb.component_str(8, 0) == Some("1"),
communications_agreement_id: optional(unb, 9, 0),
test_indicator: unb.component_str(10, 0) == Some("1"),
})
}
pub fn read(input: &[u8]) -> Result<Self, EdifactError> {
let config = ReaderConfig::default();
let bound = read_bound(&config);
let view = &input[..input.len().min(bound)];
let end = locate(view, bound, view.len() == input.len())?
.expect("a complete input is always located");
parse_head(&input[..end], config)
}
#[allow(clippy::type_complexity)]
pub fn read_from<R: Read>(
mut reader: R,
config: &ReaderConfig,
) -> Result<(Self, Chain<Cursor<Vec<u8>>, R>), EdifactError> {
let bound = read_bound(config);
let mut buf = Vec::with_capacity(bound.min(CHUNK));
let end = loop {
let start = buf.len();
let want = (bound - start).min(CHUNK);
buf.resize(start + want, 0);
let read = loop {
match reader.read(&mut buf[start..]) {
Ok(n) => break n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e.into()),
}
};
buf.truncate(start + read);
if let Some(end) = locate(&buf, bound, read == 0)? {
break end;
}
};
let header = parse_head(&buf[..end], *config)?;
Ok((header, Cursor::new(buf).chain(reader)))
}
pub fn to_segment(&self) -> Result<OwnedSegment, EdifactError> {
let [date, time] = self.prepared.format_for(self.syntax_version)?;
let flag = |set: bool| if set { "1".to_owned() } else { String::new() };
let elements: Vec<Vec<String>> = vec![
vec![
self.charset.syntax_identifier().to_owned(),
self.syntax_version.number().to_string(),
opt(&self.service_code_list_version),
opt(&self.character_encoding),
opt(&self.syntax_release),
],
self.sender.components(),
self.recipient.components(),
vec![date, time],
vec![self.control_ref.clone()],
vec![
opt(&self.recipient_password),
opt(&self.recipient_password_qualifier),
],
vec![opt(&self.application_ref)],
vec![opt(&self.processing_priority)],
vec![flag(self.acknowledgement_requested)],
vec![opt(&self.communications_agreement_id)],
vec![flag(self.test_indicator)],
];
let segment = crate::writer::canonical(OwnedSegment::new(
"UNB",
elements.iter().map(|c| Element::of(c)).collect(),
));
let mut findings = Vec::new();
crate::directory_validator::check_service_segment(
&segment,
Some(self.syntax_version.number()),
&mut findings,
);
match findings.into_iter().next() {
Some(first) => Err(first),
None => Ok(segment),
}
}
}
pub(crate) fn check_flags(unb: &Segment<'_>, out: &mut Vec<EdifactError>) {
for (element, code) in [(8, "0031"), (10, "0035")] {
match unb.component_str(element, 0) {
None | Some("" | "1") => {}
Some(value) => out.push(EdifactError::InvalidCodeValue {
tag: "UNB".to_owned(),
element_index: element,
value: value.to_owned(),
code_list: code.to_owned(),
span: unb
.get_element(element)
.and_then(|e| e.component_span(0))
.unwrap_or(unb.span),
suggestion: Some("1"),
}),
}
}
}
fn not_unb(seg: &Segment<'_>) -> EdifactError {
crate::envelope::classify_u_tag(seg.tag(), seg.span).unwrap_or_else(|| {
EdifactError::MissingSegment {
tag: "UNB".to_owned(),
expected_position: "first segment of interchange".to_owned(),
}
})
}
const CHUNK: usize = 4096;
const PROLOGUE_CAP: usize = 4096;
fn read_bound(config: &ReaderConfig) -> usize {
PROLOGUE_CAP
.saturating_add(9)
.saturating_add(config.max_segment_bytes)
}
fn locate(buf: &[u8], bound: usize, complete: bool) -> Result<Option<usize>, EdifactError> {
let exceeded = || EdifactError::LimitExceeded {
limit: "header_read",
max: bound as u64,
offset: buf.len(),
};
let (prologue, head) = crate::tokenizer::classify_head(buf);
if prologue > PROLOGUE_CAP {
return Err(exceeded());
}
let (start, ssa) = match head {
crate::tokenizer::Head::Una(una) => (
prologue + 9,
crate::tokenizer::ServiceStringAdvice::from_una(una),
),
crate::tokenizer::Head::TruncatedUna if !complete => return Ok(None),
_ => (prologue, crate::tokenizer::ServiceStringAdvice::default()),
};
let found = buf.get(start..).and_then(|rest| {
crate::parser::find_unescaped_term(rest, ssa.segment_term, ssa.release_char)
});
match found {
Some(at) => Ok(Some(start + at + 1)),
None if buf.len() >= bound => Err(exceeded()),
None if complete => Ok(Some(buf.len())),
None => Ok(None),
}
}
fn parse_head(head: &[u8], config: ReaderConfig) -> Result<InterchangeHeader, EdifactError> {
let decoded = crate::charset::decode_for_parse(head)?;
match crate::from_bytes_with_config(&decoded, config).next() {
Some(Ok(segment)) => InterchangeHeader::parse(&segment),
Some(Err(error)) => Err(error),
None => Err(EdifactError::MissingSegment {
tag: "UNB".to_owned(),
expected_position: "first segment of interchange".to_owned(),
}),
}
}
fn text(seg: &Segment<'_>, element: usize, component: usize) -> String {
seg.component_str(element, component)
.unwrap_or("")
.to_owned()
}
fn optional(seg: &Segment<'_>, element: usize, component: usize) -> Option<String> {
seg.component_str(element, component)
.filter(|s| !s.is_empty())
.map(str::to_owned)
}
fn opt(value: &Option<String>) -> String {
value.clone().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn code(result: Result<impl std::fmt::Debug, EdifactError>) -> &'static str {
result.expect_err("must fail").stable_code()
}
#[test]
fn two_digit_29_february_needs_no_century() {
assert!(PreparationDateTime::from_two_digit_year(0, 2, 29, 0, 0).is_ok());
assert_eq!(
code(PreparationDateTime::from_two_digit_year(1, 2, 29, 0, 0)),
"E060"
);
let d = PreparationDateTime::from_two_digit_year(0, 2, 29, 0, 0).unwrap();
assert_eq!(code(d.with_century(19)), "E060");
assert_eq!(d.with_century(20).unwrap().year(), Year::Full(2000));
}
#[test]
fn hour_24_is_not_a_time() {
assert_eq!(code(PreparationDateTime::new(2026, 1, 1, 24, 0)), "E060");
assert_eq!(code(PreparationDateTime::new(2026, 1, 1, 23, 60)), "E060");
assert!(PreparationDateTime::new(2026, 1, 1, 23, 59).is_ok());
}
#[test]
fn with_century_resolves_only_two_digit_years() {
let d = PreparationDateTime::from_two_digit_year(99, 1, 1, 0, 0).unwrap();
assert_eq!(d.with_century(19).unwrap().year(), Year::Full(1999));
assert_eq!(d.with_century(20).unwrap().year(), Year::Full(2099));
let full = PreparationDateTime::new(1999, 1, 1, 0, 0).unwrap();
assert_eq!(full.with_century(20).unwrap(), full);
}
#[test]
fn version_4_refuses_a_two_digit_year() {
let d = PreparationDateTime::from_two_digit_year(99, 1, 1, 0, 0).unwrap();
assert_eq!(code(d.format_for(SyntaxVersion::V4)), "E060");
assert_eq!(
d.format_for(SyntaxVersion::V3).unwrap(),
["990101".to_owned(), "0000".to_owned()]
);
let full = PreparationDateTime::new(2099, 1, 1, 7, 5).unwrap();
assert_eq!(
full.format_for(SyntaxVersion::V4).unwrap(),
["20990101".to_owned(), "0705".to_owned()]
);
assert_eq!(full.format_for(SyntaxVersion::V1).unwrap()[0], "990101");
}
#[test]
fn two_digit_and_full_years_are_never_equal() {
let two = PreparationDateTime::from_two_digit_year(99, 1, 1, 0, 0).unwrap();
let full = PreparationDateTime::new(2099, 1, 1, 0, 0).unwrap();
assert_ne!(two, full);
}
#[cfg(feature = "serde")]
#[test]
fn serde_keeps_a_two_digit_year() {
let two = PreparationDateTime::from_two_digit_year(99, 1, 1, 0, 0).unwrap();
let json = serde_json::to_string(&two).unwrap();
assert!(json.contains("TwoDigit"), "{json}");
let back: PreparationDateTime = serde_json::from_str(&json).unwrap();
assert_eq!(back, two);
assert_eq!(back.year(), Year::TwoDigit(99));
let bad = json.replace("\"day\":1", "\"day\":32");
assert!(serde_json::from_str::<PreparationDateTime>(&bad).is_err());
}
#[test]
fn writing_a_v4_header_from_a_two_digit_year_is_refused() {
let header = InterchangeHeader::new(
Charset::UnoC,
SyntaxVersion::V4,
Party::new("S"),
Party::new("R"),
PreparationDateTime::from_two_digit_year(99, 1, 1, 0, 0).unwrap(),
"1",
);
assert_eq!(code(header.to_segment()), "E060");
}
}