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> {
56 if !matches!(text.as_bytes().get(10), Some(b'T' | b't')) {
57 return Err(DateTimeError {
58 input: text.to_owned(),
59 });
60 }
61 jiff::Timestamp::from_str(text)
62 .map(Self)
63 .map_err(|_| DateTimeError {
64 input: text.to_owned(),
65 })
66 }
67
68 pub fn parse_lenient(text: &str) -> Result<Self, DateTimeError> {
74 if let Ok(value) = Self::parse(text) {
75 return Ok(value);
76 }
77 let normalized = normalize_datetime(text);
78 Self::parse(&normalized)
79 }
80}
81
82#[must_use]
86pub fn normalize_datetime(text: &str) -> String {
87 let trimmed = text.trim();
88 let with_t = match trimmed.find(' ') {
89 Some(index) if !trimmed.contains('T') => {
90 let mut s = trimmed.to_owned();
91 s.replace_range(index..=index, "T");
92 s
93 }
94 _ => trimmed.to_owned(),
95 };
96 let has_offset = with_t.ends_with('Z')
97 || with_t.ends_with('z')
98 || with_t.rfind(['+', '-']).is_some_and(|i| i > 10);
100 if has_offset {
101 with_t
102 } else {
103 format!("{with_t}Z")
104 }
105}
106
107impl fmt::Display for DateTime {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(f, "{}", self.0)
110 }
111}
112
113impl From<jiff::Timestamp> for DateTime {
114 fn from(value: jiff::Timestamp) -> Self {
115 Self(value)
116 }
117}
118
119impl From<DateTime> for jiff::Timestamp {
120 fn from(value: DateTime) -> Self {
121 value.0
122 }
123}
124
125impl FromStr for DateTime {
126 type Err = DateTimeError;
127
128 fn from_str(text: &str) -> Result<Self, Self::Err> {
129 Self::parse(text)
130 }
131}
132
133impl Serialize for DateTime {
134 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
135 ser.collect_str(&self.0)
136 }
137}
138
139impl<'de> Deserialize<'de> for DateTime {
140 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
141 struct Visitor;
142
143 impl serde::de::Visitor<'_> for Visitor {
144 type Value = DateTime;
145
146 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.write_str("an RFC 3339 date-time (`T` separator, explicit offset)")
148 }
149
150 fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<DateTime, E> {
151 DateTime::parse(text).map_err(E::custom)
152 }
153 }
154
155 de.deserialize_str(Visitor)
159 }
160}
161
162impl Validate for DateTime {
163 fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
164}
165
166#[derive(Clone, Debug, PartialEq, Eq)]
168pub struct DateTimeError {
169 input: String,
170}
171
172impl fmt::Display for DateTimeError {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(
175 f,
176 "{:?} is not an RFC 3339 date-time (`T` separator, explicit offset)",
177 self.input
178 )
179 }
180}
181
182#[cfg(feature = "std")]
183impl std::error::Error for DateTimeError {}
184
185pub use crate::decimal::{Decimal, ParseDecimalError};
190
191#[doc(hidden)]
208pub mod integer {
209 use alloc::vec::Vec;
210 use core::fmt;
211
212 use serde::de::{self, Deserialize, Deserializer, Unexpected, Visitor};
213
214 struct Int(i32);
216
217 struct IntVisitor;
218
219 impl Visitor<'_> for IntVisitor {
220 type Value = Int;
221
222 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 f.write_str("i32")
224 }
225
226 fn visit_i64<E: de::Error>(self, v: i64) -> Result<Int, E> {
227 i32::try_from(v)
228 .map(Int)
229 .map_err(|_| E::invalid_value(Unexpected::Signed(v), &self))
230 }
231
232 fn visit_u64<E: de::Error>(self, v: u64) -> Result<Int, E> {
233 i32::try_from(v)
234 .map(Int)
235 .map_err(|_| E::invalid_value(Unexpected::Unsigned(v), &self))
236 }
237
238 #[allow(
239 clippy::cast_possible_truncation,
240 clippy::cast_precision_loss,
241 clippy::float_cmp
242 )]
243 fn visit_f64<E: de::Error>(self, v: f64) -> Result<Int, E> {
244 let whole = v.is_finite() && v.abs() < 9.0e15 && (v as i64) as f64 == v;
247 if !whole {
248 return Err(E::invalid_type(Unexpected::Float(v), &self));
249 }
250 self.visit_i64(v as i64)
251 }
252 }
253
254 impl<'de> Deserialize<'de> for Int {
255 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
256 deserializer.deserialize_any(IntVisitor)
257 }
258 }
259
260 pub fn one<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i32, D::Error> {
262 Int::deserialize(deserializer).map(|v| v.0)
263 }
264
265 pub fn option<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<i32>, D::Error> {
267 Option::<Int>::deserialize(deserializer).map(|v| v.map(|v| v.0))
268 }
269
270 pub fn list<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<i32>, D::Error> {
272 Vec::<Int>::deserialize(deserializer).map(|v| v.into_iter().map(|v| v.0).collect())
273 }
274
275 pub fn option_list<'de, D: Deserializer<'de>>(
277 deserializer: D,
278 ) -> Result<Option<Vec<i32>>, D::Error> {
279 Option::<Vec<Int>>::deserialize(deserializer)
280 .map(|v| v.map(|v| v.into_iter().map(|v| v.0).collect()))
281 }
282}
283
284#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
294pub struct CustomData {
295 #[serde(rename = "vendorId")]
297 pub vendor_id: String,
298 #[serde(flatten)]
300 pub extra: serde_json::Map<String, serde_json::Value>,
301}
302
303impl CustomData {
304 #[must_use]
306 pub fn new(vendor_id: impl Into<String>) -> Self {
307 Self {
308 vendor_id: vendor_id.into(),
309 extra: serde_json::Map::new(),
310 }
311 }
312
313 #[must_use]
315 pub fn with(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
316 self.extra.insert(key.into(), value.into());
317 self
318 }
319}
320
321impl Validate for CustomData {
322 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
323 path.push_key("vendorId");
324 crate::validate::string(&self.vendor_id, None, Some(255), path, out);
325 path.pop();
326 }
327}
328
329#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
339#[serde(transparent)]
340pub struct Identity(String);
341
342pub const IDENTITY_MAX_LEN: usize = 48;
344
345impl Identity {
346 pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
348 let value = value.into();
349 if value.is_empty() {
350 return Err(IdentityError::Empty);
351 }
352 let len = value.chars().count();
353 if len > IDENTITY_MAX_LEN {
354 return Err(IdentityError::TooLong(len));
355 }
356 if value.contains(':') {
358 return Err(IdentityError::Colon);
359 }
360 if value.chars().any(char::is_control) {
361 return Err(IdentityError::Control);
362 }
363 Ok(Self(value))
364 }
365
366 #[must_use]
367 pub fn as_str(&self) -> &str {
369 &self.0
370 }
371
372 #[must_use]
374 pub fn into_string(self) -> String {
375 self.0
376 }
377}
378
379impl fmt::Display for Identity {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 f.write_str(&self.0)
382 }
383}
384
385impl FromStr for Identity {
386 type Err = IdentityError;
387
388 fn from_str(value: &str) -> Result<Self, Self::Err> {
389 Self::new(value)
390 }
391}
392
393impl<'de> Deserialize<'de> for Identity {
394 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
395 let value = String::deserialize(de)?;
396 Self::new(value).map_err(serde::de::Error::custom)
397 }
398}
399
400#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402#[non_exhaustive]
403pub enum IdentityError {
404 Empty,
406 TooLong(usize),
408 Colon,
410 Control,
412}
413
414impl fmt::Display for IdentityError {
415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416 match self {
417 IdentityError::Empty => f.write_str("charging station identity is empty"),
418 IdentityError::TooLong(len) => {
419 write!(
420 f,
421 "charging station identity is {len} characters, maximum is {IDENTITY_MAX_LEN}"
422 )
423 }
424 IdentityError::Colon => {
425 f.write_str("charging station identity must not contain ':' (A00.FR.204)")
426 }
427 IdentityError::Control => {
428 f.write_str("charging station identity contains a control character")
429 }
430 }
431 }
432}
433
434#[cfg(feature = "std")]
435impl std::error::Error for IdentityError {}
436
437pub const MESSAGE_ID_MAX_LEN: usize = 36;
443
444#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
447#[serde(transparent)]
448pub struct MessageId(String);
449
450impl MessageId {
451 pub fn new(value: impl Into<String>) -> Result<Self, MessageIdError> {
453 let value = value.into();
454 if value.is_empty() {
455 return Err(MessageIdError::Empty);
456 }
457 let len = value.chars().count();
458 if len > MESSAGE_ID_MAX_LEN {
459 return Err(MessageIdError::TooLong(len));
460 }
461 Ok(Self(value))
462 }
463
464 #[must_use]
470 pub fn from_wire(value: &str) -> Self {
471 Self(value.to_owned())
472 }
473
474 #[must_use]
476 pub fn is_conforming(&self) -> bool {
477 !self.0.is_empty() && self.0.chars().count() <= MESSAGE_ID_MAX_LEN
478 }
479
480 #[must_use]
484 pub fn truncating(value: &str) -> Self {
485 match value.char_indices().nth(MESSAGE_ID_MAX_LEN) {
486 Some((cut, _)) => Self(value[..cut].to_owned()),
487 None => Self(value.to_owned()),
488 }
489 }
490
491 #[must_use]
494 pub fn unreadable() -> Self {
495 Self("-1".to_owned())
496 }
497
498 #[must_use]
500 pub fn as_str(&self) -> &str {
501 &self.0
502 }
503
504 #[must_use]
506 pub fn into_string(self) -> String {
507 self.0
508 }
509}
510
511impl fmt::Display for MessageId {
512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513 f.write_str(&self.0)
514 }
515}
516
517impl FromStr for MessageId {
518 type Err = MessageIdError;
519
520 fn from_str(value: &str) -> Result<Self, Self::Err> {
521 Self::new(value)
522 }
523}
524
525impl<'de> Deserialize<'de> for MessageId {
526 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
527 let value = String::deserialize(de)?;
528 Self::new(value).map_err(serde::de::Error::custom)
529 }
530}
531
532#[derive(Clone, Copy, Debug, PartialEq, Eq)]
534#[non_exhaustive]
535pub enum MessageIdError {
536 Empty,
538 TooLong(usize),
540}
541
542impl fmt::Display for MessageIdError {
543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544 match self {
545 MessageIdError::Empty => f.write_str("message id is empty"),
546 MessageIdError::TooLong(len) => {
547 write!(
548 f,
549 "message id is {len} characters, maximum is {MESSAGE_ID_MAX_LEN}"
550 )
551 }
552 }
553 }
554}
555
556#[cfg(feature = "std")]
557impl std::error::Error for MessageIdError {}
558
559pub trait IdGenerator {
571 fn next_id(&mut self) -> MessageId;
575}
576
577#[cfg(feature = "getrandom")]
587#[derive(Clone, Copy, Debug, Default)]
588pub struct RandomIds {
589 counter: u64,
590}
591
592#[cfg(feature = "getrandom")]
593impl RandomIds {
594 #[must_use]
596 pub fn new() -> Self {
597 Self { counter: 0 }
598 }
599}
600
601#[cfg(feature = "getrandom")]
602impl IdGenerator for RandomIds {
603 fn next_id(&mut self) -> MessageId {
604 self.counter = self.counter.wrapping_add(1);
605 MessageId(uuid_v4().unwrap_or_else(|| degraded_uuid(self.counter)))
606 }
607}
608
609#[cfg(feature = "getrandom")]
619#[must_use]
620pub fn uuid_v4() -> Option<String> {
621 let mut bytes = [0u8; 16];
622 getrandom::fill(&mut bytes).ok()?;
623 bytes[6] = (bytes[6] & 0x0F) | 0x40; bytes[8] = (bytes[8] & 0x3F) | 0x80; Some(hyphenate(bytes))
626}
627
628#[cfg(feature = "getrandom")]
634#[must_use]
635fn degraded_uuid(counter: u64) -> String {
636 let mut bytes = [0u8; 16];
637 bytes[..8].copy_from_slice(&counter.to_be_bytes());
638 bytes[6] = (bytes[6] & 0x0F) | 0x80;
639 bytes[8] = (bytes[8] & 0x3F) | 0x80;
640 hyphenate(bytes)
641}
642
643#[cfg(feature = "getrandom")]
645fn hyphenate(bytes: [u8; 16]) -> String {
646 const HEX: &[u8; 16] = b"0123456789abcdef";
647 let mut out = [0u8; 36];
648 let mut index = 0;
649 for (position, byte) in bytes.iter().enumerate() {
650 if matches!(position, 4 | 6 | 8 | 10) {
651 out[index] = b'-';
652 index += 1;
653 }
654 out[index] = HEX[usize::from(byte >> 4)];
655 out[index + 1] = HEX[usize::from(byte & 0x0F)];
656 index += 2;
657 }
658 core::str::from_utf8(&out)
660 .unwrap_or("00000000-0000-8000-8000-000000000000")
661 .to_owned()
662}
663
664#[derive(Clone, Debug)]
675pub struct CounterIds {
676 prefix: String,
677 next: u64,
678}
679
680impl CounterIds {
681 #[must_use]
684 pub fn with_prefix(prefix: impl Into<String>) -> Self {
685 Self {
686 prefix: prefix.into(),
687 next: 0,
688 }
689 }
690}
691
692impl Default for CounterIds {
693 fn default() -> Self {
694 Self::with_prefix("")
695 }
696}
697
698impl IdGenerator for CounterIds {
699 fn next_id(&mut self) -> MessageId {
700 let value = self.next;
701 self.next = self.next.wrapping_add(1);
702 let mut digits = [0u8; 13];
703 let mut index = digits.len();
704 let mut remaining = value;
705 loop {
706 index -= 1;
707 let digit = u8::try_from(remaining % 36).unwrap_or(0);
708 digits[index] = if digit < 10 {
709 b'0' + digit
710 } else {
711 b'a' + digit - 10
712 };
713 remaining /= 36;
714 if remaining == 0 {
715 break;
716 }
717 }
718 let suffix = core::str::from_utf8(&digits[index..]).unwrap_or("0");
719 MessageId::truncating(&format!("{}{suffix}", self.prefix))
720 }
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726
727 #[test]
728 fn a_strict_date_time_needs_the_t_separator() {
729 assert!(DateTime::parse("2026-11-07T12:00:05Z").is_ok());
730 assert!(DateTime::parse("2026-11-07t12:00:05z").is_ok()); assert!(DateTime::parse("2026-11-07 12:00:05Z").is_err());
732 assert_eq!(
733 DateTime::parse_lenient("2026-11-07 12:00:05Z").unwrap(),
734 DateTime::parse("2026-11-07T12:00:05Z").unwrap()
735 );
736 }
737
738 #[test]
739 fn identity_rejects_colon_per_a00_fr_204() {
740 assert_eq!(Identity::new("cs:1"), Err(IdentityError::Colon));
741 assert!(Identity::new("CS-0001").is_ok());
742 assert_eq!(
743 Identity::new("x".repeat(49)),
744 Err(IdentityError::TooLong(49))
745 );
746 }
747
748 #[test]
749 fn message_id_truncates_to_36_characters() {
750 let id = MessageId::truncating(&"a".repeat(80));
751 assert_eq!(id.as_str().chars().count(), 36);
752 }
753
754 #[test]
755 fn counter_ids_are_unique_and_prefixed() {
756 let mut ids = CounterIds::with_prefix("lc-");
757 assert_eq!(ids.next_id().as_str(), "lc-0");
758 assert_eq!(ids.next_id().as_str(), "lc-1");
759 for _ in 0..40 {
760 ids.next_id();
761 }
762 assert_eq!(ids.next_id().as_str(), "lc-16");
763 }
764
765 #[cfg(feature = "getrandom")]
766 #[test]
767 fn random_ids_are_uuids_and_do_not_repeat() {
768 let mut ids = RandomIds::new();
769 let mut seen = std::collections::HashSet::new();
770 for _ in 0..256 {
771 let id = ids.next_id();
772 assert_eq!(id.as_str().len(), 36, "{id}");
773 assert!(id.is_conforming());
774 assert_eq!(&id.as_str()[14..15], "4", "version nibble: {id}");
775 assert!(seen.insert(id.into_string()));
776 }
777 }
778
779 #[test]
780 fn datetime_leniency_matches_field_behaviour() {
781 assert!(DateTime::parse("2024-01-01T10:00:00").is_err());
782 assert_eq!(
783 DateTime::parse_lenient("2024-01-01T10:00:00").unwrap(),
784 DateTime::parse("2024-01-01T10:00:00Z").unwrap()
785 );
786 assert_eq!(
787 DateTime::parse_lenient("2024-01-01 10:00:00").unwrap(),
788 DateTime::parse("2024-01-01T10:00:00Z").unwrap()
789 );
790 assert_eq!(
791 DateTime::parse_lenient("2024-01-01T10:00:00+02:00").unwrap(),
792 DateTime::parse("2024-01-01T08:00:00Z").unwrap()
793 );
794 }
795}