flexpool-core 0.3.0

flexpool domain core: exact energy and money units, the Europe/Berlin quarter-hour calendar, portfolio identities and the single quantisation boundary. No I/O, no clock.
Documentation
//! Portfolio identities: slugs `[a-z0-9-]{1,64}` for owners, pools, reserve groups, technical
//! units, assets, slices and products. The portfolio itself — records, references and their
//! validation — lives in `flexpool-portfolio`.

use std::fmt;

use serde::{Deserialize, Serialize};

/// An identifier that is not a slug `[a-z0-9-]{1,64}`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{kind} id {value:?} must match [a-z0-9-]{{1,64}}")]
pub struct IdError {
    kind: &'static str,
    value: String,
}

fn is_slug(value: &str) -> bool {
    (1..=64).contains(&value.len())
        && value
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

macro_rules! id {
    ($(#[$meta:meta])* $name:ident, $kind:literal) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
        #[serde(try_from = "String", into = "String")]
        pub struct $name(String);

        impl $name {
            /// Parses a slug `[a-z0-9-]{1,64}`.
            ///
            /// # Errors
            /// [`IdError`] for anything else.
            pub fn parse(value: impl Into<String>) -> Result<Self, IdError> {
                let value = value.into();
                if is_slug(&value) {
                    Ok(Self(value))
                } else {
                    Err(IdError { kind: $kind, value })
                }
            }

            /// The id as text.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl TryFrom<String> for $name {
            type Error = IdError;
            fn try_from(value: String) -> Result<Self, IdError> {
                Self::parse(value)
            }
        }

        impl From<$name> for String {
            fn from(id: $name) -> String {
                id.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }
    };
}

id!(
    /// A physical asset (battery, inverter, plant, charger).
    AssetId,
    "asset"
);
id!(
    /// A share of an asset's power and energy with its own owner and limits.
    SliceId,
    "slice"
);
id!(
    /// A technical unit (TU) as prequalified with the TSO.
    TechnicalUnitId,
    "technical unit"
);
id!(
    /// A reserve group (RG) of technical units.
    ReserveGroupId,
    "reserve group"
);
id!(
    /// A pool: the unit flexpool markets.
    PoolId,
    "pool"
);
id!(
    /// An asset owner.
    OwnerId,
    "owner"
);
id!(
    /// A market product (e.g. `fcr`, `afrr-pos`, `da`).
    ProductId,
    "product"
);