uftp 0.2.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! Typed access to an element's attributes and children, with unknown-name detection.

use std::str::FromStr;

use crate::error::Rejection;
use crate::xml::reader::Element;

/// Reads attributes of one element. `finish` fails on any attribute that was not read.
pub(crate) struct Attrs<'a> {
    el: &'a Element,
    used: Vec<bool>,
    path: String,
}

impl<'a> Attrs<'a> {
    pub(crate) fn new(el: &'a Element, path: impl Into<String>) -> Self {
        Self {
            el,
            used: vec![false; el.attrs.len()],
            path: path.into(),
        }
    }

    pub(crate) fn path(&self) -> &str {
        &self.path
    }

    fn raw(&mut self, name: &str) -> Option<&'a str> {
        let i = self.el.attrs.iter().position(|(k, _)| k == name)?;
        self.used[i] = true;
        Some(self.el.attrs[i].1.as_str())
    }

    pub(crate) fn opt<T: FromStr<Err = Rejection>>(
        &mut self,
        name: &str,
    ) -> Result<Option<T>, Rejection> {
        match self.raw(name) {
            None => Ok(None),
            Some(v) => v
                .parse()
                .map(Some)
                .map_err(|e: Rejection| e.at(format!("{}/@{name}", self.path))),
        }
    }

    pub(crate) fn req<T: FromStr<Err = Rejection>>(&mut self, name: &str) -> Result<T, Rejection> {
        let path = self.path.clone();
        self.opt(name)?.ok_or_else(|| {
            Rejection::schema(
                "[XSD] required attribute",
                format!("The required attribute {name} is missing."),
            )
            .at(format!("{path}/@{name}"))
        })
    }

    pub(crate) fn opt_string(&mut self, name: &str) -> Option<String> {
        self.raw(name).map(str::to_owned)
    }

    pub(crate) fn req_string(&mut self, name: &str) -> Result<String, Rejection> {
        let path = self.path.clone();
        self.opt_string(name).ok_or_else(|| {
            Rejection::schema(
                "[XSD] required attribute",
                format!("The required attribute {name} is missing."),
            )
            .at(format!("{path}/@{name}"))
        })
    }

    pub(crate) fn opt_bool(&mut self, name: &str) -> Result<Option<bool>, Rejection> {
        match self.raw(name) {
            None => Ok(None),
            Some("true" | "1") => Ok(Some(true)),
            Some("false" | "0") => Ok(Some(false)),
            Some(v) => Err(Rejection::schema(
                "[XSD xs:boolean]",
                format!(
                    "{v} is not true, false, 1 or 0.",
                    v = crate::error::quote(&v)
                ),
            )
            .at(format!("{}/@{name}", self.path))),
        }
    }

    pub(crate) fn req_bool(&mut self, name: &str) -> Result<bool, Rejection> {
        let path = self.path.clone();
        self.opt_bool(name)?.ok_or_else(|| {
            Rejection::schema(
                "[XSD] required attribute",
                format!("The required attribute {name} is missing."),
            )
            .at(format!("{path}/@{name}"))
        })
    }

    pub(crate) fn finish(self) -> Result<(), Rejection> {
        if let Some(i) = self.used.iter().position(|u| !u) {
            let name = crate::error::name(&self.el.attrs[i].0);
            return Err(Rejection::schema(
                "[XSD] no undeclared attributes",
                format!(
                    "The attribute {name} is not defined for <{}>.",
                    self.el.name
                ),
            )
            .at(format!("{}/@{name}", self.path)));
        }
        Ok(())
    }
}

/// Integer newtypes for the XSD's integer kinds.
#[derive(Debug, Clone, Copy)]
pub(crate) struct XsInteger(pub i64);

impl FromStr for XsInteger {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
            return Err(Rejection::schema(
                "[XSD xs:integer]",
                format!("{s} is not an integer.", s = crate::error::quote(&s)),
            ));
        }
        s.trim_start_matches('+').parse().map(Self).map_err(|_| {
            Rejection::schema(
                "[XSD xs:integer]",
                format!("{s} is out of range.", s = crate::error::quote(&s)),
            )
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct XsPositive(pub u32);

impl FromStr for XsPositive {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let XsInteger(v) = s.parse::<XsInteger>().map_err(|_| {
            Rejection::schema(
                "[XSD xs:positiveInteger]",
                format!(
                    "{s} is not a positive integer.",
                    s = crate::error::quote(&s)
                ),
            )
        })?;
        u32::try_from(v)
            .ok()
            .filter(|&v| v > 0)
            .map(Self)
            .ok_or_else(|| {
                Rejection::schema(
                    "[XSD xs:positiveInteger]",
                    format!(
                        "{s} is not a positive integer in range.",
                        s = crate::error::quote(&s)
                    ),
                )
            })
    }
}

/// Returns the children of `el`, refusing any child whose name is not in `allowed`.
pub(crate) fn children<'a>(
    el: &'a Element,
    path: &str,
    allowed: &[&str],
) -> Result<&'a [Element], Rejection> {
    if let Some(c) = el
        .children
        .iter()
        .find(|c| !allowed.contains(&c.name.as_str()))
    {
        return Err(Rejection::schema(
            "[XSD] no undeclared elements",
            format!(
                "<{}> is not allowed inside <{}>.",
                crate::error::name(&c.name),
                el.name
            ),
        )
        .at(path.to_owned()));
    }
    Ok(&el.children)
}

/// Fails if `el` has fewer than one child named `name` (`maxOccurs="unbounded"` with the
/// default `minOccurs="1"`).
pub(crate) fn require_one(el: &Element, path: &str, name: &str) -> Result<(), Rejection> {
    if el.children.iter().any(|c| c.name == name) {
        Ok(())
    } else {
        Err(Rejection::schema(
            "[XSD] minOccurs=1",
            format!("<{}> needs at least one <{name}>.", el.name),
        )
        .at(path.to_owned()))
    }
}

/// Fails unless the children of `el` appear in the order of `sequence` (an `xs:sequence`
/// of repeated elements).
pub(crate) fn in_order(el: &Element, path: &str, sequence: &[&str]) -> Result<(), Rejection> {
    let mut at = 0;
    for c in &el.children {
        let i = sequence
            .iter()
            .position(|n| *n == c.name)
            .unwrap_or(sequence.len());
        if i < at {
            return Err(Rejection::schema(
                "[XSD] xs:sequence order",
                format!(
                    "<{}> must come before <{}> inside <{}>.",
                    c.name, sequence[at], el.name
                ),
            )
            .at(path.to_owned()));
        }
        at = i;
    }
    Ok(())
}