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, ViolationKind, 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
176#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
192pub struct Decimal(f64);
193
194impl Decimal {
195 #[must_use]
196 pub const fn new(value: f64) -> Self {
198 Self(value)
199 }
200
201 #[must_use]
202 pub const fn get(self) -> f64 {
204 self.0
205 }
206}
207
208impl From<f64> for Decimal {
209 fn from(value: f64) -> Self {
210 Self(value)
211 }
212}
213
214impl From<f32> for Decimal {
215 fn from(value: f32) -> Self {
216 Self(f64::from(value))
217 }
218}
219
220impl From<i32> for Decimal {
221 fn from(value: i32) -> Self {
222 Self(f64::from(value))
223 }
224}
225
226impl From<Decimal> for f64 {
227 fn from(value: Decimal) -> Self {
228 value.0
229 }
230}
231
232impl fmt::Display for Decimal {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 write!(f, "{}", self.0)
235 }
236}
237
238impl Serialize for Decimal {
239 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
240 if self.0.is_finite() {
241 ser.serialize_f64(self.0)
242 } else {
243 Err(serde::ser::Error::custom("OCPP numbers must be finite"))
244 }
245 }
246}
247
248impl<'de> Deserialize<'de> for Decimal {
249 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
250 f64::deserialize(de).map(Self)
251 }
252}
253
254impl Validate for Decimal {
255 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
256 if !self.0.is_finite() {
257 out.push(
258 path,
259 ViolationKind::Type,
260 "value is not a finite JSON number",
261 );
262 }
263 }
264}
265
266#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
276pub struct CustomData {
277 #[serde(rename = "vendorId")]
279 pub vendor_id: String,
280 #[serde(flatten)]
282 pub extra: serde_json::Map<String, serde_json::Value>,
283}
284
285impl CustomData {
286 #[must_use]
288 pub fn new(vendor_id: impl Into<String>) -> Self {
289 Self {
290 vendor_id: vendor_id.into(),
291 extra: serde_json::Map::new(),
292 }
293 }
294
295 #[must_use]
297 pub fn with(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
298 self.extra.insert(key.into(), value.into());
299 self
300 }
301}
302
303impl Validate for CustomData {
304 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
305 path.push_key("vendorId");
306 crate::validate::string(&self.vendor_id, None, Some(255), path, out);
307 path.pop();
308 }
309}
310
311#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
321#[serde(transparent)]
322pub struct Identity(String);
323
324pub const IDENTITY_MAX_LEN: usize = 48;
326
327impl Identity {
328 pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
330 let value = value.into();
331 if value.is_empty() {
332 return Err(IdentityError::Empty);
333 }
334 let len = value.chars().count();
335 if len > IDENTITY_MAX_LEN {
336 return Err(IdentityError::TooLong(len));
337 }
338 if value.contains(':') {
340 return Err(IdentityError::Colon);
341 }
342 if value.chars().any(char::is_control) {
343 return Err(IdentityError::Control);
344 }
345 Ok(Self(value))
346 }
347
348 #[must_use]
349 pub fn as_str(&self) -> &str {
351 &self.0
352 }
353
354 #[must_use]
356 pub fn into_string(self) -> String {
357 self.0
358 }
359}
360
361impl fmt::Display for Identity {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.write_str(&self.0)
364 }
365}
366
367impl FromStr for Identity {
368 type Err = IdentityError;
369
370 fn from_str(value: &str) -> Result<Self, Self::Err> {
371 Self::new(value)
372 }
373}
374
375impl<'de> Deserialize<'de> for Identity {
376 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
377 let value = String::deserialize(de)?;
378 Self::new(value).map_err(serde::de::Error::custom)
379 }
380}
381
382#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384#[non_exhaustive]
385pub enum IdentityError {
386 Empty,
388 TooLong(usize),
390 Colon,
392 Control,
394}
395
396impl fmt::Display for IdentityError {
397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398 match self {
399 IdentityError::Empty => f.write_str("charging station identity is empty"),
400 IdentityError::TooLong(len) => {
401 write!(
402 f,
403 "charging station identity is {len} characters, maximum is {IDENTITY_MAX_LEN}"
404 )
405 }
406 IdentityError::Colon => {
407 f.write_str("charging station identity must not contain ':' (A00.FR.204)")
408 }
409 IdentityError::Control => {
410 f.write_str("charging station identity contains a control character")
411 }
412 }
413 }
414}
415
416#[cfg(feature = "std")]
417impl std::error::Error for IdentityError {}
418
419pub const MESSAGE_ID_MAX_LEN: usize = 36;
425
426#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
429#[serde(transparent)]
430pub struct MessageId(String);
431
432impl MessageId {
433 pub fn new(value: impl Into<String>) -> Result<Self, MessageIdError> {
435 let value = value.into();
436 if value.is_empty() {
437 return Err(MessageIdError::Empty);
438 }
439 let len = value.chars().count();
440 if len > MESSAGE_ID_MAX_LEN {
441 return Err(MessageIdError::TooLong(len));
442 }
443 Ok(Self(value))
444 }
445
446 #[must_use]
452 pub fn from_wire(value: &str) -> Self {
453 Self(value.to_owned())
454 }
455
456 #[must_use]
458 pub fn is_conforming(&self) -> bool {
459 !self.0.is_empty() && self.0.chars().count() <= MESSAGE_ID_MAX_LEN
460 }
461
462 #[must_use]
466 pub fn truncating(value: &str) -> Self {
467 match value.char_indices().nth(MESSAGE_ID_MAX_LEN) {
468 Some((cut, _)) => Self(value[..cut].to_owned()),
469 None => Self(value.to_owned()),
470 }
471 }
472
473 #[must_use]
476 pub fn unreadable() -> Self {
477 Self("-1".to_owned())
478 }
479
480 #[must_use]
482 pub fn as_str(&self) -> &str {
483 &self.0
484 }
485
486 #[must_use]
488 pub fn into_string(self) -> String {
489 self.0
490 }
491}
492
493impl fmt::Display for MessageId {
494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495 f.write_str(&self.0)
496 }
497}
498
499impl FromStr for MessageId {
500 type Err = MessageIdError;
501
502 fn from_str(value: &str) -> Result<Self, Self::Err> {
503 Self::new(value)
504 }
505}
506
507impl<'de> Deserialize<'de> for MessageId {
508 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
509 let value = String::deserialize(de)?;
510 Self::new(value).map_err(serde::de::Error::custom)
511 }
512}
513
514#[derive(Clone, Copy, Debug, PartialEq, Eq)]
516#[non_exhaustive]
517pub enum MessageIdError {
518 Empty,
520 TooLong(usize),
522}
523
524impl fmt::Display for MessageIdError {
525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526 match self {
527 MessageIdError::Empty => f.write_str("message id is empty"),
528 MessageIdError::TooLong(len) => {
529 write!(
530 f,
531 "message id is {len} characters, maximum is {MESSAGE_ID_MAX_LEN}"
532 )
533 }
534 }
535 }
536}
537
538#[cfg(feature = "std")]
539impl std::error::Error for MessageIdError {}
540
541pub trait IdGenerator {
553 fn next_id(&mut self) -> MessageId;
557}
558
559#[cfg(feature = "getrandom")]
569#[derive(Clone, Copy, Debug, Default)]
570pub struct RandomIds {
571 counter: u64,
572}
573
574#[cfg(feature = "getrandom")]
575impl RandomIds {
576 #[must_use]
578 pub fn new() -> Self {
579 Self { counter: 0 }
580 }
581}
582
583#[cfg(feature = "getrandom")]
584impl IdGenerator for RandomIds {
585 fn next_id(&mut self) -> MessageId {
586 self.counter = self.counter.wrapping_add(1);
587 MessageId(uuid_v4().unwrap_or_else(|| degraded_uuid(self.counter)))
588 }
589}
590
591#[cfg(feature = "getrandom")]
601#[must_use]
602pub fn uuid_v4() -> Option<String> {
603 let mut bytes = [0u8; 16];
604 getrandom::fill(&mut bytes).ok()?;
605 bytes[6] = (bytes[6] & 0x0F) | 0x40; bytes[8] = (bytes[8] & 0x3F) | 0x80; Some(hyphenate(bytes))
608}
609
610#[cfg(feature = "getrandom")]
616#[must_use]
617fn degraded_uuid(counter: u64) -> String {
618 let mut bytes = [0u8; 16];
619 bytes[..8].copy_from_slice(&counter.to_be_bytes());
620 bytes[6] = (bytes[6] & 0x0F) | 0x80;
621 bytes[8] = (bytes[8] & 0x3F) | 0x80;
622 hyphenate(bytes)
623}
624
625#[cfg(feature = "getrandom")]
627fn hyphenate(bytes: [u8; 16]) -> String {
628 const HEX: &[u8; 16] = b"0123456789abcdef";
629 let mut out = [0u8; 36];
630 let mut index = 0;
631 for (position, byte) in bytes.iter().enumerate() {
632 if matches!(position, 4 | 6 | 8 | 10) {
633 out[index] = b'-';
634 index += 1;
635 }
636 out[index] = HEX[usize::from(byte >> 4)];
637 out[index + 1] = HEX[usize::from(byte & 0x0F)];
638 index += 2;
639 }
640 core::str::from_utf8(&out)
642 .unwrap_or("00000000-0000-8000-8000-000000000000")
643 .to_owned()
644}
645
646#[derive(Clone, Debug)]
657pub struct CounterIds {
658 prefix: String,
659 next: u64,
660}
661
662impl CounterIds {
663 #[must_use]
666 pub fn with_prefix(prefix: impl Into<String>) -> Self {
667 Self {
668 prefix: prefix.into(),
669 next: 0,
670 }
671 }
672}
673
674impl Default for CounterIds {
675 fn default() -> Self {
676 Self::with_prefix("")
677 }
678}
679
680impl IdGenerator for CounterIds {
681 fn next_id(&mut self) -> MessageId {
682 let value = self.next;
683 self.next = self.next.wrapping_add(1);
684 let mut digits = [0u8; 13];
685 let mut index = digits.len();
686 let mut remaining = value;
687 loop {
688 index -= 1;
689 let digit = u8::try_from(remaining % 36).unwrap_or(0);
690 digits[index] = if digit < 10 {
691 b'0' + digit
692 } else {
693 b'a' + digit - 10
694 };
695 remaining /= 36;
696 if remaining == 0 {
697 break;
698 }
699 }
700 let suffix = core::str::from_utf8(&digits[index..]).unwrap_or("0");
701 MessageId::truncating(&format!("{}{suffix}", self.prefix))
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708
709 #[test]
710 fn identity_rejects_colon_per_a00_fr_204() {
711 assert_eq!(Identity::new("cs:1"), Err(IdentityError::Colon));
712 assert!(Identity::new("CS-0001").is_ok());
713 assert_eq!(
714 Identity::new("x".repeat(49)),
715 Err(IdentityError::TooLong(49))
716 );
717 }
718
719 #[test]
720 fn message_id_truncates_to_36_characters() {
721 let id = MessageId::truncating(&"a".repeat(80));
722 assert_eq!(id.as_str().chars().count(), 36);
723 }
724
725 #[test]
726 fn counter_ids_are_unique_and_prefixed() {
727 let mut ids = CounterIds::with_prefix("lc-");
728 assert_eq!(ids.next_id().as_str(), "lc-0");
729 assert_eq!(ids.next_id().as_str(), "lc-1");
730 for _ in 0..40 {
731 ids.next_id();
732 }
733 assert_eq!(ids.next_id().as_str(), "lc-16");
734 }
735
736 #[cfg(feature = "getrandom")]
737 #[test]
738 fn random_ids_are_uuids_and_do_not_repeat() {
739 let mut ids = RandomIds::new();
740 let mut seen = std::collections::HashSet::new();
741 for _ in 0..256 {
742 let id = ids.next_id();
743 assert_eq!(id.as_str().len(), 36, "{id}");
744 assert!(id.is_conforming());
745 assert_eq!(&id.as_str()[14..15], "4", "version nibble: {id}");
746 assert!(seen.insert(id.into_string()));
747 }
748 }
749
750 #[test]
751 fn datetime_leniency_matches_field_behaviour() {
752 assert!(DateTime::parse("2024-01-01T10:00:00").is_err());
753 assert_eq!(
754 DateTime::parse_lenient("2024-01-01T10:00:00").unwrap(),
755 DateTime::parse("2024-01-01T10:00:00Z").unwrap()
756 );
757 assert_eq!(
758 DateTime::parse_lenient("2024-01-01 10:00:00").unwrap(),
759 DateTime::parse("2024-01-01T10:00:00Z").unwrap()
760 );
761 assert_eq!(
762 DateTime::parse_lenient("2024-01-01T10:00:00+02:00").unwrap(),
763 DateTime::parse("2024-01-01T08:00:00Z").unwrap()
764 );
765 }
766}