1use core::fmt;
58use core::hash::{Hash, Hasher};
59use core::str::FromStr;
60
61use serde::{Deserialize, Deserializer, Serialize, Serializer};
62
63use super::validate::{Validate, Validator, ViolationCode};
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
67pub enum IdStandard {
68 Iso,
70 Din,
72 Either,
79}
80
81impl IdStandard {
82 #[must_use]
84 pub const fn as_str(self) -> &'static str {
85 match self {
86 Self::Iso => "ISO",
87 Self::Din => "DIN",
88 Self::Either => "ISO/DIN",
89 }
90 }
91}
92
93impl fmt::Display for IdStandard {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 f.write_str(self.as_str())
96 }
97}
98
99#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
101#[error("{value:?} is not a valid {type_name}: {reason}")]
102pub struct IdError {
103 type_name: &'static str,
104 value: String,
105 reason: &'static str,
106}
107
108impl IdError {
109 fn new(type_name: &'static str, value: &str, reason: &'static str) -> Self {
110 Self { type_name, value: value.to_owned(), reason }
111 }
112
113 #[must_use]
115 pub const fn type_name(&self) -> &'static str {
116 self.type_name
117 }
118
119 #[must_use]
121 pub fn value(&self) -> &str {
122 &self.value
123 }
124}
125
126fn significant_bytes(s: &str) -> impl Iterator<Item = u8> + '_ {
136 s.strip_prefix('+').unwrap_or(s).bytes().filter(|c| !is_separator(*c)).map(|c| c.to_ascii_uppercase())
137}
138
139fn semantic_eq(a: &str, b: &str) -> bool {
142 significant_bytes(a).eq(significant_bytes(b))
143}
144
145fn semantic_cmp(a: &str, b: &str) -> core::cmp::Ordering {
149 significant_bytes(a).cmp(significant_bytes(b))
150}
151
152fn semantic_hash<H: Hasher>(s: &str, state: &mut H) {
153 for c in significant_bytes(s) {
154 state.write_u8(c);
155 }
156 state.write_u8(0xff);
157}
158
159fn case_insensitive_cmp(a: &str, b: &str) -> core::cmp::Ordering {
161 a.bytes().map(|c| c.to_ascii_uppercase()).cmp(b.bytes().map(|c| c.to_ascii_uppercase()))
162}
163
164const fn is_separator(c: u8) -> bool {
165 matches!(c, b'*' | b'-')
166}
167
168macro_rules! oicp_id {
176 (
177 $(#[$meta:meta])*
178 $name:ident, $type_name:literal
179 ) => {
180 $(#[$meta])*
181 #[derive(Clone, Debug)]
182 pub struct $name {
183 raw: String,
185 standard: IdStandard,
186 }
187
188 impl $name {
189 pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
195 let raw = value.into();
196 let standard = Self::classify(&raw)?;
197 Ok(Self { raw, standard })
198 }
199
200 #[must_use]
206 pub fn new_unchecked(value: impl Into<String>) -> Self {
207 let raw = value.into();
208 let standard = Self::classify(&raw).unwrap_or(if raw.starts_with('+') || raw.starts_with(|c: char| c.is_ascii_digit()) {
209 IdStandard::Din
210 } else {
211 IdStandard::Iso
212 });
213 Self { raw, standard }
214 }
215
216 #[must_use]
218 pub fn as_str(&self) -> &str {
219 &self.raw
220 }
221
222 #[must_use]
224 pub const fn standard(&self) -> IdStandard {
225 self.standard
226 }
227
228 #[must_use]
233 pub fn canonical(&self) -> String {
234 significant_bytes(&self.raw).map(char::from).collect()
235 }
236
237 #[must_use]
239 pub fn is_well_formed(&self) -> bool {
240 Self::classify(&self.raw).is_ok()
241 }
242 }
243
244 impl fmt::Display for $name {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 f.write_str(&self.raw)
247 }
248 }
249
250 impl PartialEq for $name {
255 fn eq(&self, other: &Self) -> bool {
256 semantic_eq(&self.raw, &other.raw)
257 }
258 }
259 impl Eq for $name {}
260
261 impl Hash for $name {
262 fn hash<H: Hasher>(&self, state: &mut H) {
263 semantic_hash(&self.raw, state);
264 }
265 }
266
267 impl PartialOrd for $name {
268 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
269 Some(self.cmp(other))
270 }
271 }
272
273 impl Ord for $name {
274 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
275 semantic_cmp(&self.raw, &other.raw)
276 }
277 }
278
279 impl FromStr for $name {
280 type Err = IdError;
281 fn from_str(s: &str) -> Result<Self, Self::Err> {
282 Self::new(s)
283 }
284 }
285
286 impl Validate for $name {
287 fn validate_in(&self, v: &mut Validator) {
288 if let Err(e) = Self::classify(&self.raw) {
289 v.report(ViolationCode::PatternMismatch, e.to_string());
290 }
291 }
292 }
293
294 impl Serialize for $name {
295 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
296 s.serialize_str(&self.raw)
297 }
298 }
299
300 impl<'de> Deserialize<'de> for $name {
301 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
302 Ok(Self::new_unchecked(String::deserialize(d)?))
305 }
306 }
307
308 #[cfg(feature = "schema")]
309 impl schemars::JsonSchema for $name {
310 fn schema_name() -> std::borrow::Cow<'static, str> { $type_name.into() }
311 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
312 schemars::json_schema!({ "type": "string" })
313 }
314 }
315 };
316}
317
318oicp_id! {
321 EvseId, "EvseID"
329}
330
331impl EvseId {
332 fn classify(s: &str) -> Result<IdStandard, IdError> {
333 if let Ok(()) = Self::check_iso(s) {
334 return Ok(IdStandard::Iso);
335 }
336 Self::check_din(s).map(|()| IdStandard::Din)
337 }
338
339 fn check_iso(s: &str) -> Result<(), IdError> {
341 let b = s.as_bytes();
342 let mut i = 0;
343 let err = |reason| Err(IdError::new("EvseID", s, reason));
344 if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
345 return err("an ISO EvseID starts with a two-letter country code");
346 }
347 i += 2;
348 if b.get(i) == Some(&b'*') {
349 i += 1;
350 }
351 if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
352 return err("the operator part of an ISO EvseID is three alphanumeric characters");
353 }
354 i += 3;
355 if b.get(i) == Some(&b'*') {
356 i += 1;
357 }
358 if b.get(i).is_none_or(|c| !c.eq_ignore_ascii_case(&b'E')) {
359 return err("an ISO EvseID has an 'E' after the operator part");
360 }
361 i += 1;
362 let rest = &b[i..];
363 if rest.is_empty() || rest.len() > 30 {
364 return err("the instance part of an ISO EvseID is 1 to 30 characters");
365 }
366 if !rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'*') {
367 return err("the instance part of an ISO EvseID is alphanumeric with optional '*' separators");
368 }
369 Ok(())
370 }
371
372 fn check_din(s: &str) -> Result<(), IdError> {
374 let err = |reason| Err(IdError::new("EvseID", s, reason));
375 let body = s.strip_prefix('+').unwrap_or(s);
376 let mut parts = body.splitn(3, '*');
377 let (Some(country), Some(operator), Some(instance)) = (parts.next(), parts.next(), parts.next())
378 else {
379 return err("a DIN EvseID is country*operator*instance, separated by mandatory '*'");
380 };
381 if country.is_empty() || country.len() > 3 || !country.bytes().all(|c| c.is_ascii_digit()) {
382 return err("the country code of a DIN EvseID is 1 to 3 digits (ITU-T E.164)");
383 }
384 if operator.len() != 3 || !operator.bytes().all(|c| c.is_ascii_digit()) {
385 return err("the operator part of a DIN EvseID is exactly three digits");
386 }
387 if instance.is_empty()
388 || instance.len() > 32
389 || !instance.bytes().all(|c| c.is_ascii_digit() || c == b'*')
390 {
391 return err("the instance part of a DIN EvseID is 1 to 32 digits with optional '*' separators");
392 }
393 Ok(())
394 }
395
396 #[must_use]
400 pub fn country(&self) -> &str {
401 match self.standard() {
402 IdStandard::Din => {
403 let body = self.as_str().strip_prefix('+').unwrap_or(self.as_str());
404 body.split('*').next().unwrap_or("")
405 }
406 IdStandard::Iso | IdStandard::Either => &self.as_str()[..2],
408 }
409 }
410
411 #[must_use]
416 pub fn operator_id(&self) -> OperatorId {
417 let raw = match self.standard() {
418 IdStandard::Iso | IdStandard::Either => {
419 let b = self.as_str().as_bytes();
421 let mut end = 2;
422 if b.get(end) == Some(&b'*') {
423 end += 1;
424 }
425 end += 3;
426 &self.as_str()[..end]
427 }
428 IdStandard::Din => {
429 let s = self.as_str();
430 let plus = usize::from(s.starts_with('+'));
431 let body = &s[plus..];
432 match body.match_indices('*').nth(1) {
433 Some((idx, _)) => &s[..plus + idx],
434 None => s,
435 }
436 }
437 };
438 OperatorId::new_unchecked(raw)
439 }
440}
441
442oicp_id! {
445 EvcoId, "EvcoID"
454}
455
456impl EvcoId {
457 fn classify(s: &str) -> Result<IdStandard, IdError> {
458 if Self::check_iso(s).is_ok() {
459 return Ok(IdStandard::Iso);
460 }
461 Self::check_din(s).map(|()| IdStandard::Din)
462 }
463
464 fn check_iso(s: &str) -> Result<(), IdError> {
466 let b = s.as_bytes();
467 let err = |reason| Err(IdError::new("EvcoID", s, reason));
468 let mut i = 0;
469 if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
470 return err("an ISO EvcoID starts with a two-letter country code");
471 }
472 i += 2;
473 if b.get(i) == Some(&b'-') {
474 i += 1;
475 }
476 if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
477 return err("the provider part of an ISO EvcoID is three alphanumeric characters");
478 }
479 i += 3;
480 if b.get(i) == Some(&b'-') {
481 i += 1;
482 }
483 if b.get(i).is_none_or(|c| !c.eq_ignore_ascii_case(&b'C')) {
484 return err("an ISO EvcoID prefixes its instance part with 'C'");
485 }
486 i += 1;
487 if b.len() < i + 8 || !b[i..i + 8].iter().all(u8::is_ascii_alphanumeric) {
488 return err("the instance part of an ISO EvcoID is exactly eight alphanumeric characters");
489 }
490 i += 8;
491 if b.get(i) == Some(&b'-') {
492 i += 1;
493 }
494 if b.len() != i + 1 || !b[i].is_ascii_alphanumeric() {
495 return err("an ISO EvcoID ends with a single check character");
496 }
497 Ok(())
498 }
499
500 fn check_din(s: &str) -> Result<(), IdError> {
502 let b = s.as_bytes();
503 let err = |reason| Err(IdError::new("EvcoID", s, reason));
504 let mut i = 0;
505 if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
506 return err("a DIN EvcoID starts with a two-letter country code");
507 }
508 i += 2;
509 if b.get(i).is_some_and(|c| is_separator(*c)) {
510 i += 1;
511 }
512 if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
513 return err("the provider part of a DIN EvcoID is three alphanumeric characters");
514 }
515 i += 3;
516 if b.get(i).is_some_and(|c| is_separator(*c)) {
517 i += 1;
518 }
519 if b.len() < i + 6 || !b[i..i + 6].iter().all(u8::is_ascii_alphanumeric) {
520 return err("the instance part of a DIN EvcoID is exactly six alphanumeric characters");
521 }
522 i += 6;
523 if b.get(i).is_some_and(|c| is_separator(*c)) {
524 i += 1;
525 }
526 if b.len() != i + 1 || !(b[i].is_ascii_digit() || b[i].eq_ignore_ascii_case(&b'X')) {
527 return err("a DIN EvcoID ends with a check digit or 'X'");
528 }
529 Ok(())
530 }
531
532 #[must_use]
537 pub fn provider_id(&self) -> ProviderId {
538 let b = self.as_str().as_bytes();
539 let mut end = 2;
540 if b.get(end).is_some_and(|c| is_separator(*c)) {
541 end += 1;
542 }
543 end = (end + 3).min(self.as_str().len());
544 ProviderId::new_unchecked(&self.as_str()[..end])
545 }
546}
547
548oicp_id! {
551 OperatorId, "OperatorID"
560}
561
562impl OperatorId {
563 fn classify(s: &str) -> Result<IdStandard, IdError> {
564 let b = s.as_bytes();
565 let err = |reason| Err(IdError::new("OperatorID", s, reason));
566 if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1].is_ascii_alphabetic() {
568 let rest = if b.get(2) == Some(&b'*') { &b[3..] } else { &b[2..] };
569 if rest.len() == 3 && rest.iter().all(u8::is_ascii_alphanumeric) {
570 return Ok(IdStandard::Iso);
571 }
572 return err("an ISO OperatorID is a two-letter country code and three alphanumeric characters");
573 }
574 let body = s.strip_prefix('+').unwrap_or(s);
576 let mut parts = body.splitn(2, '*');
577 let (Some(country), Some(operator)) = (parts.next(), parts.next()) else {
578 return err("a DIN OperatorID is country*operator with a mandatory '*'");
579 };
580 if country.is_empty() || country.len() > 3 || !country.bytes().all(|c| c.is_ascii_digit()) {
581 return err("the country code of a DIN OperatorID is 1 to 3 digits");
582 }
583 if operator.len() != 3 || !operator.bytes().all(|c| c.is_ascii_digit()) {
584 return err("the operator part of a DIN OperatorID is exactly three digits");
585 }
586 Ok(IdStandard::Din)
587 }
588
589 #[must_use]
591 pub fn country(&self) -> &str {
592 match self.standard() {
593 IdStandard::Din => {
594 let body = self.as_str().strip_prefix('+').unwrap_or(self.as_str());
595 body.split('*').next().unwrap_or("")
596 }
597 IdStandard::Iso | IdStandard::Either => &self.as_str()[..2],
599 }
600 }
601}
602
603oicp_id! {
606 ProviderId, "ProviderID"
615}
616
617impl ProviderId {
618 fn classify(s: &str) -> Result<IdStandard, IdError> {
619 let b = s.as_bytes();
620 let err = |reason| Err(IdError::new("ProviderID", s, reason));
621 if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
622 return err("a ProviderID starts with a two-letter country code");
623 }
624 let (rest, separated) =
625 if b.get(2).is_some_and(|c| is_separator(*c)) { (&b[3..], true) } else { (&b[2..], false) };
626 if rest.len() != 3 || !rest.iter().all(u8::is_ascii_alphanumeric) {
627 return err("a ProviderID is a two-letter country code and three alphanumeric characters");
628 }
629 let _ = separated;
633 Ok(IdStandard::Either)
634 }
635
636 #[must_use]
638 pub fn country(&self) -> &str {
639 &self.as_str()[..2]
640 }
641}
642
643oicp_id! {
646 ChargingPoolId, "ChargingPoolID"
653}
654
655impl ChargingPoolId {
656 fn classify(s: &str) -> Result<IdStandard, IdError> {
657 let b = s.as_bytes();
658 let err = |reason| Err(IdError::new("ChargingPoolID", s, reason));
659 let mut i = 0;
660 if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
661 return err("a ChargingPoolID starts with a two-letter country code");
662 }
663 i += 2;
664 if b.get(i) == Some(&b'*') {
665 i += 1;
666 }
667 if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
668 return err("the operator part of a ChargingPoolID is three alphanumeric characters");
669 }
670 i += 3;
671 if b.get(i) == Some(&b'*') {
672 i += 1;
673 }
674 if b.get(i).is_none_or(|c| !c.eq_ignore_ascii_case(&b'P')) {
675 return err("a ChargingPoolID has a 'P' after the operator part, marking it as a pool");
676 }
677 i += 1;
678 let rest = &b[i..];
679 if rest.is_empty() || rest.len() > 30 {
680 return err("the pool part of a ChargingPoolID is 1 to 30 characters");
681 }
682 if !rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'*') {
683 return err("the pool part of a ChargingPoolID is alphanumeric with optional '*' separators");
684 }
685 Ok(IdStandard::Iso)
686 }
687}
688
689#[derive(Clone, Debug)]
699pub struct SessionId(String);
700
701impl SessionId {
702 pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
708 let raw = value.into();
709 Self::check(&raw)?;
710 Ok(Self(raw))
711 }
712
713 #[must_use]
715 pub fn new_unchecked(value: impl Into<String>) -> Self {
716 Self(value.into())
717 }
718
719 #[must_use]
721 pub fn as_str(&self) -> &str {
722 &self.0
723 }
724
725 #[must_use]
727 pub fn is_well_formed(&self) -> bool {
728 Self::check(&self.0).is_ok()
729 }
730
731 fn check(s: &str) -> Result<(), IdError> {
732 let err = |reason| Err(IdError::new("SessionID", s, reason));
733 let groups: Vec<&str> = s.split('-').collect();
734 if groups.len() != 5 {
735 return err("a SessionID has five '-'-separated groups");
736 }
737 let expected = [8usize, 4, 4, 4, 12];
738 for (group, want) in groups.iter().zip(expected) {
739 if group.len() != want || !group.bytes().all(|c| c.is_ascii_alphanumeric()) {
740 return err("a SessionID is 8-4-4-4-12 alphanumeric characters");
741 }
742 }
743 Ok(())
744 }
745}
746
747impl fmt::Display for SessionId {
748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749 f.write_str(&self.0)
750 }
751}
752
753impl PartialEq for SessionId {
754 fn eq(&self, other: &Self) -> bool {
755 self.0.eq_ignore_ascii_case(&other.0)
756 }
757}
758impl Eq for SessionId {}
759
760impl Hash for SessionId {
761 fn hash<H: Hasher>(&self, state: &mut H) {
762 for c in self.0.bytes() {
763 state.write_u8(c.to_ascii_uppercase());
764 }
765 }
766}
767
768impl PartialOrd for SessionId {
769 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
770 Some(self.cmp(other))
771 }
772}
773
774impl Ord for SessionId {
775 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
776 case_insensitive_cmp(&self.0, &other.0)
777 }
778}
779
780impl FromStr for SessionId {
781 type Err = IdError;
782 fn from_str(s: &str) -> Result<Self, Self::Err> {
783 Self::new(s)
784 }
785}
786
787impl Validate for SessionId {
788 fn validate_in(&self, v: &mut Validator) {
789 if let Err(e) = Self::check(&self.0) {
790 v.report(ViolationCode::PatternMismatch, e.to_string());
791 }
792 }
793}
794
795impl Serialize for SessionId {
796 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
797 s.serialize_str(&self.0)
798 }
799}
800
801impl<'de> Deserialize<'de> for SessionId {
802 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
803 Ok(Self::new_unchecked(String::deserialize(d)?))
804 }
805}
806
807#[cfg(feature = "schema")]
808impl schemars::JsonSchema for SessionId {
809 fn schema_name() -> std::borrow::Cow<'static, str> {
810 "SessionID".into()
811 }
812 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
813 schemars::json_schema!({ "type": "string" })
814 }
815}
816
817#[derive(Clone, Debug)]
835pub struct Uid(String);
836
837impl Uid {
838 pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
844 let raw = value.into();
845 Self::check(&raw)?;
846 Ok(Self(raw))
847 }
848
849 #[must_use]
851 pub fn new_unchecked(value: impl Into<String>) -> Self {
852 Self(value.into())
853 }
854
855 #[must_use]
857 pub fn as_str(&self) -> &str {
858 &self.0
859 }
860
861 #[must_use]
863 pub fn canonical(&self) -> String {
864 self.0.to_ascii_uppercase()
865 }
866
867 #[must_use]
869 pub fn is_well_formed(&self) -> bool {
870 Self::check(&self.0).is_ok()
871 }
872
873 fn check(s: &str) -> Result<(), IdError> {
874 if !matches!(s.len(), 8 | 14 | 20) {
875 return Err(IdError::new("UID", s, "an RFID UID is 8, 14 or 20 characters"));
876 }
877 if !s.bytes().all(|c| c.is_ascii_hexdigit()) {
878 return Err(IdError::new("UID", s, "an RFID UID is hexadecimal"));
879 }
880 if s.bytes().any(|c| c.is_ascii_lowercase()) {
885 return Err(IdError::new(
886 "UID",
887 s,
888 "the specification writes an RFID UID in uppercase hexadecimal",
889 ));
890 }
891 Ok(())
892 }
893}
894
895impl fmt::Display for Uid {
896 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897 f.write_str(&self.0)
898 }
899}
900
901impl PartialEq for Uid {
902 fn eq(&self, other: &Self) -> bool {
903 self.0.eq_ignore_ascii_case(&other.0)
904 }
905}
906impl Eq for Uid {}
907
908impl Hash for Uid {
909 fn hash<H: Hasher>(&self, state: &mut H) {
910 for c in self.0.bytes() {
911 state.write_u8(c.to_ascii_uppercase());
912 }
913 }
914}
915
916impl PartialOrd for Uid {
917 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
918 Some(self.cmp(other))
919 }
920}
921
922impl Ord for Uid {
923 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
924 case_insensitive_cmp(&self.0, &other.0)
925 }
926}
927
928impl FromStr for Uid {
929 type Err = IdError;
930 fn from_str(s: &str) -> Result<Self, Self::Err> {
931 Self::new(s)
932 }
933}
934
935impl Validate for Uid {
936 fn validate_in(&self, v: &mut Validator) {
937 if let Err(e) = Self::check(&self.0) {
938 v.report(ViolationCode::PatternMismatch, e.to_string());
939 }
940 }
941}
942
943impl Serialize for Uid {
944 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
945 s.serialize_str(&self.0)
946 }
947}
948
949impl<'de> Deserialize<'de> for Uid {
950 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
951 Ok(Self::new_unchecked(String::deserialize(d)?))
952 }
953}
954
955#[cfg(feature = "schema")]
956impl schemars::JsonSchema for Uid {
957 fn schema_name() -> std::borrow::Cow<'static, str> {
958 "UID".into()
959 }
960 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
961 schemars::json_schema!({ "type": "string" })
962 }
963}
964
965#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
975pub enum ProviderIdOrAll {
976 One(ProviderId),
978 All,
980}
981
982impl ProviderIdOrAll {
983 #[must_use]
985 pub fn as_str(&self) -> &str {
986 match self {
987 Self::One(id) => id.as_str(),
988 Self::All => "*",
989 }
990 }
991
992 #[must_use]
994 pub const fn is_all(&self) -> bool {
995 matches!(self, Self::All)
996 }
997}
998
999impl fmt::Display for ProviderIdOrAll {
1000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 f.write_str(self.as_str())
1002 }
1003}
1004
1005impl From<ProviderId> for ProviderIdOrAll {
1006 fn from(id: ProviderId) -> Self {
1007 Self::One(id)
1008 }
1009}
1010
1011impl FromStr for ProviderIdOrAll {
1012 type Err = IdError;
1013 fn from_str(s: &str) -> Result<Self, Self::Err> {
1014 if s == "*" { Ok(Self::All) } else { ProviderId::new(s).map(Self::One) }
1015 }
1016}
1017
1018impl Validate for ProviderIdOrAll {
1019 fn validate_in(&self, v: &mut Validator) {
1020 if let Self::One(id) = self {
1021 id.validate_in(v);
1022 }
1023 }
1024}
1025
1026impl Serialize for ProviderIdOrAll {
1027 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1028 s.serialize_str(self.as_str())
1029 }
1030}
1031
1032impl<'de> Deserialize<'de> for ProviderIdOrAll {
1033 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1034 let s = String::deserialize(d)?;
1035 Ok(if s == "*" { Self::All } else { Self::One(ProviderId::new_unchecked(s)) })
1036 }
1037}
1038
1039#[cfg(feature = "schema")]
1040impl schemars::JsonSchema for ProviderIdOrAll {
1041 fn schema_name() -> std::borrow::Cow<'static, str> {
1042 "ProviderIDAsterisk".into()
1043 }
1044 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
1045 schemars::json_schema!({ "type": "string" })
1046 }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051 use super::*;
1052
1053 #[test]
1054 fn evse_id_accepts_every_example_the_spec_gives() {
1055 for (text, standard) in [
1056 ("DE*AB7*E840*6487", IdStandard::Iso),
1057 ("DEAB7E8406487", IdStandard::Iso),
1058 ("DE*XYZ*ETEST1", IdStandard::Iso),
1059 ("+49*810*000*438", IdStandard::Din),
1060 ("49*810*000*438", IdStandard::Din),
1061 ] {
1062 let id: EvseId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1063 assert_eq!(id.standard(), standard, "{text}");
1064 assert_eq!(id.to_string(), text, "{text} was rewritten");
1065 }
1066 }
1067
1068 #[test]
1069 fn evse_ids_that_differ_only_in_separators_and_case_are_equal() {
1070 let a: EvseId = "DE*AB7*E840*6487".parse().unwrap();
1071 let b: EvseId = "DEAB7E8406487".parse().unwrap();
1072 let c: EvseId = "de*ab7*e840*6487".parse().unwrap();
1073 assert_eq!(a, b);
1074 assert_eq!(a, c);
1075 assert_eq!(a.to_string(), "DE*AB7*E840*6487");
1077 assert_eq!(b.to_string(), "DEAB7E8406487");
1078 }
1079
1080 #[test]
1081 fn an_iso_id_never_equals_a_din_one() {
1082 let iso: EvseId = "DE*AB7*E840*6487".parse().unwrap();
1085 let din: EvseId = "+49*810*000*438".parse().unwrap();
1086 assert_ne!(iso, din);
1087 }
1088
1089 #[test]
1090 fn the_optional_din_plus_does_not_make_a_second_charging_spot() {
1091 let with: EvseId = "+49*810*000*438".parse().unwrap();
1093 let without: EvseId = "49*810*000*438".parse().unwrap();
1094
1095 assert_eq!(with, without);
1096 assert_eq!(with.cmp(&without), core::cmp::Ordering::Equal);
1097 assert_eq!(with.canonical(), without.canonical());
1098 assert_eq!(with.to_string(), "+49*810*000*438", "and each keeps its own text");
1099 assert_eq!(with.operator_id(), without.operator_id());
1100 }
1101
1102 #[test]
1103 fn ordering_agrees_with_equality_for_every_identifier() {
1104 use std::hash::{BuildHasher as _, RandomState};
1107 let hasher = RandomState::new();
1108 let spellings = ["DE*AB7*E840*6487", "DEAB7E8406487", "de-ab7-e840-6487", "DE*XYZ*ETEST1"];
1109 for a in spellings {
1110 for b in spellings {
1111 let (x, y) = (EvseId::new_unchecked(a), EvseId::new_unchecked(b));
1112 assert_eq!(
1113 (x.cmp(&y) == core::cmp::Ordering::Equal),
1114 x == y,
1115 "Ord and Eq disagree on {a:?} vs {b:?}"
1116 );
1117 if x == y {
1118 assert_eq!(hasher.hash_one(&x), hasher.hash_one(&y), "{a:?} and {b:?} hash apart");
1119 } else {
1120 assert_ne!(hasher.hash_one(&x), hasher.hash_one(&y), "{a:?} and {b:?} hash alike");
1123 }
1124 }
1125 }
1126 }
1127
1128 #[test]
1129 fn the_operator_is_derived_from_the_evse_id_the_way_hubject_does_it() {
1130 let iso: EvseId = "DE*AB7*E840*6487".parse().unwrap();
1131 assert_eq!(iso.operator_id().to_string(), "DE*AB7");
1132 assert_eq!(iso.country(), "DE");
1133
1134 let packed: EvseId = "DEAB7E8406487".parse().unwrap();
1135 assert_eq!(packed.operator_id().to_string(), "DEAB7");
1136 assert_eq!(iso.operator_id(), packed.operator_id());
1138
1139 let din: EvseId = "+49*810*000*438".parse().unwrap();
1140 assert_eq!(din.operator_id().to_string(), "+49*810");
1141 assert_eq!(din.country(), "49");
1142 }
1143
1144 #[test]
1145 fn evco_id_accepts_every_example_the_spec_gives() {
1146 for (text, standard) in [
1147 ("DE-8EO-CAet5e4XY-3", IdStandard::Iso),
1148 ("DE8EOCAet5e43X1", IdStandard::Iso),
1149 ("DE*8EO*Aet5e4*3", IdStandard::Din),
1150 ("DE-8EO-Aet5e4-3", IdStandard::Din),
1151 ("DE8EOAet5e43", IdStandard::Din),
1152 ("DE-DCB-C12345678-X", IdStandard::Iso),
1153 ] {
1154 let id: EvcoId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1155 assert_eq!(id.standard(), standard, "{text}");
1156 assert_eq!(id.to_string(), text);
1157 }
1158 }
1159
1160 #[test]
1161 fn the_provider_is_derived_from_the_evco_id() {
1162 let iso: EvcoId = "DE-8EO-CAet5e4XY-3".parse().unwrap();
1163 assert_eq!(iso.provider_id().to_string(), "DE-8EO");
1164 let din: EvcoId = "DE*8EO*Aet5e4*3".parse().unwrap();
1165 assert_eq!(din.provider_id().to_string(), "DE*8EO");
1166 assert_eq!(iso.provider_id(), din.provider_id());
1167 }
1168
1169 #[test]
1170 fn operator_and_provider_ids_accept_the_spec_examples() {
1171 for text in ["DE*A36", "DEA36", "+49*536", "49*536"] {
1172 let id: OperatorId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1173 assert_eq!(id.to_string(), text);
1174 }
1175 for text in ["DE8EO", "DE-8EO", "DE*8EO"] {
1176 let id: ProviderId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1177 assert_eq!(id.to_string(), text);
1178 assert_eq!(id.country(), "DE");
1179 }
1180 }
1181
1182 #[test]
1183 fn malformed_ids_are_rejected_by_new_but_survive_deserialisation() {
1184 assert!("not-an-evse-id".parse::<EvseId>().is_err());
1185 assert!("DE*AB7*840*6487".parse::<EvseId>().is_err()); let id: EvseId = serde_json::from_str(r#""garbage""#).unwrap();
1189 assert!(!id.is_well_formed());
1190 assert_eq!(serde_json::to_string(&id).unwrap(), r#""garbage""#);
1191 assert_eq!(id.validate().unwrap_err().as_slice()[0].code, ViolationCode::PatternMismatch);
1192 }
1193
1194 #[test]
1195 fn every_prefix_of_a_valid_identifier_is_rejected_without_panicking() {
1196 let valid = [
1206 "DE*AB7*E840*6487",
1207 "DEAB7E8406487",
1208 "+49*810*000*438",
1209 "DE-8EO-CAet5e4XY-3",
1210 "DE*8EO*Aet5e4*3",
1211 "DE*A36",
1212 "+49*536",
1213 "DE-8EO",
1214 "IT*123*P456*AB789",
1215 "b2688855-7f00-0002-6d8e-48d883f6abb6",
1216 "7568290FFF765F",
1217 ];
1218
1219 for text in valid {
1220 let extended = format!("{text}9");
1222 for cut in 0..=extended.len() {
1223 let candidate = &extended[..cut];
1224
1225 assert_eq!(
1231 EvseId::new_unchecked(candidate).is_well_formed(),
1232 EvseId::new(candidate).is_ok(),
1233 "EvseID disagreed with itself on {candidate:?}"
1234 );
1235 assert_eq!(
1236 EvcoId::new_unchecked(candidate).is_well_formed(),
1237 EvcoId::new(candidate).is_ok(),
1238 "EvcoID disagreed with itself on {candidate:?}"
1239 );
1240 assert_eq!(
1241 OperatorId::new_unchecked(candidate).is_well_formed(),
1242 OperatorId::new(candidate).is_ok(),
1243 "OperatorID disagreed with itself on {candidate:?}"
1244 );
1245 assert_eq!(
1246 ProviderId::new_unchecked(candidate).is_well_formed(),
1247 ProviderId::new(candidate).is_ok(),
1248 "ProviderID disagreed with itself on {candidate:?}"
1249 );
1250 assert_eq!(
1251 ChargingPoolId::new_unchecked(candidate).is_well_formed(),
1252 ChargingPoolId::new(candidate).is_ok(),
1253 "ChargingPoolID disagreed with itself on {candidate:?}"
1254 );
1255 assert_eq!(
1256 SessionId::new_unchecked(candidate).is_well_formed(),
1257 SessionId::new(candidate).is_ok(),
1258 "SessionID disagreed with itself on {candidate:?}"
1259 );
1260 assert_eq!(
1261 Uid::new_unchecked(candidate).is_well_formed(),
1262 Uid::new(candidate).is_ok(),
1263 "UID disagreed with itself on {candidate:?}"
1264 );
1265 }
1266 }
1267
1268 assert!("DE".parse::<EvseId>().is_err(), "no operator part at all");
1270 assert!("DE*A".parse::<EvseId>().is_err(), "one operator character");
1271 assert!("DE*AB7*E".parse::<EvseId>().is_err(), "no instance after the E marker");
1272 assert!("DE-8EO-C".parse::<EvcoId>().is_err(), "no instance after the C marker");
1273 assert!("IT*123*P".parse::<ChargingPoolId>().is_err(), "no pool part after the P marker");
1274 assert!("DE".parse::<OperatorId>().is_err(), "a country code is not an OperatorID");
1275 assert!("DE".parse::<ProviderId>().is_err(), "nor a ProviderID");
1276 }
1277
1278 #[test]
1279 fn both_characters_of_a_country_code_must_be_letters() {
1280 for bad in [
1286 "1EAB7E840", "E1AB7E840", "D3*AB7*E840*6487", ] {
1290 assert!(bad.parse::<EvseId>().is_err(), "{bad} should be rejected");
1291 }
1292 for bad in ["1E-8EO-CAet5e4XY-3", "D3-8EO-CAet5e4XY-3", "1E*8EO*Aet5e4*3", "D3*8EO*Aet5e4*3"] {
1293 assert!(bad.parse::<EvcoId>().is_err(), "{bad} should be rejected");
1294 }
1295 for bad in ["1E8EO", "D38EO", "1E-8EO"] {
1296 assert!(bad.parse::<ProviderId>().is_err(), "{bad} should be rejected");
1297 }
1298 for bad in ["1T*123*P456", "I3*123*P456"] {
1299 assert!(bad.parse::<ChargingPoolId>().is_err(), "{bad} should be rejected");
1300 }
1301 for bad in ["1E*A36", "D3*A36"] {
1302 assert!(bad.parse::<OperatorId>().is_err(), "{bad} should be rejected");
1303 }
1304
1305 assert!("DE*AB7*E840*6487".parse::<EvseId>().is_ok());
1307 assert!("DE-8EO-CAet5e4XY-3".parse::<EvcoId>().is_ok());
1308 assert!("DE-8EO".parse::<ProviderId>().is_ok());
1309 assert!("IT*123*P456".parse::<ChargingPoolId>().is_ok());
1310 assert!("DE*A36".parse::<OperatorId>().is_ok());
1311 }
1312
1313 #[test]
1314 fn the_din_grammars_reject_each_part_on_its_own() {
1315 for bad in [
1318 "49810000438", "49*810", "*810*000", "4999*810*000", "4a*810*000", "49*81*000", "49*8100*000", "49*8a0*000", "49*810*", "49*810*00a", ] {
1329 assert!(bad.parse::<EvseId>().is_err(), "{bad} should be rejected");
1330 assert!(!EvseId::new_unchecked(bad).is_well_formed(), "{bad}");
1331 }
1332 assert!(format!("49*810*{}", "0".repeat(32)).parse::<EvseId>().is_ok(), "thirty-two digits");
1333 assert!(format!("49*810*{}", "0".repeat(33)).parse::<EvseId>().is_err(), "thirty-three is too many");
1334
1335 for bad in ["49810", "49", "*536", "4999*536", "4a*536", "49*53", "49*5366", "49*5a6"] {
1337 assert!(bad.parse::<OperatorId>().is_err(), "{bad} should be rejected");
1338 }
1339 assert!("+999*536".parse::<OperatorId>().is_ok(), "a three-digit country code");
1340 }
1341
1342 #[test]
1343 fn the_components_a_caller_reads_are_the_ones_in_the_identifier() {
1344 assert_eq!("DE*A36".parse::<OperatorId>().unwrap().country(), "DE");
1346 assert_eq!("DEA36".parse::<OperatorId>().unwrap().country(), "DE");
1347 assert_eq!("+49*536".parse::<OperatorId>().unwrap().country(), "49");
1348 assert_eq!("999*536".parse::<OperatorId>().unwrap().country(), "999");
1349 assert_eq!("DE-8EO".parse::<ProviderId>().unwrap().country(), "DE");
1350
1351 let session: SessionId = "b2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1352 assert_eq!(session.as_str(), "b2688855-7f00-0002-6d8e-48d883f6abb6");
1353 assert!(session.is_well_formed());
1354 let broken = SessionId::new_unchecked("nope");
1355 assert_eq!(broken.as_str(), "nope");
1356 assert!(!broken.is_well_formed());
1357 }
1358
1359 #[test]
1360 fn the_pricing_asterisk_survives_every_road_in_and_out() {
1361 let all: ProviderIdOrAll = "*".parse().unwrap();
1362 let one: ProviderIdOrAll = "DE-8EO".parse().unwrap();
1363
1364 assert_eq!(all.to_string(), "*");
1365 assert_eq!(one.to_string(), "DE-8EO");
1366 assert_eq!(all.as_str(), "*");
1367 assert!(all.is_all() && !one.is_all());
1368 assert!(all.validate().is_ok(), "the asterisk is not an identifier to validate");
1369 assert!(one.validate().is_ok());
1370 assert!(ProviderIdOrAll::One(ProviderId::new_unchecked("nope")).validate().is_err());
1371
1372 assert_eq!(serde_json::from_str::<ProviderIdOrAll>(r#""*""#).unwrap(), ProviderIdOrAll::All);
1374 assert_eq!(serde_json::from_str::<ProviderIdOrAll>(r#""DE-8EO""#).unwrap(), one);
1375 assert_eq!(serde_json::to_string(&all).unwrap(), r#""*""#);
1376 }
1377
1378 #[test]
1379 fn a_rejection_says_which_type_rejected_what() {
1380 let err = "not-an-evse-id".parse::<EvseId>().unwrap_err();
1383 assert_eq!(err.type_name(), "EvseID");
1384 assert_eq!(err.value(), "not-an-evse-id");
1385 assert!(err.to_string().contains("EvseID"), "{err}");
1386 assert!(err.to_string().contains("not-an-evse-id"), "{err}");
1387
1388 assert_eq!("DE*A36".parse::<OperatorId>().unwrap().standard().as_str(), "ISO");
1389 assert_eq!("+49*536".parse::<OperatorId>().unwrap().standard().as_str(), "DIN");
1390 assert_eq!("DE8EO".parse::<ProviderId>().unwrap().standard().as_str(), "ISO/DIN");
1391 assert_eq!(IdStandard::Iso.to_string(), "ISO");
1392 assert_eq!(IdStandard::Din.to_string(), "DIN");
1393 assert_eq!(IdStandard::Either.to_string(), "ISO/DIN");
1394 }
1395
1396 #[cfg(feature = "schema")]
1397 #[test]
1398 fn the_published_schema_describes_every_identifier_as_a_string() {
1399 let mut generator = schemars::SchemaGenerator::default();
1402 for (name, schema) in [
1403 ("EvseID", <EvseId as schemars::JsonSchema>::json_schema(&mut generator)),
1404 ("EvcoID", <EvcoId as schemars::JsonSchema>::json_schema(&mut generator)),
1405 ("OperatorID", <OperatorId as schemars::JsonSchema>::json_schema(&mut generator)),
1406 ("ProviderID", <ProviderId as schemars::JsonSchema>::json_schema(&mut generator)),
1407 ("ChargingPoolID", <ChargingPoolId as schemars::JsonSchema>::json_schema(&mut generator)),
1408 ("SessionID", <SessionId as schemars::JsonSchema>::json_schema(&mut generator)),
1409 ("UID", <Uid as schemars::JsonSchema>::json_schema(&mut generator)),
1410 ("ProviderIDAsterisk", <ProviderIdOrAll as schemars::JsonSchema>::json_schema(&mut generator)),
1411 ] {
1412 let json = serde_json::to_value(&schema).unwrap();
1413 assert_eq!(json["type"], "string", "{name} published an empty schema: {json}");
1414 }
1415 assert_eq!(<EvseId as schemars::JsonSchema>::schema_name(), "EvseID");
1416 assert_eq!(<Uid as schemars::JsonSchema>::schema_name(), "UID");
1417 assert_eq!(<ProviderIdOrAll as schemars::JsonSchema>::schema_name(), "ProviderIDAsterisk");
1418 }
1419
1420 #[test]
1421 fn session_ids_compare_hash_and_order_as_one_session() {
1422 use std::hash::{BuildHasher as _, RandomState};
1426 let hasher = RandomState::new();
1427
1428 let lower: SessionId = "b2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1429 let upper: SessionId = "B2688855-7F00-0002-6D8E-48D883F6ABB6".parse().unwrap();
1430 let other: SessionId = "c2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1431
1432 assert_eq!(lower, upper, "one session, written two ways");
1433 assert_eq!(hasher.hash_one(&lower), hasher.hash_one(&upper));
1434 assert_eq!(lower.cmp(&upper), core::cmp::Ordering::Equal);
1435 assert_eq!(lower.to_string(), "b2688855-7f00-0002-6d8e-48d883f6abb6", "and each keeps its text");
1436
1437 assert_ne!(lower, other, "two sessions are two sessions");
1438 assert_ne!(hasher.hash_one(&lower), hasher.hash_one(&other));
1439 assert!(lower < other);
1440 assert!(other > upper);
1441 assert_eq!(lower.partial_cmp(&other), Some(core::cmp::Ordering::Less));
1442 }
1443
1444 #[test]
1445 fn rfid_uids_compare_hash_and_order_as_one_card() {
1446 use std::hash::{BuildHasher as _, RandomState};
1449 let hasher = RandomState::new();
1450
1451 let upper: Uid = "7568290FFF765F".parse().unwrap();
1452 let lower = Uid::new_unchecked("7568290fff765f");
1453 let other: Uid = "AABBCCDDEEFF11".parse().unwrap();
1454
1455 assert_eq!(upper, lower);
1456 assert_eq!(hasher.hash_one(&upper), hasher.hash_one(&lower));
1457 assert_eq!(upper.cmp(&lower), core::cmp::Ordering::Equal);
1458
1459 assert_ne!(upper, other);
1460 assert_ne!(hasher.hash_one(&upper), hasher.hash_one(&other));
1461 assert!(other > upper, "A sorts after 7");
1462 assert_eq!(upper.partial_cmp(&other), Some(core::cmp::Ordering::Less));
1463 }
1464
1465 #[test]
1471 fn every_grammar_boundary_is_checked_at_the_boundary() {
1472 assert!("DE*AB7*E1".parse::<EvseId>().is_ok(), "one instance character is enough");
1474 assert!(format!("DE*AB7*E{}", "1".repeat(30)).parse::<EvseId>().is_ok(), "thirty is the cap");
1475 assert!(format!("DE*AB7*E{}", "1".repeat(31)).parse::<EvseId>().is_err(), "thirty-one is not");
1476 assert!("DE*AB7*E".parse::<EvseId>().is_err(), "an empty instance part is not an EvseID");
1477 assert!("DE*AB*E1".parse::<EvseId>().is_err(), "two operator characters is not three");
1478 assert!("DE*AB7".parse::<EvseId>().is_err(), "and the E marker is not optional");
1479
1480 assert!("DE-8EO-CAet5e4XY-3".parse::<EvcoId>().is_ok());
1482 assert!("DE-8EO-CAet5e4X-3".parse::<EvcoId>().is_err(), "seven is not eight");
1483 assert!("DE-8EO-CAet5e4XYZ-3".parse::<EvcoId>().is_err(), "nor is nine");
1484 assert!("DE-8EO-CAet5e4XY-".parse::<EvcoId>().is_err(), "the check character is not optional");
1485 assert!("DE-8EO-CAet5e4XY-34".parse::<EvcoId>().is_err(), "and there is exactly one of it");
1486 assert!("DE-8E-CAet5e4XY-3".parse::<EvcoId>().is_err(), "two provider characters is not three");
1487
1488 assert!("DE*8EO*Aet5e4*3".parse::<EvcoId>().is_ok());
1490 assert!("DE*8EO*Aet5e*3".parse::<EvcoId>().is_err(), "five is not six");
1491 assert!("DE*8EO*Aet5e44*3".parse::<EvcoId>().is_err(), "nor is seven");
1492 assert!("DE*8EO*Aet5e4*".parse::<EvcoId>().is_err(), "the check digit is not optional");
1493 assert!("DE*8EO*Aet5e4*33".parse::<EvcoId>().is_err(), "and there is exactly one of it");
1494 assert!("DE*8EO*Aet5e4*X".parse::<EvcoId>().is_ok(), "X is a check digit");
1495 assert!("DE*8EO*Aet5e4*Y".parse::<EvcoId>().is_err(), "Y is not");
1496
1497 assert!("IT*123*P4".parse::<ChargingPoolId>().is_ok());
1499 assert!(format!("IT*123*P{}", "4".repeat(30)).parse::<ChargingPoolId>().is_ok());
1500 assert!(format!("IT*123*P{}", "4".repeat(31)).parse::<ChargingPoolId>().is_err());
1501 assert!("IT*123*P".parse::<ChargingPoolId>().is_err(), "an empty pool part is not a pool");
1502 assert!("IT*12*P456".parse::<ChargingPoolId>().is_err(), "two operator characters is not three");
1503 assert!("IT*123*456".parse::<ChargingPoolId>().is_err(), "and the P marker is not optional");
1504
1505 assert!("b2688855-7f00-0002-6d8e-48d883f6abb6".parse::<SessionId>().is_ok());
1507 for bad in [
1508 "b268885-7f00-0002-6d8e-48d883f6abb6", "b26888556-7f00-0002-6d8e-48d883f6abb6", "b2688855-7f0-0002-6d8e-48d883f6abb6", "b2688855-7f00-0002-6d8e-48d883f6abb", "b2688855-7f00-0002-6d8e-48d883f6abb6a", "b2688855-7f00-0002-6d8e-48d883f6ab_6", ] {
1515 assert!(bad.parse::<SessionId>().is_err(), "{bad} should be rejected");
1516 }
1517 }
1518
1519 #[test]
1520 fn session_ids_follow_the_guid_shape() {
1521 let id: SessionId = "b2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1522 assert_eq!(id.to_string(), "b2688855-7f00-0002-6d8e-48d883f6abb6");
1523 assert!("b2688855-7f00-0002-6d8e".parse::<SessionId>().is_err());
1524 assert!("zzzzzzzz-aaaa-bbbb-cccc-dddddddddddd".parse::<SessionId>().is_ok());
1526 }
1527
1528 #[test]
1529 fn rfid_uids_match_case_insensitively_but_only_uppercase_is_emitted() {
1530 let upper: Uid = "7568290FFF765F".parse().unwrap();
1531 let lower = Uid::new_unchecked("7568290fff765f");
1533
1534 assert_eq!(upper, lower, "the same card");
1535 assert_eq!(lower.to_string(), "7568290fff765f", "and its text survives");
1536 assert_eq!(lower.canonical(), "7568290FFF765F", "with an uppercase key for lookups");
1537
1538 assert!("7568290fff765f".parse::<Uid>().is_err());
1540 assert!(lower.validate().is_err());
1541 assert!(!lower.is_well_formed());
1542 assert!(upper.validate().is_ok());
1543 assert!("123".parse::<Uid>().is_err());
1544 }
1545
1546 #[test]
1547 fn is_well_formed_agrees_with_validate_for_every_identifier() {
1548 for text in ["7568290FFF765F", "7568290fff765f", "123", "", "DE*ABC*E1", "not an id"] {
1551 let uid = Uid::new_unchecked(text);
1552 assert_eq!(uid.is_well_formed(), uid.validate().is_ok(), "Uid disagreed on {text:?}");
1553 let evse = EvseId::new_unchecked(text);
1554 assert_eq!(evse.is_well_formed(), evse.validate().is_ok(), "EvseId disagreed on {text:?}");
1555 let session = SessionId::new_unchecked(text);
1556 assert_eq!(
1557 session.is_well_formed(),
1558 session.validate().is_ok(),
1559 "SessionId disagreed on {text:?}"
1560 );
1561 }
1562 }
1563
1564 #[test]
1565 fn charging_pool_ids_use_the_p_marker() {
1566 let id: ChargingPoolId = "IT*123*P456*AB789".parse().unwrap();
1567 assert_eq!(id.to_string(), "IT*123*P456*AB789");
1568 assert!("IT*123*E456*AB789".parse::<ChargingPoolId>().is_err());
1569 }
1570
1571 #[test]
1572 fn the_pricing_asterisk_is_its_own_variant() {
1573 let all: ProviderIdOrAll = "*".parse().unwrap();
1574 assert!(all.is_all());
1575 assert_eq!(serde_json::to_string(&all).unwrap(), r#""*""#);
1576 let one: ProviderIdOrAll = "DE-8EO".parse().unwrap();
1577 assert!(!one.is_all());
1578 }
1579}