use std::fmt;
use std::str::FromStr;
use rust_decimal::Decimal;
use crate::error::Rejection;
macro_rules! display_as_str {
($t:ty) => {
impl fmt::Display for $t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
};
}
fn no_line_breaks(s: &str) -> bool {
!s.contains(['\n', '\r'])
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SpecVersion(String);
impl SpecVersion {
pub const CURRENT: &'static str = "3.1.0";
#[must_use]
pub fn current() -> Self {
Self(Self::CURRENT.to_owned())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn major(&self) -> u64 {
self.0
.split('.')
.next()
.and_then(|m| m.parse().ok())
.unwrap_or(0)
}
}
impl FromStr for SpecVersion {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let parts: Vec<&str> = s.split('.').collect();
if parts.len() == 3
&& parts
.iter()
.all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
{
Ok(Self(s.to_owned()))
} else {
Err(Rejection::schema(
"[XSD SpecVersion]",
format!(
"{s} is not a version of the form 3.1.0.",
s = crate::error::quote(&s)
),
))
}
}
}
display_as_str!(SpecVersion);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MessageUuid(uuid::Uuid);
impl MessageUuid {
#[must_use]
pub fn from_uuid(id: uuid::Uuid) -> Self {
Self(id)
}
#[must_use]
pub fn from_bytes(bytes: [u8; 16]) -> Self {
Self(uuid::Uuid::from_bytes(bytes))
}
#[must_use]
pub fn as_uuid(&self) -> &uuid::Uuid {
&self.0
}
}
impl FromStr for MessageUuid {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let groups: Vec<&str> = s.split('-').collect();
let shape_ok = groups.len() == 5
&& groups
.iter()
.zip([8, 4, 4, 4, 12])
.all(|(g, n)| g.len() == n && g.bytes().all(|b| b.is_ascii_hexdigit()));
if !shape_ok {
return Err(Rejection::schema(
"[XSD UUIDType]",
format!(
"{s} is not a UUID in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.",
s = crate::error::quote(&s)
),
));
}
uuid::Uuid::parse_str(s).map(Self).map_err(|_| {
Rejection::schema(
"[XSD UUIDType]",
format!("{s} is not a UUID.", s = crate::error::quote(&s)),
)
})
}
}
impl fmt::Display for MessageUuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0.hyphenated(), f)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EntityAddress(String);
impl EntityAddress {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for EntityAddress {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let ok = if let Some(digits) = s.strip_prefix("ean.") {
(12..=34).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit())
} else if let Some(rest) = s.strip_prefix("ea1.") {
let b = rest.as_bytes();
let date_ok = b.len() > 8
&& b[..4].iter().all(u8::is_ascii_digit)
&& b[4] == b'-'
&& b[5..7].iter().all(u8::is_ascii_digit)
&& b[7] == b'.';
date_ok && no_line_breaks(rest) && {
let tail = &rest[8..];
tail.char_indices()
.filter(|&(_, c)| c == ':')
.any(|(i, _)| {
let (l, r) = (tail[..i].chars().count(), tail[i + 1..].chars().count());
(1..=244).contains(&l) && (1..=244).contains(&r)
})
}
} else {
false
};
if ok {
Ok(Self(s.to_owned()))
} else {
Err(Rejection::schema(
"[XSD EntityAddressType]",
format!(
"{s} is not an entity address (ean.<12–34 digits> or ea1.YYYY-MM.<authority>:<name>).",
s = crate::error::quote(&s)
),
))
}
}
}
display_as_str!(EntityAddress);
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct InternetDomain(String);
impl InternetDomain {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for InternetDomain {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let labels: Vec<&str> = s.split('.').collect();
let label_ok = |l: &&str| {
!l.is_empty()
&& !l.starts_with('-')
&& !l.ends_with('-')
&& !l.contains("--")
&& l.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
};
let ok = labels.len() >= 2
&& labels[..labels.len() - 1].iter().all(label_ok)
&& labels
.last()
.is_some_and(|t| t.len() >= 2 && t.bytes().all(|b| b.is_ascii_lowercase()));
if ok {
Ok(Self(s.to_owned()))
} else {
Err(Rejection::schema(
"[XSD InternetDomainType]",
format!(
"{s} is not a lower-case Internet domain such as dso.example.com.",
s = crate::error::quote(&s)
),
))
}
}
}
display_as_str!(InternetDomain);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Currency([u8; 3]);
impl Currency {
pub const EUR: Self = Self(*b"EUR");
#[must_use]
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).unwrap_or("???")
}
}
impl FromStr for Currency {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
match s.as_bytes() {
&[a, b, c] if [a, b, c].iter().all(u8::is_ascii_uppercase) => Ok(Self([a, b, c])),
_ => Err(Rejection::schema(
"[XSD ISO4217CurrencyType]",
format!(
"{s} is not a three-letter currency code.",
s = crate::error::quote(&s)
),
)),
}
}
}
display_as_str!(Currency);
fn parse_xsd_decimal(s: &str, rule: &'static str) -> Result<Decimal, Rejection> {
let body = s.strip_prefix(['+', '-']).unwrap_or(s);
let (int, frac) = body.split_once('.').unwrap_or((body, ""));
let lexical_ok = !(int.is_empty() && frac.is_empty())
&& int.bytes().all(|b| b.is_ascii_digit())
&& frac.bytes().all(|b| b.is_ascii_digit());
if !lexical_ok {
return Err(Rejection::schema(
rule,
format!("{s} is not a decimal number.", s = crate::error::quote(&s)),
));
}
let normalised = if int.is_empty() {
format!("0{s}")
} else {
s.to_owned()
};
Decimal::from_str_exact(normalised.trim_start_matches('+')).map_err(|_| {
Rejection::schema(
rule,
format!(
"{s} is out of the supported decimal range.",
s = crate::error::quote(&s)
),
)
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Amount(Decimal);
impl Amount {
pub const ZERO: Self = Self(Decimal::ZERO);
pub fn new(value: Decimal) -> Result<Self, Rejection> {
if value.scale() <= 4 {
return Ok(Self(value));
}
let v = value.normalize();
if v.scale() <= 4 {
Ok(Self(v))
} else {
Err(Rejection::schema(
"[XSD CurrencyAmountType]",
format!("{value} has more than four fraction digits."),
))
}
}
#[must_use]
pub fn value(&self) -> Decimal {
self.0
}
}
impl FromStr for Amount {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
Self::new(parse_xsd_decimal(s, "[XSD CurrencyAmountType]")?)
}
}
impl fmt::Display for Amount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ActivationFactor(Decimal);
impl ActivationFactor {
pub const FULL: Self = Self(Decimal::ONE);
pub fn new(value: Decimal) -> Result<Self, Rejection> {
let v = value.normalize();
if v.scale() <= 2 && v >= Decimal::new(1, 2) && v <= Decimal::ONE {
Ok(Self(v))
} else {
Err(Rejection::schema(
"[XSD ActivationFactorType]",
format!(
"{value} is not an activation factor between 0.01 and 1.00 with two decimals."
),
))
}
}
#[must_use]
pub fn value(&self) -> Decimal {
self.0
}
}
impl Default for ActivationFactor {
fn default() -> Self {
Self::FULL
}
}
impl FromStr for ActivationFactor {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
Self::new(parse_xsd_decimal(s, "[XSD ActivationFactorType]")?)
}
}
impl fmt::Display for ActivationFactor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.2}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneName {
name: String,
zone: jiff::tz::TimeZone,
}
impl TimeZoneName {
#[must_use]
pub fn as_str(&self) -> &str {
&self.name
}
#[must_use]
pub fn zone(&self) -> &jiff::tz::TimeZone {
&self.zone
}
}
impl FromStr for TimeZoneName {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let pattern_ok = s.split_once('/').is_some_and(|(area, rest)| {
["Africa", "America", "Australia", "Europe", "Pacific"].contains(&area)
&& rest.len() >= 3
&& rest
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/')
});
if !pattern_ok {
return Err(Rejection::schema(
"[XSD TimeZoneNameType]",
format!(
"{s} is not an Africa/, America/, Australia/, Europe/ or Pacific/ time-zone name.",
s = crate::error::quote(&s)
),
));
}
let zone = jiff::tz::db().get(s).map_err(|_| {
Rejection::schema(
"[XSD TimeZoneNameType]",
format!(
"{s} is not in the IANA time-zone database.",
s = crate::error::quote(&s)
),
)
})?;
Ok(Self {
name: s.to_owned(),
zone,
})
}
}
display_as_str!(TimeZoneName);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IspDuration(u16);
impl IspDuration {
pub const PT15M: Self = Self(15);
pub fn from_minutes(minutes: u16) -> Result<Self, Rejection> {
if minutes > 0 && 1440 % minutes == 0 {
Ok(Self(minutes))
} else {
Err(Rejection::schema(
"[UFTP §4.2.2 ISP-Duration]",
format!("{minutes} minutes is not an ISP length that divides a day."),
))
}
}
#[must_use]
pub fn minutes(self) -> u16 {
self.0
}
}
impl FromStr for IspDuration {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let minutes = s
.strip_prefix("PT")
.and_then(|m| m.strip_suffix('M'))
.filter(|m| !m.is_empty() && m.bytes().all(|b| b.is_ascii_digit()))
.and_then(|m| m.parse::<u16>().ok())
.ok_or_else(|| {
Rejection::schema(
"[UFTP §4.2.2 ISP-Duration]",
format!(
"{s} is not a duration in whole minutes such as PT15M.",
s = crate::error::quote(&s)
),
)
})?;
Self::from_minutes(minutes)
}
}
impl fmt::Display for IspDuration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PT{}M", self.0)
}
}
macro_rules! xsd_enum {
($(#[$doc:meta])* $name:ident, $rule:literal, { $($(#[$vdoc:meta])* $variant:ident => $text:literal),+ $(,)? }) => {
$(#[$doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum $name {
$($(#[$vdoc])* $variant),+
}
impl $name {
#[must_use]
pub fn as_str(self) -> &'static str {
match self { $(Self::$variant => $text),+ }
}
}
impl FromStr for $name {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
match s {
$($text => Ok(Self::$variant),)+
_ => Err(Rejection::schema($rule, format!(concat!("{} is not one of: ", $($text, " "),+), crate::error::quote(s)))),
}
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
};
}
xsd_enum!(
Role, "[XSD USEF-RoleType]", {
Agr => "AGR",
Cro => "CRO",
Dso => "DSO",
}
);
xsd_enum!(
AcceptedRejected, "[XSD AcceptedRejectedType]", {
Accepted => "Accepted",
Rejected => "Rejected",
}
);
xsd_enum!(
AvailableRequested, "[XSD AvailableRequestedType]", {
Available => "Available",
Requested => "Requested",
}
);
xsd_enum!(
AcceptedDisputed, "[XSD AcceptedDisputedType]", {
Accepted => "Accepted",
Disputed => "Disputed",
}
);
xsd_enum!(
RedispatchBy, "[XSD RedispatchByType]", {
Agr => "AGR",
Dso => "DSO",
}
);
xsd_enum!(
MeteringProfileType, "[XSD MeteringProfileEnum]", {
Power => "Power",
ImportEnergy => "ImportEnergy",
ExportEnergy => "ExportEnergy",
ImportMeterReading => "ImportMeterReading",
ExportMeterReading => "ExportMeterReading",
}
);
impl MeteringProfileType {
#[must_use]
pub fn unit(self) -> MeteringUnit {
match self {
Self::Power => MeteringUnit::Kw,
_ => MeteringUnit::Kwh,
}
}
}
xsd_enum!(
MeteringUnit, "[XSD MeteringUnitType]", {
Kw => "kW",
Kwh => "kWh",
}
);
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Ean(String);
impl Ean {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for Ean {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let b = s.as_bytes();
if b.len() == 19 && matches!(b[0], b'E' | b'e') && b[1..].iter().all(u8::is_ascii_digit) {
Ok(Self(s.to_owned()))
} else {
Err(Rejection::schema(
"[XSD EANType]",
format!(
"{s} is not an EAN: E followed by 18 digits.",
s = crate::error::quote(&s)
),
))
}
}
}
display_as_str!(Ean);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ean_form() {
assert!("E871685900012636543".parse::<Ean>().is_ok());
assert!("e871685900012636543".parse::<Ean>().is_ok());
assert!("ean.871685900012636543".parse::<Ean>().is_err());
assert!("E87168590001263654".parse::<Ean>().is_err());
assert_eq!(MeteringProfileType::Power.unit().as_str(), "kW");
assert_eq!(
MeteringProfileType::ImportMeterReading.unit().as_str(),
"kWh"
);
}
#[test]
fn entity_address_forms() {
assert!("ean.871685900012636543".parse::<EntityAddress>().is_ok());
assert!(
"ea1.2026-11.de.stadtwerk-example:feeder-12"
.parse::<EntityAddress>()
.is_ok()
);
assert!("ean.12345".parse::<EntityAddress>().is_err());
assert!(
"ea1.2026-11.de.example".parse::<EntityAddress>().is_err(),
"needs a colon"
);
assert!("ea1.2026-11.a:b\nc".parse::<EntityAddress>().is_err());
assert!("EAN.871685900012636543".parse::<EntityAddress>().is_err());
}
#[test]
fn domain_is_lower_case() {
assert!("dso.example.com".parse::<InternetDomain>().is_ok());
assert!("my-agr.example".parse::<InternetDomain>().is_ok());
assert!("DSO.example.com".parse::<InternetDomain>().is_err());
assert!("example".parse::<InternetDomain>().is_err());
assert!("-a.example".parse::<InternetDomain>().is_err());
assert!("a.e1".parse::<InternetDomain>().is_err());
}
#[test]
fn uuid_shape_only_hyphenated() {
assert!(
"3F2504E0-4F89-11D3-9A0C-0305E82C3301"
.parse::<MessageUuid>()
.is_ok()
);
assert!(
"3f2504e04f8911d39a0c0305e82c3301"
.parse::<MessageUuid>()
.is_err()
);
assert!(
"{3f2504e0-4f89-11d3-9a0c-0305e82c3301}"
.parse::<MessageUuid>()
.is_err()
);
let a: MessageUuid = "3F2504E0-4F89-11D3-9A0C-0305E82C3301".parse().unwrap();
let b: MessageUuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301".parse().unwrap();
assert_eq!(a, b);
}
#[test]
fn amounts_refuse_extra_digits() {
assert_eq!("12.5000".parse::<Amount>().unwrap().to_string(), "12.5000");
assert!("0.00001".parse::<Amount>().is_err());
assert!("1e3".parse::<Amount>().is_err());
assert!("-3.25".parse::<Amount>().is_ok());
assert!(".5".parse::<Amount>().is_ok());
}
#[test]
fn activation_factor_bounds() {
assert!("0.01".parse::<ActivationFactor>().is_ok());
assert!("1.00".parse::<ActivationFactor>().is_ok());
assert!("0.005".parse::<ActivationFactor>().is_err());
assert!("1.01".parse::<ActivationFactor>().is_err());
assert!("0".parse::<ActivationFactor>().is_err());
assert_eq!(ActivationFactor::FULL.to_string(), "1.00");
}
#[test]
fn time_zone_pattern_and_database() {
assert!("Europe/Amsterdam".parse::<TimeZoneName>().is_ok());
assert!(
"America/Argentina/Buenos_Aires"
.parse::<TimeZoneName>()
.is_ok()
);
assert!(
"Asia/Tokyo".parse::<TimeZoneName>().is_err(),
"SS-09: the XSD pattern excludes Asia"
);
assert!("Europe/Atlantis".parse::<TimeZoneName>().is_err());
}
#[test]
fn isp_duration() {
assert_eq!("PT15M".parse::<IspDuration>().unwrap(), IspDuration::PT15M);
assert!("PT15M30S".parse::<IspDuration>().is_err());
assert!("PT7M".parse::<IspDuration>().is_err());
assert!("PT0M".parse::<IspDuration>().is_err());
assert!("P1D".parse::<IspDuration>().is_err());
}
}