use std::fmt;
use std::str::FromStr;
use crate::error::ParseError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Mcc(u16);
impl Mcc {
pub const GERMANY: Self = Self(262);
#[must_use]
pub const fn new(value: u16) -> Option<Self> {
if value >= 1 && value <= 999 {
Some(Self(value))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
#[must_use]
pub const fn is_north_american(self) -> bool {
self.0 >= 300 && self.0 <= 399
}
}
impl fmt::Display for Mcc {
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Mnc {
value: u16,
width: u8,
}
impl Mnc {
#[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
}
}
#[must_use]
pub const fn get(self) -> u16 {
self.value
}
#[must_use]
pub const fn width(self) -> u8 {
self.width
}
}
impl fmt::Display for Mnc {
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;
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MncWidth {
Two,
Three,
}
impl MncWidth {
#[must_use]
pub const fn digits(self) -> u8 {
match self {
Self::Two => 2,
Self::Three => 3,
}
}
}
pub trait MncWidths {
fn width_for(&self, mcc: Mcc) -> Option<MncWidth>;
}
#[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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PlmnId {
mcc: Mcc,
mnc: Mnc,
}
impl PlmnId {
#[must_use]
pub const fn new(mcc: Mcc, mnc: Mnc) -> Self {
Self { mcc, mnc }
}
#[must_use]
pub const fn mcc(self) -> Mcc {
self.mcc
}
#[must_use]
pub const fn mnc(self) -> Mnc {
self.mnc
}
#[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()
}
#[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)
}
}
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;
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())?,
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TadigCode([u8; 5]);
impl TadigCode {
#[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))
}
#[must_use]
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).expect("a TADIG code is ASCII by construction")
}
#[must_use]
pub fn country(&self) -> &str {
&self.as_str()[..3]
}
#[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",
)
})
}
}
#[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 {
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::*;
#[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);
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", "262-0234", "26-02", "2620-2", "26202", "262-ab", "",
] {
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());
}
#[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));
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");
}
}
}