use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use super::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Fc {
ST,
MX,
SP,
SV,
CF,
DC,
SG,
SE,
SR,
OR,
BL,
EX,
CO,
US,
MS,
RP,
BR,
LG,
GO,
GS,
XX,
}
impl Fc {
pub fn parse(s: &str) -> Option<Fc> {
Some(match s {
"ST" => Fc::ST,
"MX" => Fc::MX,
"SP" => Fc::SP,
"SV" => Fc::SV,
"CF" => Fc::CF,
"DC" => Fc::DC,
"SG" => Fc::SG,
"SE" => Fc::SE,
"SR" => Fc::SR,
"OR" => Fc::OR,
"BL" => Fc::BL,
"EX" => Fc::EX,
"CO" => Fc::CO,
"US" => Fc::US,
"MS" => Fc::MS,
"RP" => Fc::RP,
"BR" => Fc::BR,
"LG" => Fc::LG,
"GO" => Fc::GO,
"GS" => Fc::GS,
"XX" => Fc::XX,
_ => return None,
})
}
pub const fn is_client_writable(self) -> bool {
match self {
Fc::SP | Fc::SV | Fc::CF | Fc::DC | Fc::SE | Fc::BL | Fc::RP | Fc::BR | Fc::LG | Fc::GO | Fc::GS | Fc::MS | Fc::US => true,
Fc::ST | Fc::MX | Fc::SG | Fc::SR | Fc::OR | Fc::EX | Fc::CO | Fc::XX => false,
}
}
pub const fn as_str(self) -> &'static str {
match self {
Fc::ST => "ST",
Fc::MX => "MX",
Fc::SP => "SP",
Fc::SV => "SV",
Fc::CF => "CF",
Fc::DC => "DC",
Fc::SG => "SG",
Fc::SE => "SE",
Fc::SR => "SR",
Fc::OR => "OR",
Fc::BL => "BL",
Fc::EX => "EX",
Fc::CO => "CO",
Fc::US => "US",
Fc::MS => "MS",
Fc::RP => "RP",
Fc::BR => "BR",
Fc::LG => "LG",
Fc::GO => "GO",
Fc::GS => "GS",
Fc::XX => "XX",
}
}
}
impl fmt::Display for Fc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Selector<'a> {
Component(&'a str),
Index(u32),
IndexRange {
low: u32,
count: u32,
},
AllElements,
}
impl fmt::Display for Selector<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Selector::Component(name) => write!(f, ".{name}"),
Selector::Index(i) => write!(f, "({i})"),
Selector::IndexRange { low, count } => write!(f, "({low}..{})", low.saturating_add(*count).saturating_sub(1)),
Selector::AllElements => f.write_str("(*)"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ObjectReference<'a> {
pub ld: &'a str,
pub ln: &'a str,
pub fc: Option<Fc>,
path: &'a str,
}
impl<'a> ObjectReference<'a> {
pub fn parse(s: &'a str) -> Result<Self, Error> {
let (ld, rest) = s.split_once('/').ok_or(Error::InvalidReference("missing `/` between LD and LN"))?;
if ld.is_empty() || !ld.bytes().all(is_name_byte) {
return Err(Error::InvalidReference("logical device name"));
}
let (ln, fc, path) = if let Some((ln, tail)) = rest.split_once('$') {
let (fc_str, path) = match tail.split_once('$') {
Some((fc, path)) => (fc, path),
None => (tail, ""),
};
let fc = Fc::parse(fc_str).ok_or(Error::InvalidReference("functional constraint"))?;
(ln, Some(fc), path)
} else {
match rest.split_once('.') {
Some((ln, path)) => (ln, None, path),
None => (rest, None, ""),
}
};
if ln.is_empty() || !ln.bytes().all(is_name_byte) {
return Err(Error::InvalidReference("logical node name"));
}
for part in path.split(['.', '$']) {
if path.is_empty() {
break;
}
let (name, index) = split_index(part);
if name.is_empty() || !name.bytes().all(is_name_byte) {
return Err(Error::InvalidReference("data object / attribute name"));
}
if index.is_none() && name.len() != part.len() {
return Err(Error::InvalidReference("array index"));
}
}
Ok(ObjectReference { ld, ln, fc, path })
}
pub fn path(&self) -> impl Iterator<Item = &'a str> + 'a {
self.parts().map(|(name, _)| name).take(self.named_len())
}
fn parts(&self) -> impl Iterator<Item = (&'a str, Option<u32>)> + 'a {
self.path.split(['.', '$']).filter(|s| !s.is_empty()).map(split_index)
}
fn named_len(&self) -> usize {
let mut n = 0usize;
for (_, index) in self.parts() {
n += 1;
if index.is_some() {
break;
}
}
n
}
pub fn selection(&self) -> Vec<Selector<'a>> {
let named = self.named_len();
let mut out = Vec::new();
for (n, (name, index)) in self.parts().enumerate() {
if n + 1 > named {
out.push(Selector::Component(name));
}
if let Some(i) = index {
out.push(Selector::Index(i));
}
}
out
}
pub fn data_object(&self) -> Option<&'a str> {
self.path().next()
}
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.ld.len() + 1 + self.ln.len() + if self.path.is_empty() { 0 } else { 1 + self.path.len() }
}
pub fn fits(&self, edition: crate::common::Edition) -> bool {
self.len() <= edition.max_object_reference_len()
}
}
impl ObjectReference<'_> {
pub fn to_mms(&self, fc: Fc) -> (&str, String) {
self.to_mms_under(self.fc.unwrap_or(fc))
}
pub fn to_mms_under(&self, fc: Fc) -> (&str, String) {
let mut item = String::with_capacity(self.ln.len() + 3 + self.path.len() + 1);
item.push_str(self.ln);
item.push('$');
item.push_str(fc.as_str());
for part in self.path() {
item.push('$');
item.push_str(part);
}
(self.ld, item)
}
}
impl fmt::Display for ObjectReference<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.ld, self.ln)?;
match self.fc {
Some(fc) => {
write!(f, "${fc}")?;
for p in self.path.split(['.', '$']).filter(|s| !s.is_empty()) {
write!(f, "${p}")?;
}
}
None => {
for p in self.path.split(['.', '$']).filter(|s| !s.is_empty()) {
write!(f, ".{p}")?;
}
}
}
Ok(())
}
}
const fn is_name_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
pub fn split_index(part: &str) -> (&str, Option<u32>) {
let Some(open) = part.find('(') else { return (part, None) };
let (name, rest) = part.split_at(open);
match rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).and_then(|d| d.parse::<u32>().ok()) {
Some(index) => (name, Some(index)),
None => (part, None),
}
}
#[cfg(test)]
mod tests {
extern crate alloc;
use super::*;
use alloc::string::ToString;
use alloc::vec::Vec;
#[test]
fn a_controllable_object_can_be_asked_for_its_configuration() {
let co = ObjectReference::parse("IED1LD0/CSWI1$CO$Pos").unwrap();
assert_eq!(co.to_mms(Fc::CF), ("IED1LD0", String::from("CSWI1$CO$Pos")), "the reference's own constraint stands");
assert_eq!(co.to_mms_under(Fc::CF), ("IED1LD0", String::from("CSWI1$CF$Pos")), "…until it is deliberately replaced");
let dotted = ObjectReference::parse("IED1LD0/CSWI1.Pos").unwrap();
assert_eq!(dotted.to_mms(Fc::CF), dotted.to_mms_under(Fc::CF));
}
#[test]
fn the_mms_mapping_puts_the_functional_constraint_after_the_logical_node() {
let r = ObjectReference::parse("IED1LD0/MMXU1.TotW.mag.f").unwrap();
assert_eq!(r.to_mms(Fc::MX), ("IED1LD0", String::from("MMXU1$MX$TotW$mag$f")));
let m = ObjectReference::parse("IED1LD0/LLN0$ST$Mod$stVal").unwrap();
assert_eq!(m.to_mms(Fc::MX), ("IED1LD0", String::from("LLN0$ST$Mod$stVal")));
let ln = ObjectReference::parse("IED1LD0/LLN0").unwrap();
assert_eq!(ln.to_mms(Fc::ST), ("IED1LD0", String::from("LLN0$ST")));
}
#[test]
fn dotted_and_mms_forms() {
let r = ObjectReference::parse("IED1LD0/MMXU1.TotW.mag.f").unwrap();
assert_eq!((r.ld, r.ln, r.fc), ("IED1LD0", "MMXU1", None));
assert_eq!(r.path().collect::<Vec<_>>(), ["TotW", "mag", "f"]);
assert_eq!(r.to_string(), "IED1LD0/MMXU1.TotW.mag.f");
let m = ObjectReference::parse("IED1LD0/LLN0$ST$Mod$stVal").unwrap();
assert_eq!(m.fc, Some(Fc::ST));
assert_eq!(m.data_object(), Some("Mod"));
assert_eq!(m.to_string(), "IED1LD0/LLN0$ST$Mod$stVal");
let ln = ObjectReference::parse("IED1LD0/LLN0").unwrap();
assert_eq!(ln.path().count(), 0);
assert_eq!(ln.len(), 12);
assert!(ln.fits(crate::common::Edition::Ed1));
assert!(ObjectReference::parse("nolyslash").is_err());
assert!(ObjectReference::parse("LD/LN$ZZ$Mod").is_err());
assert!(ObjectReference::parse("LD/LN..x").is_err());
assert!(ObjectReference::parse("L D/LN").is_err());
}
}