use crate::std_shim::{String, ToString};
use core::{fmt, str::FromStr};
use serde::{Deserialize, Deserializer, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum IdentifierError {
#[error("{kind} length {len} is outside the allowed range {min}..={max}")]
Length {
kind: &'static str,
len: usize,
min: usize,
max: usize,
},
#[error("{kind} contains characters outside [a-zA-Z0-9_-]")]
Charset {
kind: &'static str,
},
#[error(
"{kind} must not contain a comma: it is carried in `?targets=` lists, where a comma \
separates one value from the next"
)]
Comma {
kind: &'static str,
},
#[error("{kind} must not be {value:?}")]
Reserved {
kind: &'static str,
value: String,
},
}
const RESERVED: &[&str] = &["null", "undefined", ".", ".."];
fn abridged(value: &str) -> String {
const LIMIT: usize = 64;
match value.char_indices().nth(LIMIT) {
Some((at, _)) => crate::std_shim::format!("{:?}…", &value[..at]),
None => crate::std_shim::format!("{value:?}"),
}
}
macro_rules! constrained_string {
(
$(#[$meta:meta])*
$name:ident, min = $min:expr, max = $max:expr, url_safe = $url_safe:expr
$(, list_safe = $list_safe:expr)?
) => {
$(#[$meta])*
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct $name(String);
impl $name {
pub const MIN_LEN: usize = $min;
pub const MAX_LEN: usize = $max;
pub fn new(value: impl Into<String>) -> Result<Self, IdentifierError> {
let value = value.into();
Self::validate(&value)?;
Ok(Self(value))
}
pub fn validate(value: &str) -> Result<(), IdentifierError> {
let len = value.len();
if !($min..=$max).contains(&len) {
return Err(IdentifierError::Length {
kind: stringify!($name),
len,
min: $min,
max: $max,
});
}
if RESERVED.iter().any(|r| value.eq_ignore_ascii_case(r)) {
return Err(IdentifierError::Reserved {
kind: stringify!($name),
value: value.to_string(),
});
}
if $url_safe
&& !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return Err(IdentifierError::Charset {
kind: stringify!($name),
});
}
$(
if $list_safe && value.contains(',') {
return Err(IdentifierError::Comma {
kind: stringify!($name),
});
}
)?
Ok(())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl FromStr for $name {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
impl TryFrom<String> for $name {
type Error = IdentifierError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
impl AsRef<str> for $name {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", stringify!($name), self.0)
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::validate(&s).map_err(|e| {
serde::de::Error::custom(crate::std_shim::format!(
"{e} (got {})",
abridged(&s)
))
})?;
Ok(Self(s))
}
}
};
}
constrained_string!(
ObjectId,
min = 1,
max = 128,
url_safe = true
);
constrained_string!(
ClientId,
min = 1,
max = 128,
url_safe = false
);
constrained_string!(
Target,
min = 1,
max = 128,
url_safe = false,
list_safe = true
);
constrained_string!(
VenName,
min = 1,
max = 128,
url_safe = false
);
constrained_string!(
ResourceName,
min = 1,
max = 128,
url_safe = false
);
constrained_string!(
ClientName,
min = 1,
max = 128,
url_safe = false
);
constrained_string!(
ProgramName,
min = 1,
max = 128,
url_safe = false
);
impl ResourceName {
pub const AGGREGATED: &'static str = "AGGREGATED_REPORT";
pub fn is_aggregated(&self) -> bool {
self.0 == Self::AGGREGATED
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn object_id_charset_is_enforced() {
assert!(ObjectId::new("abc-123_XYZ").is_ok());
assert!(matches!(
ObjectId::new("has space"),
Err(IdentifierError::Charset { .. })
));
assert!(matches!(
ObjectId::new("slash/es"),
Err(IdentifierError::Charset { .. })
));
}
#[test]
fn lengths_follow_the_schema() {
assert!(ObjectId::new("").is_err());
assert!(ObjectId::new("x".repeat(128)).is_ok());
assert!(ObjectId::new("x".repeat(129)).is_err());
}
#[test]
fn reserved_words_are_rejected_case_insensitively() {
for bad in ["null", "NULL", "..", "."] {
assert!(
matches!(ObjectId::new(bad), Err(IdentifierError::Reserved { .. })),
"{bad} should be reserved"
);
}
}
#[test]
fn targets_allow_punctuation_that_object_ids_do_not() {
assert!(Target::new("871685900000000000").is_ok());
assert!(Target::new("BATTERY-*").is_ok());
assert!(Target::new("zone.a/feeder-3").is_ok());
assert!(matches!(
Target::new("zone-a,north"),
Err(IdentifierError::Comma { .. })
));
assert!(VenName::new("charge-point, bay 2").is_ok());
}
#[test]
fn deserialization_rejects_invalid_values() {
assert!(serde_json::from_str::<ObjectId>("\"ok-1\"").is_ok());
assert!(serde_json::from_str::<ObjectId>("\"not ok\"").is_err());
}
}