1use alloc::borrow::ToOwned;
4use alloc::format;
5use alloc::string::String;
6use core::fmt;
7use core::str::FromStr;
8
9use serde::{Deserialize, Serialize};
10
11use crate::validate::{Validate, ValidationPath, Violations};
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub struct DateTime(jiff::Timestamp);
26
27impl DateTime {
28 pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
30
31 #[must_use]
32 pub const fn from_timestamp(timestamp: jiff::Timestamp) -> Self {
34 Self(timestamp)
35 }
36
37 #[must_use]
38 pub const fn timestamp(self) -> jiff::Timestamp {
40 self.0
41 }
42
43 #[cfg(feature = "std")]
45 #[must_use]
46 pub fn now() -> Self {
47 Self(jiff::Timestamp::now())
48 }
49
50 pub fn parse(text: &str) -> Result<Self, DateTimeError> {
52 jiff::Timestamp::from_str(text)
53 .map(Self)
54 .map_err(|_| DateTimeError {
55 input: text.to_owned(),
56 })
57 }
58
59 pub fn parse_lenient(text: &str) -> Result<Self, DateTimeError> {
65 if let Ok(value) = Self::parse(text) {
66 return Ok(value);
67 }
68 let normalized = normalize_datetime(text);
69 Self::parse(&normalized)
70 }
71}
72
73#[must_use]
77pub fn normalize_datetime(text: &str) -> String {
78 let trimmed = text.trim();
79 let with_t = match trimmed.find(' ') {
80 Some(index) if !trimmed.contains('T') => {
81 let mut s = trimmed.to_owned();
82 s.replace_range(index..=index, "T");
83 s
84 }
85 _ => trimmed.to_owned(),
86 };
87 let has_offset = with_t.ends_with('Z')
88 || with_t.ends_with('z')
89 || with_t.rfind(['+', '-']).is_some_and(|i| i > 10);
91 if has_offset {
92 with_t
93 } else {
94 format!("{with_t}Z")
95 }
96}
97
98impl fmt::Display for DateTime {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 write!(f, "{}", self.0)
101 }
102}
103
104impl From<jiff::Timestamp> for DateTime {
105 fn from(value: jiff::Timestamp) -> Self {
106 Self(value)
107 }
108}
109
110impl From<DateTime> for jiff::Timestamp {
111 fn from(value: DateTime) -> Self {
112 value.0
113 }
114}
115
116impl FromStr for DateTime {
117 type Err = DateTimeError;
118
119 fn from_str(text: &str) -> Result<Self, Self::Err> {
120 Self::parse(text)
121 }
122}
123
124impl Serialize for DateTime {
125 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
126 ser.collect_str(&self.0)
127 }
128}
129
130impl<'de> Deserialize<'de> for DateTime {
131 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
132 struct Visitor;
133
134 impl serde::de::Visitor<'_> for Visitor {
135 type Value = DateTime;
136
137 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 f.write_str("an RFC 3339 date-time with an offset")
139 }
140
141 fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<DateTime, E> {
142 DateTime::parse(text).map_err(E::custom)
143 }
144 }
145
146 de.deserialize_str(Visitor)
150 }
151}
152
153impl Validate for DateTime {
154 fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
155}
156
157#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct DateTimeError {
160 input: String,
161}
162
163impl fmt::Display for DateTimeError {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 write!(
166 f,
167 "{:?} is not an RFC 3339 date-time with an offset",
168 self.input
169 )
170 }
171}
172
173#[cfg(feature = "std")]
174impl std::error::Error for DateTimeError {}
175
176pub use crate::decimal::{Decimal, ParseDecimalError};
181
182#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
192pub struct CustomData {
193 #[serde(rename = "vendorId")]
195 pub vendor_id: String,
196 #[serde(flatten)]
198 pub extra: serde_json::Map<String, serde_json::Value>,
199}
200
201impl CustomData {
202 #[must_use]
204 pub fn new(vendor_id: impl Into<String>) -> Self {
205 Self {
206 vendor_id: vendor_id.into(),
207 extra: serde_json::Map::new(),
208 }
209 }
210
211 #[must_use]
213 pub fn with(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
214 self.extra.insert(key.into(), value.into());
215 self
216 }
217}
218
219impl Validate for CustomData {
220 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
221 path.push_key("vendorId");
222 crate::validate::string(&self.vendor_id, None, Some(255), path, out);
223 path.pop();
224 }
225}
226
227#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
237#[serde(transparent)]
238pub struct Identity(String);
239
240pub const IDENTITY_MAX_LEN: usize = 48;
242
243impl Identity {
244 pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
246 let value = value.into();
247 if value.is_empty() {
248 return Err(IdentityError::Empty);
249 }
250 let len = value.chars().count();
251 if len > IDENTITY_MAX_LEN {
252 return Err(IdentityError::TooLong(len));
253 }
254 if value.contains(':') {
256 return Err(IdentityError::Colon);
257 }
258 if value.chars().any(char::is_control) {
259 return Err(IdentityError::Control);
260 }
261 Ok(Self(value))
262 }
263
264 #[must_use]
265 pub fn as_str(&self) -> &str {
267 &self.0
268 }
269
270 #[must_use]
272 pub fn into_string(self) -> String {
273 self.0
274 }
275}
276
277impl fmt::Display for Identity {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 f.write_str(&self.0)
280 }
281}
282
283impl FromStr for Identity {
284 type Err = IdentityError;
285
286 fn from_str(value: &str) -> Result<Self, Self::Err> {
287 Self::new(value)
288 }
289}
290
291impl<'de> Deserialize<'de> for Identity {
292 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
293 let value = String::deserialize(de)?;
294 Self::new(value).map_err(serde::de::Error::custom)
295 }
296}
297
298#[derive(Clone, Copy, Debug, PartialEq, Eq)]
300#[non_exhaustive]
301pub enum IdentityError {
302 Empty,
304 TooLong(usize),
306 Colon,
308 Control,
310}
311
312impl fmt::Display for IdentityError {
313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314 match self {
315 IdentityError::Empty => f.write_str("charging station identity is empty"),
316 IdentityError::TooLong(len) => {
317 write!(
318 f,
319 "charging station identity is {len} characters, maximum is {IDENTITY_MAX_LEN}"
320 )
321 }
322 IdentityError::Colon => {
323 f.write_str("charging station identity must not contain ':' (A00.FR.204)")
324 }
325 IdentityError::Control => {
326 f.write_str("charging station identity contains a control character")
327 }
328 }
329 }
330}
331
332#[cfg(feature = "std")]
333impl std::error::Error for IdentityError {}
334
335pub const MESSAGE_ID_MAX_LEN: usize = 36;
341
342#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
345#[serde(transparent)]
346pub struct MessageId(String);
347
348impl MessageId {
349 pub fn new(value: impl Into<String>) -> Result<Self, MessageIdError> {
351 let value = value.into();
352 if value.is_empty() {
353 return Err(MessageIdError::Empty);
354 }
355 let len = value.chars().count();
356 if len > MESSAGE_ID_MAX_LEN {
357 return Err(MessageIdError::TooLong(len));
358 }
359 Ok(Self(value))
360 }
361
362 #[must_use]
368 pub fn from_wire(value: &str) -> Self {
369 Self(value.to_owned())
370 }
371
372 #[must_use]
374 pub fn is_conforming(&self) -> bool {
375 !self.0.is_empty() && self.0.chars().count() <= MESSAGE_ID_MAX_LEN
376 }
377
378 #[must_use]
382 pub fn truncating(value: &str) -> Self {
383 match value.char_indices().nth(MESSAGE_ID_MAX_LEN) {
384 Some((cut, _)) => Self(value[..cut].to_owned()),
385 None => Self(value.to_owned()),
386 }
387 }
388
389 #[must_use]
392 pub fn unreadable() -> Self {
393 Self("-1".to_owned())
394 }
395
396 #[must_use]
398 pub fn as_str(&self) -> &str {
399 &self.0
400 }
401
402 #[must_use]
404 pub fn into_string(self) -> String {
405 self.0
406 }
407}
408
409impl fmt::Display for MessageId {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 f.write_str(&self.0)
412 }
413}
414
415impl FromStr for MessageId {
416 type Err = MessageIdError;
417
418 fn from_str(value: &str) -> Result<Self, Self::Err> {
419 Self::new(value)
420 }
421}
422
423impl<'de> Deserialize<'de> for MessageId {
424 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
425 let value = String::deserialize(de)?;
426 Self::new(value).map_err(serde::de::Error::custom)
427 }
428}
429
430#[derive(Clone, Copy, Debug, PartialEq, Eq)]
432#[non_exhaustive]
433pub enum MessageIdError {
434 Empty,
436 TooLong(usize),
438}
439
440impl fmt::Display for MessageIdError {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 match self {
443 MessageIdError::Empty => f.write_str("message id is empty"),
444 MessageIdError::TooLong(len) => {
445 write!(
446 f,
447 "message id is {len} characters, maximum is {MESSAGE_ID_MAX_LEN}"
448 )
449 }
450 }
451 }
452}
453
454#[cfg(feature = "std")]
455impl std::error::Error for MessageIdError {}
456
457pub trait IdGenerator {
469 fn next_id(&mut self) -> MessageId;
473}
474
475#[cfg(feature = "getrandom")]
485#[derive(Clone, Copy, Debug, Default)]
486pub struct RandomIds {
487 counter: u64,
488}
489
490#[cfg(feature = "getrandom")]
491impl RandomIds {
492 #[must_use]
494 pub fn new() -> Self {
495 Self { counter: 0 }
496 }
497}
498
499#[cfg(feature = "getrandom")]
500impl IdGenerator for RandomIds {
501 fn next_id(&mut self) -> MessageId {
502 self.counter = self.counter.wrapping_add(1);
503 MessageId(uuid_v4().unwrap_or_else(|| degraded_uuid(self.counter)))
504 }
505}
506
507#[cfg(feature = "getrandom")]
517#[must_use]
518pub fn uuid_v4() -> Option<String> {
519 let mut bytes = [0u8; 16];
520 getrandom::fill(&mut bytes).ok()?;
521 bytes[6] = (bytes[6] & 0x0F) | 0x40; bytes[8] = (bytes[8] & 0x3F) | 0x80; Some(hyphenate(bytes))
524}
525
526#[cfg(feature = "getrandom")]
532#[must_use]
533fn degraded_uuid(counter: u64) -> String {
534 let mut bytes = [0u8; 16];
535 bytes[..8].copy_from_slice(&counter.to_be_bytes());
536 bytes[6] = (bytes[6] & 0x0F) | 0x80;
537 bytes[8] = (bytes[8] & 0x3F) | 0x80;
538 hyphenate(bytes)
539}
540
541#[cfg(feature = "getrandom")]
543fn hyphenate(bytes: [u8; 16]) -> String {
544 const HEX: &[u8; 16] = b"0123456789abcdef";
545 let mut out = [0u8; 36];
546 let mut index = 0;
547 for (position, byte) in bytes.iter().enumerate() {
548 if matches!(position, 4 | 6 | 8 | 10) {
549 out[index] = b'-';
550 index += 1;
551 }
552 out[index] = HEX[usize::from(byte >> 4)];
553 out[index + 1] = HEX[usize::from(byte & 0x0F)];
554 index += 2;
555 }
556 core::str::from_utf8(&out)
558 .unwrap_or("00000000-0000-8000-8000-000000000000")
559 .to_owned()
560}
561
562#[derive(Clone, Debug)]
573pub struct CounterIds {
574 prefix: String,
575 next: u64,
576}
577
578impl CounterIds {
579 #[must_use]
582 pub fn with_prefix(prefix: impl Into<String>) -> Self {
583 Self {
584 prefix: prefix.into(),
585 next: 0,
586 }
587 }
588}
589
590impl Default for CounterIds {
591 fn default() -> Self {
592 Self::with_prefix("")
593 }
594}
595
596impl IdGenerator for CounterIds {
597 fn next_id(&mut self) -> MessageId {
598 let value = self.next;
599 self.next = self.next.wrapping_add(1);
600 let mut digits = [0u8; 13];
601 let mut index = digits.len();
602 let mut remaining = value;
603 loop {
604 index -= 1;
605 let digit = u8::try_from(remaining % 36).unwrap_or(0);
606 digits[index] = if digit < 10 {
607 b'0' + digit
608 } else {
609 b'a' + digit - 10
610 };
611 remaining /= 36;
612 if remaining == 0 {
613 break;
614 }
615 }
616 let suffix = core::str::from_utf8(&digits[index..]).unwrap_or("0");
617 MessageId::truncating(&format!("{}{suffix}", self.prefix))
618 }
619}
620
621#[cfg(test)]
622mod tests {
623 use super::*;
624
625 #[test]
626 fn identity_rejects_colon_per_a00_fr_204() {
627 assert_eq!(Identity::new("cs:1"), Err(IdentityError::Colon));
628 assert!(Identity::new("CS-0001").is_ok());
629 assert_eq!(
630 Identity::new("x".repeat(49)),
631 Err(IdentityError::TooLong(49))
632 );
633 }
634
635 #[test]
636 fn message_id_truncates_to_36_characters() {
637 let id = MessageId::truncating(&"a".repeat(80));
638 assert_eq!(id.as_str().chars().count(), 36);
639 }
640
641 #[test]
642 fn counter_ids_are_unique_and_prefixed() {
643 let mut ids = CounterIds::with_prefix("lc-");
644 assert_eq!(ids.next_id().as_str(), "lc-0");
645 assert_eq!(ids.next_id().as_str(), "lc-1");
646 for _ in 0..40 {
647 ids.next_id();
648 }
649 assert_eq!(ids.next_id().as_str(), "lc-16");
650 }
651
652 #[cfg(feature = "getrandom")]
653 #[test]
654 fn random_ids_are_uuids_and_do_not_repeat() {
655 let mut ids = RandomIds::new();
656 let mut seen = std::collections::HashSet::new();
657 for _ in 0..256 {
658 let id = ids.next_id();
659 assert_eq!(id.as_str().len(), 36, "{id}");
660 assert!(id.is_conforming());
661 assert_eq!(&id.as_str()[14..15], "4", "version nibble: {id}");
662 assert!(seen.insert(id.into_string()));
663 }
664 }
665
666 #[test]
667 fn datetime_leniency_matches_field_behaviour() {
668 assert!(DateTime::parse("2024-01-01T10:00:00").is_err());
669 assert_eq!(
670 DateTime::parse_lenient("2024-01-01T10:00:00").unwrap(),
671 DateTime::parse("2024-01-01T10:00:00Z").unwrap()
672 );
673 assert_eq!(
674 DateTime::parse_lenient("2024-01-01 10:00:00").unwrap(),
675 DateTime::parse("2024-01-01T10:00:00Z").unwrap()
676 );
677 assert_eq!(
678 DateTime::parse_lenient("2024-01-01T10:00:00+02:00").unwrap(),
679 DateTime::parse("2024-01-01T08:00:00Z").unwrap()
680 );
681 }
682}