mediation 0.1.0

Telecom usage mediation domain library — 3GPP CDR local-time-plus-offset arithmetic (quarter-hour offsets, DST-adjusted), integer octet volumes, validated identifiers (IMSI/MSISDN/IMEI/ICCID/SUPI/GPSI/PEI, PLMN, TADIG), natural-key deduplication, RFC 1982 wrap-aware sequence-gap detection, partial-record reassembly, cross-node correlation, signed restatement, a numbered validation catalogue, a conservation law that spans batches, TBCD/BCD wire codecs, a zero-copy BER reader, usage aggregation, roaming-batch reconciliation, longest-prefix number ranges with portability, User Location Information (CGI/SAI/ECGI/NCGI/TAI), conserving tariff-band apportionment, two-question jurisdiction determination and an EU/German regulatory layer. Zero I/O, no async, no clock, exact integer quantities.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Network identity: [`Mcc`], [`Mnc`], [`PlmnId`] and [`TadigCode`].
//!
//! # The MNC is two digits or three, and the digits do not say which
//!
//! An IMSI is `MCC` (3 digits) + `MNC` (**2 or 3**) + `MSIN`, and nothing in
//! the digit string reveals the boundary. North American MCCs use three-digit
//! MNCs; most of the rest of the world uses two. Splitting at a fixed offset
//! therefore misattributes an entire region's records to networks that do not
//! exist — silently, because the result is still a well-formed identifier.
//!
//! The authority is the ITU-T E.212 assignment list, republished operationally
//! through GSMA IR.21. This crate ships the *structure* and the *validation*,
//! and takes the assignment from a caller-supplied [`MncWidths`]. Vendoring a
//! table here would ship a snapshot that is stale the week it is published, and
//! would put the blame for a misattributed record on the wrong party.
//!
//! [`NorthAmericanRule`] covers the one rule that is stable enough to state —
//! MCC 3xx is three digits — and is offered as a starting point, not as an
//! authority.
//!
//! # An MNC is a string, not a number
//!
//! German MNCs under MCC 262 are `01` (Telekom), `02` (Vodafone), `03` and `07`
//! (Telefónica) and `23` (1&1). Stored as an integer, `01` and `1` collapse
//! into one value — merging two operators, or splitting one, depending on which
//! way the coercion falls. [`Mnc`] preserves the declared width, so `262-01`
//! and `262-1` are different values and only one of them is well-formed.
//!
//! ```rust
//! use mediation::{Mnc, PlmnId};
//!
//! let telekom: PlmnId = "262-01".parse().unwrap();
//! assert_eq!(telekom.to_string(), "262-01");
//! assert_eq!(telekom.mnc().width(), 2);
//!
//! // A two-digit MNC and a three-digit one are never equal, even numerically.
//! assert_ne!(Mnc::new(1, 2).unwrap(), Mnc::new(1, 3).unwrap());
//! ```

use std::fmt;
use std::str::FromStr;

use crate::error::ParseError;

// ── Mcc ──────────────────────────────────────────────────────────────────────

/// An ITU-T E.212 Mobile Country Code: exactly three digits.
///
/// Always recoverable from an IMSI without any external table, which is why it
/// is a separate type from [`PlmnId`] — [`crate::Imsi::mcc`] is infallible while
/// the full network identity is not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Mcc(u16);

impl Mcc {
    /// Germany.
    pub const GERMANY: Self = Self(262);

    /// A country code from its numeric value, which must be three digits.
    ///
    /// `000` is rejected: E.212 does not assign it, and a zero default is the
    /// most common way an unparsed field reaches storage looking valid.
    #[must_use]
    pub const fn new(value: u16) -> Option<Self> {
        if value >= 1 && value <= 999 {
            Some(Self(value))
        } else {
            None
        }
    }

    /// The numeric value.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }

    /// `true` for the North American numbering region, MCC 3xx.
    ///
    /// The one MNC-width rule stable enough to encode. It is still a rule about
    /// a *region*, not a guarantee about a specific assignment — see
    /// [`MncWidths`].
    #[must_use]
    pub const fn is_north_american(self) -> bool {
        self.0 >= 300 && self.0 <= 399
    }
}

impl fmt::Display for Mcc {
    /// Writes three digits, zero-padded.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:03}", self.0)
    }
}

impl FromStr for Mcc {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::format("Mcc", s, "exactly three decimal digits, such as 262");
        let t = s.trim();
        if t.len() != 3 || !t.bytes().all(|b| b.is_ascii_digit()) {
            return Err(err());
        }
        Self::new(t.parse().map_err(|_| err())?).ok_or_else(err)
    }
}

// ── Mnc ──────────────────────────────────────────────────────────────────────

/// An ITU-T E.212 Mobile Network Code: two or three digits, leading zeros
/// significant.
///
/// The declared width is part of the value. `01` and `001` are different
/// networks, and comparing them numerically merges them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Mnc {
    value: u16,
    width: u8,
}

impl Mnc {
    /// A network code from its numeric value and declared digit width.
    ///
    /// `None` for a width other than 2 or 3, or a value that does not fit the
    /// declared width.
    #[must_use]
    pub const fn new(value: u16, width: u8) -> Option<Self> {
        let fits = match width {
            2 => value <= 99,
            3 => value <= 999,
            _ => false,
        };
        if fits {
            Some(Self { value, width })
        } else {
            None
        }
    }

    /// The numeric value, which is meaningless without [`width`](Self::width).
    #[must_use]
    pub const fn get(self) -> u16 {
        self.value
    }

    /// The declared digit width: 2 or 3.
    #[must_use]
    pub const fn width(self) -> u8 {
        self.width
    }
}

impl fmt::Display for Mnc {
    /// Writes the declared number of digits, zero-padded.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:0width$}", self.value, width = self.width as usize)
    }
}

impl FromStr for Mnc {
    type Err = ParseError;

    /// Parses two or three digits, taking the width from the input.
    ///
    /// The width comes from how many digits were written, so `"01"` and
    /// `"001"` parse to different values rather than to the same one.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::format("Mnc", s, "two or three decimal digits, such as 02 or 001");
        let t = s.trim();
        if !matches!(t.len(), 2 | 3) || !t.bytes().all(|b| b.is_ascii_digit()) {
            return Err(err());
        }
        let width = u8::try_from(t.len()).map_err(|_| err())?;
        Self::new(t.parse().map_err(|_| err())?, width).ok_or_else(err)
    }
}

// ── MncWidth resolution ──────────────────────────────────────────────────────

/// How many digits an MCC's network codes occupy.
///
/// The value a caller must supply before an IMSI can be split. See the module
/// documentation for why this crate does not decide it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MncWidth {
    /// Two-digit MNCs — most of the world.
    Two,
    /// Three-digit MNCs — the North American region, and some others.
    Three,
}

impl MncWidth {
    /// The width as a digit count.
    #[must_use]
    pub const fn digits(self) -> u8 {
        match self {
            Self::Two => 2,
            Self::Three => 3,
        }
    }
}

/// Resolves an [`Mcc`] to the digit width of its network codes.
///
/// Implement this over whatever assignment data you maintain — a database
/// table, a parsed IR.21 dump, a static map. The crate calls it and never
/// guesses on your behalf.
pub trait MncWidths {
    /// The MNC width for `mcc`, or `None` when the assignment is unknown.
    ///
    /// Returning `None` is the correct answer for an unrecognised country code,
    /// and callers surface it as an unresolvable identity rather than falling
    /// back to a default that would attribute the record to a real network that
    /// did not serve it.
    fn width_for(&self, mcc: Mcc) -> Option<MncWidth>;
}

/// The region rule alone: MCC 3xx is three digits, everything else is two.
///
/// Offered as a starting point for development and tests. It is **not** an
/// authority: several countries outside the North American region also assign
/// three-digit MNCs, and this resolver answers `Two` for all of them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct NorthAmericanRule;

impl MncWidths for NorthAmericanRule {
    fn width_for(&self, mcc: Mcc) -> Option<MncWidth> {
        Some(if mcc.is_north_american() {
            MncWidth::Three
        } else {
            MncWidth::Two
        })
    }
}

impl<F> MncWidths for F
where
    F: Fn(Mcc) -> Option<MncWidth>,
{
    fn width_for(&self, mcc: Mcc) -> Option<MncWidth> {
        self(mcc)
    }
}

// ── PlmnId ───────────────────────────────────────────────────────────────────

/// A Public Land Mobile Network identity: [`Mcc`] plus [`Mnc`].
///
/// The canonical string is `MCC-MNC` with the MNC's leading zeros intact —
/// `262-02`, never `262-2`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PlmnId {
    mcc: Mcc,
    mnc: Mnc,
}

impl PlmnId {
    /// A network identity from its two parts.
    #[must_use]
    pub const fn new(mcc: Mcc, mnc: Mnc) -> Self {
        Self { mcc, mnc }
    }

    /// The country code.
    #[must_use]
    pub const fn mcc(self) -> Mcc {
        self.mcc
    }

    /// The network code, with its declared width.
    #[must_use]
    pub const fn mnc(self) -> Mnc {
        self.mnc
    }

    /// `true` when both identities name the same network.
    ///
    /// Equivalent to `==`; named because the roaming predicates read better with
    /// it and because `serving == home` is a validation rule in its own right.
    #[must_use]
    pub const fn is_same_network(self, other: Self) -> bool {
        self.mcc.get() == other.mcc.get()
            && self.mnc.get() == other.mnc.get()
            && self.mnc.width() == other.mnc.width()
    }

    /// `true` when the two identities are in the same country.
    #[must_use]
    pub const fn is_same_country(self, other: Self) -> bool {
        self.mcc.get() == other.mcc.get()
    }
}

impl fmt::Display for PlmnId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{}", self.mcc, self.mnc)
    }
}

/// The shape [`PlmnId`] accepts, as rendered in a [`ParseError`].
const PLMN_FORMAT: &str = "MCC-MNC with the MNC's leading zeros, such as 262-02 or 310-260";

impl FromStr for PlmnId {
    type Err = ParseError;

    /// Parses `MCC-MNC`.
    ///
    /// The separator is required: without it, `26202` cannot be split without
    /// the very table this type exists to make explicit.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::format("PlmnId", s, PLMN_FORMAT);
        let (mcc, mnc) = s.trim().split_once('-').ok_or_else(err)?;
        Ok(Self::new(
            mcc.parse().map_err(|_| err())?,
            mnc.parse().map_err(|_| err())?,
        ))
    }
}

// ── TadigCode ────────────────────────────────────────────────────────────────

/// A GSMA TADIG code: five characters identifying a roaming partner.
///
/// The first three name the country and the last two the operator — `DEUD1`,
/// `GBRVF`, `USACG`. TADIG codes and [`PlmnId`]s identify the same operators
/// through different registries, and neither is derivable from the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TadigCode([u8; 5]);

impl TadigCode {
    /// A code from five ASCII alphanumeric characters.
    ///
    /// Lower case is accepted and normalised to upper, so one operator has one
    /// value however a partner's file spelled it.
    #[must_use]
    pub fn new(code: &str) -> Option<Self> {
        let t = code.trim();
        if t.len() != 5 || !t.bytes().all(|b| b.is_ascii_alphanumeric()) {
            return None;
        }
        let mut buf = [0u8; 5];
        for (slot, byte) in buf.iter_mut().zip(t.bytes()) {
            *slot = byte.to_ascii_uppercase();
        }
        Some(Self(buf))
    }

    /// The whole code.
    ///
    /// # Panics
    ///
    /// Never: [`new`](Self::new) is the only constructor and accepts nothing
    /// but ASCII alphanumerics, so the buffer is always valid UTF-8. It panics
    /// rather than substituting a placeholder, because a placeholder would
    /// become a roaming partner that does not exist.
    #[must_use]
    pub fn as_str(&self) -> &str {
        std::str::from_utf8(&self.0).expect("a TADIG code is ASCII by construction")
    }

    /// The three-character country part.
    #[must_use]
    pub fn country(&self) -> &str {
        &self.as_str()[..3]
    }

    /// The two-character operator part.
    #[must_use]
    pub fn operator(&self) -> &str {
        &self.as_str()[3..]
    }
}

impl fmt::Display for TadigCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for TadigCode {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s).ok_or_else(|| {
            ParseError::format(
                "TadigCode",
                s,
                "five alphanumeric characters, such as DEUD1",
            )
        })
    }
}

// ── Serde ────────────────────────────────────────────────────────────────────

#[cfg(feature = "serde")]
mod serde_impl {
    use super::{Mcc, Mnc, PlmnId, TadigCode};
    use serde::de::{self, Visitor};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::fmt;

    macro_rules! string_serde {
        ($ty:ty, $expecting:literal) => {
            impl Serialize for $ty {
                /// The canonical string, so leading zeros survive the round trip
                /// that a numeric representation would strip.
                fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                    serializer.collect_str(self)
                }
            }

            impl<'de> Deserialize<'de> for $ty {
                fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                    struct V;
                    impl Visitor<'_> for V {
                        type Value = $ty;
                        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                            f.write_str($expecting)
                        }
                        fn visit_str<E: de::Error>(self, v: &str) -> Result<$ty, E> {
                            v.parse().map_err(de::Error::custom)
                        }
                    }
                    deserializer.deserialize_str(V)
                }
            }
        };
    }

    string_serde!(Mcc, "a three-digit country code such as \"262\"");
    string_serde!(Mnc, "a two- or three-digit network code such as \"02\"");
    string_serde!(PlmnId, "a network identity such as \"262-02\"");
    string_serde!(TadigCode, "a five-character TADIG code such as \"DEUD1\"");
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The bug this module exists to prevent: an MNC held as a number loses its
    /// leading zero and merges two networks.
    #[test]
    fn leading_zeros_are_part_of_the_value() {
        let telekom: PlmnId = "262-01".parse().unwrap();
        assert_eq!(telekom.to_string(), "262-01");
        assert_eq!(telekom.mnc().get(), 1);
        assert_eq!(telekom.mnc().width(), 2);

        // Same number, different width, different network.
        let two = Mnc::new(1, 2).unwrap();
        let three = Mnc::new(1, 3).unwrap();
        assert_ne!(two, three);
        assert_eq!(two.to_string(), "01");
        assert_eq!(three.to_string(), "001");
    }

    #[test]
    fn german_networks_render_canonically() {
        for (s, mnc) in [("262-01", 1), ("262-02", 2), ("262-03", 3), ("262-23", 23)] {
            let p: PlmnId = s.parse().unwrap();
            assert_eq!(p.mcc(), Mcc::GERMANY);
            assert_eq!(p.mnc().get(), mnc);
            assert_eq!(p.to_string(), s);
        }
    }

    #[test]
    fn a_three_digit_mnc_round_trips() {
        let p: PlmnId = "310-260".parse().unwrap();
        assert_eq!(p.mnc().width(), 3);
        assert_eq!(p.to_string(), "310-260");
        assert!(p.mcc().is_north_american());
    }

    #[test]
    fn malformed_network_identities_are_rejected() {
        for s in [
            "262-2",    // MNC width 1
            "262-0234", // MNC width 4
            "26-02",    // MCC width 2
            "2620-2",   // MCC width 4
            "26202",    // no separator — unsplittable without a table
            "262-ab",   // not digits
            "",
        ] {
            assert!(s.parse::<PlmnId>().is_err(), "{s:?} must not parse");
        }
    }

    #[test]
    fn mcc_zero_is_not_a_country() {
        assert_eq!(Mcc::new(0), None);
        assert!("000".parse::<Mcc>().is_err());
        assert!(Mcc::new(1).is_some());
    }

    /// The width rule is a caller's decision; the built-in resolver states only
    /// the region rule and says so.
    #[test]
    fn width_resolution_is_supplied_not_guessed() {
        let rule = NorthAmericanRule;
        assert_eq!(
            rule.width_for(Mcc::new(310).unwrap()),
            Some(MncWidth::Three)
        );
        assert_eq!(rule.width_for(Mcc::GERMANY), Some(MncWidth::Two));

        // A closure is a resolver too, so a caller's table needs no newtype.
        let table = |mcc: Mcc| match mcc.get() {
            262 => Some(MncWidth::Two),
            _ => None,
        };
        assert_eq!(table.width_for(Mcc::GERMANY), Some(MncWidth::Two));
        assert_eq!(table.width_for(Mcc::new(310).unwrap()), None);
    }

    #[test]
    fn same_network_compares_all_three_components() {
        let a: PlmnId = "262-02".parse().unwrap();
        let b: PlmnId = "262-002".parse().unwrap();
        assert!(!a.is_same_network(b));
        assert!(a.is_same_country(b));
        assert!(a.is_same_network(a));
    }

    #[test]
    fn tadig_codes_normalise_case_and_split() {
        let t: TadigCode = "deud1".parse().unwrap();
        assert_eq!(t.to_string(), "DEUD1");
        assert_eq!(t.country(), "DEU");
        assert_eq!(t.operator(), "D1");
        assert_eq!("DEUD1".parse::<TadigCode>().unwrap(), t);

        for s in ["DEUD", "DEUD11", "DEU-1", ""] {
            assert!(s.parse::<TadigCode>().is_err(), "{s:?} must not parse");
        }
    }
}