Skip to main content

carrier_core/
id.rs

1//! Identifiers both WBCI and S/PRI carry: carrier codes, the Vorabstimmungs-ID and the LineID.
2//!
3//! Source: XSD `wbci-type-simple.xsd` (`CarrierCode`, `VorabstimmungsIdType`, `LineIDType`);
4//! id format WBCI Anl. 1 V5.4.1 §2.9.1. S/PRI XSD 4.00.03 `VorabstimmungIdType` (16–21
5//! characters) and `LineIdType` (7–21) restrict by length only; they denote the same WBCI id
6//! and AK S&P LineID, so the stricter types here serve both (an interpretation). A valid value
7//! always satisfies the S/PRI facets.
8
9use crate::text::{Charset, TextSpec, Ws, upper_alnum};
10use crate::{ValueError, ValueErrorKind, text_type};
11
12/// A [`TextSpec`] in the WBCI character set with a shape check.
13#[must_use]
14pub const fn id_spec(
15    name: &'static str,
16    min: usize,
17    max: usize,
18    check: fn(&str) -> bool,
19    expected: &'static str,
20) -> TextSpec {
21    TextSpec { name, min, max, charset: Charset::Wbci, ws: Ws::Preserve, pattern: Some((check, expected)) }
22}
23
24/// `CC.ICC` — ISO country code and ITU M.1400 carrier code.
25#[must_use]
26pub fn is_carrier(s: &str) -> bool {
27    s.split_once('.').is_some_and(|(cc, icc)| upper_alnum(cc, 3, 3) && upper_alnum(icc, 1, 6))
28}
29
30/// `CC.ICC.<tail>` with a tail check.
31pub fn carrier_and(s: &str, tail: impl Fn(&str) -> bool) -> bool {
32    s.rsplit_once('.').is_some_and(|(carrier, rest)| is_carrier(carrier) && tail(rest))
33}
34
35/// `CC.ICC.<letter>[0-9A-Z]{9}`.
36#[must_use]
37pub fn is_request_id(s: &str, letter: char) -> bool {
38    carrier_and(s, |t| t.len() == 10 && t.starts_with(letter) && upper_alnum(t.get(1..).unwrap_or(""), 9, 9))
39}
40
41text_type!(
42    /// A carrier: ISO 3166 alpha-3 country code and ITU M.1400 carrier code, e.g. `DEU.EKP1`.
43    ///
44    /// XSD `CarrierCode`: `[0-9A-Z]{3}\.[0-9A-Z]{1,6}`.
45    CarrierCode,
46    id_spec("CarrierCode", 5, 10, is_carrier, r"[0-9A-Z]{3}\.[0-9A-Z]{1,6}"),
47    plain
48);
49
50/// The carrier prefix of a request id that has already been validated.
51#[doc(hidden)]
52#[must_use]
53pub fn carrier_of_valid_id(id: &str) -> CarrierCode {
54    let (carrier, _) = id.rsplit_once('.').unwrap_or((id, ""));
55    CarrierCode(carrier.to_owned())
56}
57
58text_type!(
59    /// The line identifier of a technical resource, e.g. `DEU.EKP1.1754639821`.
60    ///
61    /// XSD `LineIDType` (WBCI): `[0-9A-Z]{3}\.[0-9A-Z]{1,6}\.[0-9A-Z]{1,10}`, 7–21 characters;
62    /// S/PRI `LineIdType` admits any 7–21 characters (see the module docs).
63    LineId,
64    id_spec(
65        "LineId",
66        7,
67        21,
68        |s| carrier_and(s, |t| upper_alnum(t, 1, 10)),
69        r"[0-9A-Z]{3}\.[0-9A-Z]{1,6}\.[0-9A-Z]{1,10}"
70    ),
71    plain
72);
73
74/// The largest sequence number a request id's `allocate` accepts: nine decimal digits.
75///
76/// The schema admits `[0-9A-Z]{9}`; decimal keeps allocated ids readable and matches the
77/// specification's example (`DEU.EKP1.V000000013` for number 13).
78pub const MAX_SEQUENCE: u64 = 999_999_999;
79
80/// `CC.ICC.<letter><seq:09>`.
81///
82/// # Errors
83///
84/// `seq` larger than [`MAX_SEQUENCE`].
85pub fn encode_request_id(
86    carrier: &CarrierCode,
87    letter: char,
88    seq: u64,
89    name: &'static str,
90) -> Result<String, ValueError> {
91    if seq > MAX_SEQUENCE {
92        return Err(ValueError { type_name: name, kind: ValueErrorKind::Sequence { max: MAX_SEQUENCE } });
93    }
94    Ok(format!("{carrier}.{letter}{seq:09}"))
95}
96
97/// Declares a WBCI request id `CC.ICC.<letter>[0-9A-Z]{9}` with `allocate` and `carrier`.
98#[macro_export]
99macro_rules! request_id {
100    ($(#[$meta:meta])* $name:ident, $letter:literal, $expected:literal) => {
101        $crate::text_type!(
102            $(#[$meta])*
103            $name,
104            $crate::id::id_spec(stringify!($name), 16, 21, |s| $crate::id::is_request_id(s, $letter), $expected),
105            plain
106        );
107
108        impl $name {
109            /// Allocates the id for `seq` under `carrier`: the sequence is written as nine
110            /// decimal digits, zero-padded.
111            ///
112            /// The caller owns the sequence and must never reuse a number (A1 V5.4.1 §2.9.1:
113            /// „stellt sicher, dass die ID eindeutig ist").
114            ///
115            /// # Errors
116            ///
117            /// `seq` larger than `MAX_SEQUENCE` (999 999 999).
118            pub fn allocate(carrier: &$crate::CarrierCode, seq: u64) -> Result<Self, $crate::ValueError> {
119                $crate::id::encode_request_id(carrier, $letter, seq, stringify!($name)).map(Self)
120            }
121
122            /// The carrier that issued this id.
123            #[must_use]
124            pub fn carrier(&self) -> $crate::CarrierCode {
125                $crate::id::carrier_of_valid_id(&self.0)
126            }
127        }
128    };
129}
130
131request_id!(
132    /// The id of a pre-agreement request, e.g. `DEU.EKP1.V000000013`.
133    ///
134    /// XSD `VorabstimmungsIdType` (WBCI): `[0-9A-Z]{3}\.[0-9A-Z]{1,6}\.V[0-9A-Z]{9}`. S/PRI
135    /// carries it as `vorabstimmungId` (`VorabstimmungIdType`, 16–21 characters).
136    VorabstimmungsId,
137    'V',
138    r"[0-9A-Z]{3}\.[0-9A-Z]{1,6}\.V[0-9A-Z]{9}"
139);
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    fn cc(s: &str) -> CarrierCode {
146        s.parse().unwrap()
147    }
148
149    #[test]
150    fn carrier_codes() {
151        for ok in ["DEU.EKP1", "DEU.D", "DEU.DTAG12"] {
152            assert!(ok.parse::<CarrierCode>().is_ok(), "{ok}");
153        }
154        for bad in ["DE.EKP1", "DEU.ekp1", "DEU.", "DEU.EKP1234", "DEUEKP1", "DEU.EK P"] {
155            assert!(bad.parse::<CarrierCode>().is_err(), "{bad}");
156        }
157    }
158
159    #[test]
160    fn allocation_matches_the_schema_example() {
161        let id = VorabstimmungsId::allocate(&cc("DEU.EKP1"), 13).unwrap();
162        assert_eq!(id.as_str(), "DEU.EKP1.V000000013");
163        assert_eq!(id.carrier(), cc("DEU.EKP1"));
164        assert_eq!(VorabstimmungsId::allocate(&cc("DEU.EKP1"), MAX_SEQUENCE).unwrap().as_str(), "DEU.EKP1.V999999999");
165        let err = VorabstimmungsId::allocate(&cc("DEU.EKP1"), MAX_SEQUENCE + 1).unwrap_err();
166        assert_eq!(err.kind, ValueErrorKind::Sequence { max: MAX_SEQUENCE });
167    }
168
169    #[test]
170    fn request_ids_check_their_letter() {
171        assert!("DEU.EKP1.V000000013".parse::<VorabstimmungsId>().is_ok());
172        assert!("DEU.EKP1.S000000013".parse::<VorabstimmungsId>().is_err());
173        assert!("DEU.EKP1.V00000013".parse::<VorabstimmungsId>().is_err());
174        assert!("DEU.EKP1.v000000013".parse::<VorabstimmungsId>().is_err());
175    }
176
177    #[test]
178    fn line_ids() {
179        assert!("DEU.EKP1.1754639821".parse::<LineId>().is_ok());
180        assert!("DEU.EKP1.00000".parse::<LineId>().is_ok());
181        assert!("DEU.EKP1.12345678901".parse::<LineId>().is_err());
182    }
183
184    #[test]
185    fn shared_ids_satisfy_the_spri_length_facets() {
186        // S/PRI VorabstimmungIdType 16–21, LineIdType 7–21.
187        let shortest = VorabstimmungsId::new("DEU.D.V000000001").unwrap();
188        assert_eq!(shortest.as_str().len(), 16);
189        const { assert!(VorabstimmungsId::SPEC.min >= 16 && VorabstimmungsId::SPEC.max <= 21) };
190        const { assert!(LineId::SPEC.min >= 7 && LineId::SPEC.max <= 21) };
191    }
192}