use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::String;
use core::fmt;
use core::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::validate::{Validate, ValidationPath, Violations};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateTime(jiff::Timestamp);
impl DateTime {
pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
#[must_use]
pub const fn from_timestamp(timestamp: jiff::Timestamp) -> Self {
Self(timestamp)
}
#[must_use]
pub const fn timestamp(self) -> jiff::Timestamp {
self.0
}
#[cfg(feature = "std")]
#[must_use]
pub fn now() -> Self {
Self(jiff::Timestamp::now())
}
pub fn parse(text: &str) -> Result<Self, DateTimeError> {
if !matches!(text.as_bytes().get(10), Some(b'T' | b't')) {
return Err(DateTimeError {
input: text.to_owned(),
});
}
jiff::Timestamp::from_str(text)
.map(Self)
.map_err(|_| DateTimeError {
input: text.to_owned(),
})
}
pub fn parse_lenient(text: &str) -> Result<Self, DateTimeError> {
if let Ok(value) = Self::parse(text) {
return Ok(value);
}
let normalized = normalize_datetime(text);
Self::parse(&normalized)
}
}
#[must_use]
pub fn normalize_datetime(text: &str) -> String {
let trimmed = text.trim();
let with_t = match trimmed.find(' ') {
Some(index) if !trimmed.contains('T') => {
let mut s = trimmed.to_owned();
s.replace_range(index..=index, "T");
s
}
_ => trimmed.to_owned(),
};
let has_offset = with_t.ends_with('Z')
|| with_t.ends_with('z')
|| with_t.rfind(['+', '-']).is_some_and(|i| i > 10);
if has_offset {
with_t
} else {
format!("{with_t}Z")
}
}
impl fmt::Display for DateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<jiff::Timestamp> for DateTime {
fn from(value: jiff::Timestamp) -> Self {
Self(value)
}
}
impl From<DateTime> for jiff::Timestamp {
fn from(value: DateTime) -> Self {
value.0
}
}
impl FromStr for DateTime {
type Err = DateTimeError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::parse(text)
}
}
impl Serialize for DateTime {
fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
ser.collect_str(&self.0)
}
}
impl<'de> Deserialize<'de> for DateTime {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
struct Visitor;
impl serde::de::Visitor<'_> for Visitor {
type Value = DateTime;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("an RFC 3339 date-time (`T` separator, explicit offset)")
}
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<DateTime, E> {
DateTime::parse(text).map_err(E::custom)
}
}
de.deserialize_str(Visitor)
}
}
impl Validate for DateTime {
fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DateTimeError {
input: String,
}
impl fmt::Display for DateTimeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?} is not an RFC 3339 date-time (`T` separator, explicit offset)",
self.input
)
}
}
#[cfg(feature = "std")]
impl std::error::Error for DateTimeError {}
pub use crate::decimal::{Decimal, ParseDecimalError};
#[doc(hidden)]
pub mod integer {
use alloc::vec::Vec;
use core::fmt;
use serde::de::{self, Deserialize, Deserializer, Unexpected, Visitor};
struct Int(i32);
struct IntVisitor;
impl Visitor<'_> for IntVisitor {
type Value = Int;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("i32")
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<Int, E> {
i32::try_from(v)
.map(Int)
.map_err(|_| E::invalid_value(Unexpected::Signed(v), &self))
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<Int, E> {
i32::try_from(v)
.map(Int)
.map_err(|_| E::invalid_value(Unexpected::Unsigned(v), &self))
}
#[allow(
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::float_cmp
)]
fn visit_f64<E: de::Error>(self, v: f64) -> Result<Int, E> {
let whole = v.is_finite() && v.abs() < 9.0e15 && (v as i64) as f64 == v;
if !whole {
return Err(E::invalid_type(Unexpected::Float(v), &self));
}
self.visit_i64(v as i64)
}
}
impl<'de> Deserialize<'de> for Int {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(IntVisitor)
}
}
pub fn one<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i32, D::Error> {
Int::deserialize(deserializer).map(|v| v.0)
}
pub fn option<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<i32>, D::Error> {
Option::<Int>::deserialize(deserializer).map(|v| v.map(|v| v.0))
}
pub fn list<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<i32>, D::Error> {
Vec::<Int>::deserialize(deserializer).map(|v| v.into_iter().map(|v| v.0).collect())
}
pub fn option_list<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Vec<i32>>, D::Error> {
Option::<Vec<Int>>::deserialize(deserializer)
.map(|v| v.map(|v| v.into_iter().map(|v| v.0).collect()))
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct CustomData {
#[serde(rename = "vendorId")]
pub vendor_id: String,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl CustomData {
#[must_use]
pub fn new(vendor_id: impl Into<String>) -> Self {
Self {
vendor_id: vendor_id.into(),
extra: serde_json::Map::new(),
}
}
#[must_use]
pub fn with(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
self.extra.insert(key.into(), value.into());
self
}
}
impl Validate for CustomData {
fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
path.push_key("vendorId");
crate::validate::string(&self.vendor_id, None, Some(255), path, out);
path.pop();
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct Identity(String);
pub const IDENTITY_MAX_LEN: usize = 48;
impl Identity {
pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
let value = value.into();
if value.is_empty() {
return Err(IdentityError::Empty);
}
let len = value.chars().count();
if len > IDENTITY_MAX_LEN {
return Err(IdentityError::TooLong(len));
}
if value.contains(':') {
return Err(IdentityError::Colon);
}
if value.chars().any(char::is_control) {
return Err(IdentityError::Control);
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for Identity {
type Err = IdentityError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl<'de> Deserialize<'de> for Identity {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
let value = String::deserialize(de)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IdentityError {
Empty,
TooLong(usize),
Colon,
Control,
}
impl fmt::Display for IdentityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IdentityError::Empty => f.write_str("charging station identity is empty"),
IdentityError::TooLong(len) => {
write!(
f,
"charging station identity is {len} characters, maximum is {IDENTITY_MAX_LEN}"
)
}
IdentityError::Colon => {
f.write_str("charging station identity must not contain ':' (A00.FR.204)")
}
IdentityError::Control => {
f.write_str("charging station identity contains a control character")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for IdentityError {}
pub const MESSAGE_ID_MAX_LEN: usize = 36;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct MessageId(String);
impl MessageId {
pub fn new(value: impl Into<String>) -> Result<Self, MessageIdError> {
let value = value.into();
if value.is_empty() {
return Err(MessageIdError::Empty);
}
let len = value.chars().count();
if len > MESSAGE_ID_MAX_LEN {
return Err(MessageIdError::TooLong(len));
}
Ok(Self(value))
}
#[must_use]
pub fn from_wire(value: &str) -> Self {
Self(value.to_owned())
}
#[must_use]
pub fn is_conforming(&self) -> bool {
!self.0.is_empty() && self.0.chars().count() <= MESSAGE_ID_MAX_LEN
}
#[must_use]
pub fn truncating(value: &str) -> Self {
match value.char_indices().nth(MESSAGE_ID_MAX_LEN) {
Some((cut, _)) => Self(value[..cut].to_owned()),
None => Self(value.to_owned()),
}
}
#[must_use]
pub fn unreadable() -> Self {
Self("-1".to_owned())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Display for MessageId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for MessageId {
type Err = MessageIdError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl<'de> Deserialize<'de> for MessageId {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
let value = String::deserialize(de)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MessageIdError {
Empty,
TooLong(usize),
}
impl fmt::Display for MessageIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MessageIdError::Empty => f.write_str("message id is empty"),
MessageIdError::TooLong(len) => {
write!(
f,
"message id is {len} characters, maximum is {MESSAGE_ID_MAX_LEN}"
)
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for MessageIdError {}
pub trait IdGenerator {
fn next_id(&mut self) -> MessageId;
}
#[cfg(feature = "getrandom")]
#[derive(Clone, Copy, Debug, Default)]
pub struct RandomIds {
counter: u64,
}
#[cfg(feature = "getrandom")]
impl RandomIds {
#[must_use]
pub fn new() -> Self {
Self { counter: 0 }
}
}
#[cfg(feature = "getrandom")]
impl IdGenerator for RandomIds {
fn next_id(&mut self) -> MessageId {
self.counter = self.counter.wrapping_add(1);
MessageId(uuid_v4().unwrap_or_else(|| degraded_uuid(self.counter)))
}
}
#[cfg(feature = "getrandom")]
#[must_use]
pub fn uuid_v4() -> Option<String> {
let mut bytes = [0u8; 16];
getrandom::fill(&mut bytes).ok()?;
bytes[6] = (bytes[6] & 0x0F) | 0x40; bytes[8] = (bytes[8] & 0x3F) | 0x80; Some(hyphenate(bytes))
}
#[cfg(feature = "getrandom")]
#[must_use]
fn degraded_uuid(counter: u64) -> String {
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&counter.to_be_bytes());
bytes[6] = (bytes[6] & 0x0F) | 0x80;
bytes[8] = (bytes[8] & 0x3F) | 0x80;
hyphenate(bytes)
}
#[cfg(feature = "getrandom")]
fn hyphenate(bytes: [u8; 16]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = [0u8; 36];
let mut index = 0;
for (position, byte) in bytes.iter().enumerate() {
if matches!(position, 4 | 6 | 8 | 10) {
out[index] = b'-';
index += 1;
}
out[index] = HEX[usize::from(byte >> 4)];
out[index + 1] = HEX[usize::from(byte & 0x0F)];
index += 2;
}
core::str::from_utf8(&out)
.unwrap_or("00000000-0000-8000-8000-000000000000")
.to_owned()
}
#[derive(Clone, Debug)]
pub struct CounterIds {
prefix: String,
next: u64,
}
impl CounterIds {
#[must_use]
pub fn with_prefix(prefix: impl Into<String>) -> Self {
Self {
prefix: prefix.into(),
next: 0,
}
}
}
impl Default for CounterIds {
fn default() -> Self {
Self::with_prefix("")
}
}
impl IdGenerator for CounterIds {
fn next_id(&mut self) -> MessageId {
let value = self.next;
self.next = self.next.wrapping_add(1);
let mut digits = [0u8; 13];
let mut index = digits.len();
let mut remaining = value;
loop {
index -= 1;
let digit = u8::try_from(remaining % 36).unwrap_or(0);
digits[index] = if digit < 10 {
b'0' + digit
} else {
b'a' + digit - 10
};
remaining /= 36;
if remaining == 0 {
break;
}
}
let suffix = core::str::from_utf8(&digits[index..]).unwrap_or("0");
MessageId::truncating(&format!("{}{suffix}", self.prefix))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_strict_date_time_needs_the_t_separator() {
assert!(DateTime::parse("2026-11-07T12:00:05Z").is_ok());
assert!(DateTime::parse("2026-11-07t12:00:05z").is_ok()); assert!(DateTime::parse("2026-11-07 12:00:05Z").is_err());
assert_eq!(
DateTime::parse_lenient("2026-11-07 12:00:05Z").unwrap(),
DateTime::parse("2026-11-07T12:00:05Z").unwrap()
);
}
#[test]
fn identity_rejects_colon_per_a00_fr_204() {
assert_eq!(Identity::new("cs:1"), Err(IdentityError::Colon));
assert!(Identity::new("CS-0001").is_ok());
assert_eq!(
Identity::new("x".repeat(49)),
Err(IdentityError::TooLong(49))
);
}
#[test]
fn message_id_truncates_to_36_characters() {
let id = MessageId::truncating(&"a".repeat(80));
assert_eq!(id.as_str().chars().count(), 36);
}
#[test]
fn counter_ids_are_unique_and_prefixed() {
let mut ids = CounterIds::with_prefix("lc-");
assert_eq!(ids.next_id().as_str(), "lc-0");
assert_eq!(ids.next_id().as_str(), "lc-1");
for _ in 0..40 {
ids.next_id();
}
assert_eq!(ids.next_id().as_str(), "lc-16");
}
#[cfg(feature = "getrandom")]
#[test]
fn random_ids_are_uuids_and_do_not_repeat() {
let mut ids = RandomIds::new();
let mut seen = std::collections::HashSet::new();
for _ in 0..256 {
let id = ids.next_id();
assert_eq!(id.as_str().len(), 36, "{id}");
assert!(id.is_conforming());
assert_eq!(&id.as_str()[14..15], "4", "version nibble: {id}");
assert!(seen.insert(id.into_string()));
}
}
#[test]
fn datetime_leniency_matches_field_behaviour() {
assert!(DateTime::parse("2024-01-01T10:00:00").is_err());
assert_eq!(
DateTime::parse_lenient("2024-01-01T10:00:00").unwrap(),
DateTime::parse("2024-01-01T10:00:00Z").unwrap()
);
assert_eq!(
DateTime::parse_lenient("2024-01-01 10:00:00").unwrap(),
DateTime::parse("2024-01-01T10:00:00Z").unwrap()
);
assert_eq!(
DateTime::parse_lenient("2024-01-01T10:00:00+02:00").unwrap(),
DateTime::parse("2024-01-01T08:00:00Z").unwrap()
);
}
}