use std::fmt;
use std::str::FromStr;
use crate::digits::DigitString;
use crate::error::ParseError;
use crate::identity::Msisdn;
use crate::numbering::NumberRangeSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Destination {
Number(Msisdn),
Short(ShortCode),
}
impl Destination {
#[must_use]
pub const fn as_number(&self) -> Option<Msisdn> {
match self {
Self::Number(n) => Some(*n),
Self::Short(_) => None,
}
}
#[must_use]
pub const fn digits(&self) -> DigitString {
match self {
Self::Number(n) => n.digits(),
Self::Short(s) => s.0,
}
}
#[must_use]
pub fn class(&self, plan: &(impl NumberingPlan + ?Sized)) -> Option<DestinationClass> {
plan.classify(self)
}
}
impl From<Msisdn> for Destination {
fn from(number: Msisdn) -> Self {
Self::Number(number)
}
}
impl From<ShortCode> for Destination {
fn from(code: ShortCode) -> Self {
Self::Short(code)
}
}
impl fmt::Display for Destination {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Number(n) => write!(f, "+{n}"),
Self::Short(s) => s.fmt(f),
}
}
}
const DESTINATION_FORMAT: &str = "+ and a country code not starting with 0, 1 to 15 digits in all, \
or a short code of 2 to 6 digits, such as +49301234567 or 110";
impl FromStr for Destination {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim();
if t.starts_with('+') {
if t.bytes().find(u8::is_ascii_digit) == Some(b'0') {
return Err(ParseError::withheld("Destination", DESTINATION_FORMAT));
}
t.parse()
.map(Self::Number)
.map_err(|_| ParseError::withheld("Destination", DESTINATION_FORMAT))
} else {
t.parse()
.map(Self::Short)
.map_err(|_| ParseError::withheld("Destination", DESTINATION_FORMAT))
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShortCode(DigitString);
impl ShortCode {
pub const MIN_DIGITS: usize = 2;
pub const MAX_DIGITS: usize = 6;
#[must_use]
pub const fn len(self) -> usize {
self.0.len()
}
#[must_use]
pub const fn is_empty(self) -> bool {
false
}
#[must_use]
pub const fn digits(self) -> DigitString {
self.0
}
fn from_digits(digits: DigitString) -> Option<Self> {
(Self::MIN_DIGITS..=Self::MAX_DIGITS)
.contains(&digits.len())
.then_some(Self(digits))
}
}
impl fmt::Display for ShortCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for ShortCode {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::withheld("ShortCode", "2 to 6 digits, such as 110 or 116117");
DigitString::parse(s.trim(), Self::MAX_DIGITS)
.and_then(Self::from_digits)
.ok_or_else(err)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AreaCode(DigitString);
impl AreaCode {
#[must_use]
pub const fn digits(self) -> DigitString {
self.0
}
}
impl fmt::Display for AreaCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for AreaCode {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::format("AreaCode", s, "1 to 5 digits, such as 30 or 030");
let t = s.trim();
let t = t.strip_prefix('0').unwrap_or(t);
let digits = DigitString::parse(t, 5).ok_or_else(err)?;
if digits.is_empty() || digits.at(0) == 0 {
return Err(err());
}
Ok(Self(digits))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShortCodePattern {
prefix: &'static str,
len: u8,
}
impl ShortCodePattern {
#[must_use]
pub const fn new(prefix: &'static str, len: u8) -> Self {
Self { prefix, len }
}
#[must_use]
pub const fn prefix(self) -> &'static str {
self.prefix
}
#[must_use]
pub const fn len(self) -> u8 {
self.len
}
#[must_use]
pub const fn is_empty(self) -> bool {
false
}
fn is_valid(self) -> bool {
is_digits(self.prefix)
&& (ShortCode::MIN_DIGITS..=ShortCode::MAX_DIGITS).contains(&usize::from(self.len))
&& self.prefix.len() <= usize::from(self.len)
}
fn matches(self, digits: &[u8]) -> bool {
digits.len() == usize::from(self.len) && strip(digits, self.prefix).is_some()
}
fn overlaps(self, digits: &[u8]) -> bool {
self.prefix
.bytes()
.zip(digits)
.all(|(p, &d)| p.wrapping_sub(b'0') == d)
}
}
const fn pattern(prefix: &'static str, len: u8) -> ShortCodePattern {
ShortCodePattern::new(prefix, len)
}
const GERMAN_SHORT_CODES: &[ShortCodePattern] = &[
pattern("110", 3),
pattern("112", 3),
pattern("115", 3),
pattern("116", 6),
pattern("118", 5),
pattern("111", 3),
pattern("113", 3),
pattern("114", 3),
pattern("117", 3),
pattern("119", 3),
];
const ITALIAN_SHORT_CODES: &[ShortCodePattern] = &[
pattern("112", 3),
pattern("113", 3),
pattern("115", 3),
pattern("118", 3),
pattern("116", 6),
];
const NANP_SHORT_CODES: &[ShortCodePattern] = &[
pattern("211", 3),
pattern("311", 3),
pattern("411", 3),
pattern("511", 3),
pattern("611", 3),
pattern("711", 3),
pattern("811", 3),
pattern("911", 3),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DialContext {
country_code: u16,
international_prefix: &'static str,
trunk_prefix: Option<&'static str>,
closed: bool,
national_len: Option<u8>,
short_codes: &'static [ShortCodePattern],
area_code: Option<AreaCode>,
}
impl DialContext {
pub const MAX_DIALLED: usize = 64;
#[must_use]
pub const fn germany() -> Self {
Self {
country_code: 49,
international_prefix: "00",
trunk_prefix: Some("0"),
closed: false,
national_len: None,
short_codes: GERMAN_SHORT_CODES,
area_code: None,
}
}
#[must_use]
pub const fn italy() -> Self {
Self {
country_code: 39,
international_prefix: "00",
trunk_prefix: None,
closed: true,
national_len: None,
short_codes: ITALIAN_SHORT_CODES,
area_code: None,
}
}
#[must_use]
pub const fn nanp() -> Self {
Self {
country_code: 1,
international_prefix: "011",
trunk_prefix: Some("1"),
closed: true,
national_len: Some(10),
short_codes: NANP_SHORT_CODES,
area_code: None,
}
}
pub fn new(
country_code: u16,
international_prefix: &'static str,
) -> Result<Self, DialContextError> {
if !(1..=999).contains(&country_code) {
return Err(DialContextError::CountryCode);
}
if !is_digits(international_prefix) {
return Err(DialContextError::InternationalPrefix);
}
Ok(Self {
country_code,
international_prefix,
trunk_prefix: None,
closed: false,
national_len: None,
short_codes: &[],
area_code: None,
})
}
pub fn with_trunk_prefix(mut self, trunk: &'static str) -> Result<Self, DialContextError> {
if !is_digits(trunk) {
return Err(DialContextError::TrunkPrefix);
}
self.trunk_prefix = Some(trunk);
self.checked()
}
#[must_use]
pub const fn closed(mut self) -> Self {
self.closed = true;
self.area_code = None;
self
}
pub fn with_national_length(mut self, digits: u8) -> Result<Self, DialContextError> {
let total = usize::from(digits) + CountryCodeDigits::of(self.country_code).as_slice().len();
if digits == 0 || total > Msisdn::MAX_DIGITS {
return Err(DialContextError::NationalLength);
}
self.national_len = Some(digits);
Ok(self)
}
pub fn with_short_codes(
mut self,
patterns: &'static [ShortCodePattern],
) -> Result<Self, DialContextError> {
if let Some(index) = patterns.iter().position(|p| !p.is_valid()) {
return Err(DialContextError::ShortCodePattern { index });
}
self.short_codes = patterns;
self.checked()
}
pub fn with_area_code(mut self, area: &str) -> Result<Self, DialContextError> {
if self.closed {
return Err(DialContextError::ClosedPlan);
}
self.area_code = Some(area.parse().map_err(|_| DialContextError::AreaCode)?);
Ok(self)
}
fn checked(self) -> Result<Self, DialContextError> {
let overlap = |a: &str, b: &str| a.bytes().zip(b.bytes()).all(|(x, y)| x == y);
let prefixes = [Some(self.international_prefix), self.trunk_prefix];
if let [Some(intl), Some(trunk)] = prefixes
&& trunk.starts_with(intl)
{
return Err(DialContextError::PrefixesOverlap);
}
for prefix in prefixes.into_iter().flatten() {
if self.short_codes.iter().any(|p| overlap(p.prefix, prefix)) {
return Err(DialContextError::PrefixesOverlap);
}
}
Ok(self)
}
#[must_use]
pub const fn area_code(&self) -> Option<AreaCode> {
self.area_code
}
#[must_use]
pub const fn country_code(&self) -> u16 {
self.country_code
}
#[must_use]
pub const fn is_closed(&self) -> bool {
self.closed
}
pub fn normalise(&self, dialled: &str) -> Result<Destination, DialError> {
if dialled.len() > Self::MAX_DIALLED {
return Err(DialError::TooLong);
}
let zero_trunk = self.trunk_prefix == Some("0");
let mut digits = [0u8; Self::MAX_DIALLED];
let mut count = 0;
let mut plus = false;
let bytes = dialled.as_bytes();
let mut position = 0;
while position < bytes.len() {
match bytes[position] {
b @ b'0'..=b'9' => {
digits[count] = b - b'0';
count += 1;
}
b'(' if bytes[position..].starts_with(b"(0)") => {
if zero_trunk && self.after_own_country_code(plus, &digits[..count]) {
position += 3;
continue;
}
if !(zero_trunk && count == 0 && !plus) {
return Err(DialError::MisplacedTrunkDigit { position });
}
}
b' ' | b'-' | b'/' | b'(' | b')' | b'.' => {}
b'+' if count == 0 && !plus => plus = true,
b'+' => return Err(DialError::MisplacedPlus { position }),
_ => return Err(DialError::InvalidCharacter { position }),
}
position += 1;
}
let digits = &digits[..count];
if digits.is_empty() {
return Err(DialError::Empty);
}
if plus {
return international(digits);
}
if let Some(rest) = strip(digits, self.international_prefix) {
return international(rest);
}
if let Some(rest) = self.trunk_prefix.and_then(|t| strip(digits, t)) {
return self.national(rest);
}
if self.short_codes.iter().any(|p| p.matches(digits)) {
let code = collect(digits, ShortCode::MAX_DIGITS)
.and_then(ShortCode::from_digits)
.ok_or(DialError::InvalidShortCode)?;
return Ok(Destination::Short(code));
}
if self.short_codes.iter().any(|p| p.overlaps(digits)) {
return Err(DialError::InvalidShortCode);
}
if self.closed {
return self.national(digits);
}
match self.area_code {
Some(area) => {
let mut national = area.0;
for &d in digits {
national = national.checked_push(d).ok_or(DialError::NumberTooLong)?;
}
self.national_digits(national)
}
None => Err(DialError::AreaCodeRequired),
}
}
fn after_own_country_code(&self, plus: bool, digits: &[u8]) -> bool {
let rest = if plus {
Some(digits)
} else {
strip(digits, self.international_prefix)
};
rest == Some(CountryCodeDigits::of(self.country_code).as_slice())
}
fn national(&self, rest: &[u8]) -> Result<Destination, DialError> {
if rest.is_empty() {
return Err(DialError::MissingNumber);
}
let national = collect(rest, Msisdn::MAX_DIGITS).ok_or(DialError::NumberTooLong)?;
self.national_digits(national)
}
fn national_digits(&self, national: DigitString) -> Result<Destination, DialError> {
if self
.national_len
.is_some_and(|len| usize::from(len) != national.len())
{
return Err(DialError::NationalNumberLength);
}
let mut out = DigitString::EMPTY;
for &d in CountryCodeDigits::of(self.country_code).as_slice() {
out = out.checked_push(d).ok_or(DialError::NumberTooLong)?;
}
for i in 0..national.len() {
out = out
.checked_push(national.at(i))
.ok_or(DialError::NumberTooLong)?;
}
number(out)
}
}
struct CountryCodeDigits([u8; 3], usize);
impl CountryCodeDigits {
fn of(cc: u16) -> Self {
let all = [(cc / 100 % 10) as u8, (cc / 10 % 10) as u8, (cc % 10) as u8];
let start = all.iter().position(|&d| d != 0).unwrap_or(2);
Self(all, start)
}
fn as_slice(&self) -> &[u8] {
&self.0[self.1..]
}
}
fn is_digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
fn strip<'a>(digits: &'a [u8], prefix: &str) -> Option<&'a [u8]> {
if prefix.is_empty() || prefix.len() > digits.len() {
return None;
}
let matches = prefix
.bytes()
.zip(digits)
.all(|(p, &d)| p.is_ascii_digit() && p - b'0' == d);
matches.then(|| &digits[prefix.len()..])
}
fn collect(digits: &[u8], max: usize) -> Option<DigitString> {
if digits.len() > max {
return None;
}
digits
.iter()
.try_fold(DigitString::EMPTY, |acc, &d| acc.checked_push(d))
}
fn international(digits: &[u8]) -> Result<Destination, DialError> {
match digits.first() {
None => Err(DialError::MissingNumber),
Some(0) => Err(DialError::InvalidCountryCode),
Some(_) => number(collect(digits, Msisdn::MAX_DIGITS).ok_or(DialError::NumberTooLong)?),
}
}
fn number(digits: DigitString) -> Result<Destination, DialError> {
if digits.len() > Msisdn::MAX_DIGITS {
return Err(DialError::NumberTooLong);
}
Ok(Destination::Number(Msisdn::from_digits(digits)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[non_exhaustive]
pub enum DialContextError {
#[error("a country code is 1 to 999 (ITU-T E.164)")]
CountryCode,
#[error("the international prefix must be one or more digits")]
InternationalPrefix,
#[error("the trunk prefix must be one or more digits")]
TrunkPrefix,
#[error(
"the trunk prefix starts with the international prefix, or a short code starts like a prefix"
)]
PrefixesOverlap,
#[error("short-code pattern {index} is not a digit prefix for a code of 2 to 6 digits")]
ShortCodePattern {
index: usize,
},
#[error("the country code and the national number exceed 15 digits (ITU-T E.164)")]
NationalLength,
#[error("an area code is 1 to 5 digits, such as 30 or 030")]
AreaCode,
#[error("a closed numbering plan has no area code")]
ClosedPlan,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[non_exhaustive]
pub enum DialError {
#[error("the dialled string holds no digits")]
Empty,
#[error("the dialled string is longer than {} bytes", DialContext::MAX_DIALLED)]
TooLong,
#[error("invalid character at byte {position} of the dialled string")]
InvalidCharacter {
position: usize,
},
#[error("'+' at byte {position} is not at the start of the dialled string")]
MisplacedPlus {
position: usize,
},
#[error("'(0)' at byte {position} is not directly after the country code")]
MisplacedTrunkDigit {
position: usize,
},
#[error("the dialled string ends after its prefix")]
MissingNumber,
#[error("no country code starts with 0 (ITU-T E.164)")]
InvalidCountryCode,
#[error("the normalised number is longer than 15 digits (ITU-T E.164)")]
NumberTooLong,
#[error("the national number does not have the length the numbering plan fixes")]
NationalNumberLength,
#[error("a local number needs the subscriber's area code, and the dialling context has none")]
AreaCodeRequired,
#[error("starts like a short code but has another length")]
InvalidShortCode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DestinationClass {
Geographic,
Mobile,
Paging,
Freephone,
SharedCost,
Premium,
MassTraffic,
Personal,
NationalSubscriber,
Vpn,
OnlineService,
Directory,
Harmonised,
Emergency,
Authority,
NetworkInternal,
International,
}
impl DestinationClass {
pub const ALL: &'static [Self] = &[
Self::Geographic,
Self::Mobile,
Self::Paging,
Self::Freephone,
Self::SharedCost,
Self::Premium,
Self::MassTraffic,
Self::Personal,
Self::NationalSubscriber,
Self::Vpn,
Self::OnlineService,
Self::Directory,
Self::Harmonised,
Self::Emergency,
Self::Authority,
Self::NetworkInternal,
Self::International,
];
pub const CODES: &'static [&'static str] = &[
"GEOGRAPHIC",
"MOBILE",
"PAGING",
"FREEPHONE",
"SHARED_COST",
"PREMIUM",
"MASS_TRAFFIC",
"PERSONAL",
"NATIONAL_SUBSCRIBER",
"VPN",
"ONLINE_SERVICE",
"DIRECTORY",
"HARMONISED",
"EMERGENCY",
"AUTHORITY",
"NETWORK_INTERNAL",
"INTERNATIONAL",
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Geographic => "GEOGRAPHIC",
Self::Mobile => "MOBILE",
Self::Paging => "PAGING",
Self::Freephone => "FREEPHONE",
Self::SharedCost => "SHARED_COST",
Self::Premium => "PREMIUM",
Self::MassTraffic => "MASS_TRAFFIC",
Self::Personal => "PERSONAL",
Self::NationalSubscriber => "NATIONAL_SUBSCRIBER",
Self::Vpn => "VPN",
Self::OnlineService => "ONLINE_SERVICE",
Self::Directory => "DIRECTORY",
Self::Harmonised => "HARMONISED",
Self::Emergency => "EMERGENCY",
Self::Authority => "AUTHORITY",
Self::NetworkInternal => "NETWORK_INTERNAL",
Self::International => "INTERNATIONAL",
}
}
}
impl fmt::Display for DestinationClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for DestinationClass {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|c| c.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| ParseError::one_of("DestinationClass", s, Self::CODES))
}
}
pub trait NumberingPlan {
fn classify(&self, destination: &Destination) -> Option<DestinationClass>;
}
impl<F> NumberingPlan for F
where
F: Fn(&Destination) -> Option<DestinationClass>,
{
fn classify(&self, destination: &Destination) -> Option<DestinationClass> {
self(destination)
}
}
impl NumberingPlan for NumberRangeSet<DestinationClass> {
fn classify(&self, destination: &Destination) -> Option<DestinationClass> {
let number = destination.as_number()?;
let (_, classes) = self.longest_match_all(number)?;
let (first, rest) = classes.split_first()?;
rest.iter().all(|c| c == first).then_some(*first)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct GermanNumberingPlan;
impl GermanNumberingPlan {
pub const SOURCE: &'static str = "Bundesnetzagentur, Nummernplan Nummernraum für die \
öffentliche Telekommunikation (Vfg 29/2015 as amended by Vfg 92/2025), \
with the range plans for mobile, 0180, 0900, 0137, 032, 0700, 116 and 118";
pub const AS_OF: &'static str = "2025-11-06";
}
const GERMAN_RANGES: &[(&str, Option<DestinationClass>)] = {
use DestinationClass::{
Freephone, MassTraffic, Mobile, NationalSubscriber, NetworkInternal, OnlineService, Paging,
Personal, Premium, SharedCost, Vpn,
};
&[
("10", None),
("11", None),
("12", None),
("13", None),
("137", Some(MassTraffic)),
("1370", None),
("14", None),
("15", Some(Mobile)),
("16", None),
("160", Some(Mobile)),
("162", Some(Mobile)),
("163", Some(Mobile)),
("164", Some(Paging)),
("168", Some(Paging)),
("169", Some(Paging)),
("17", Some(Mobile)),
("18", Some(Vpn)),
("180", None),
("1801", Some(SharedCost)),
("1802", Some(SharedCost)),
("1803", Some(SharedCost)),
("1804", Some(SharedCost)),
("1805", Some(SharedCost)),
("1806", Some(SharedCost)),
("1807", Some(SharedCost)),
("19", None),
("191", Some(OnlineService)),
("192", Some(OnlineService)),
("193", Some(OnlineService)),
("194", Some(OnlineService)),
("199", Some(NetworkInternal)),
("31", None),
("32", Some(NationalSubscriber)),
("500", None),
("501", None),
("700", Some(Personal)),
("701", None),
("800", Some(Freephone)),
("801", None),
("900", Some(Premium)),
("9009", None),
("901", None),
("902", None),
("903", None),
("904", None),
("905", None),
]
};
fn digits_start_with(digits: DigitString, offset: usize, prefix: &str) -> bool {
prefix.len() + offset <= digits.len()
&& prefix
.bytes()
.enumerate()
.all(|(i, p)| digits.at(offset + i) == p - b'0')
}
impl NumberingPlan for GermanNumberingPlan {
fn classify(&self, destination: &Destination) -> Option<DestinationClass> {
match destination {
Destination::Short(code) => german_short_code(code.0),
Destination::Number(number) => {
let digits = number.digits();
if !digits_start_with(digits, 0, "49") {
return Some(DestinationClass::International);
}
match digits.len().saturating_sub(2) {
3 if digits_start_with(digits, 2, "115") => {
return Some(DestinationClass::Authority);
}
6 if digits_start_with(digits, 2, "116") => {
return Some(DestinationClass::Harmonised);
}
_ => {}
}
let longest = GERMAN_RANGES
.iter()
.filter(|(prefix, _)| digits_start_with(digits, 2, prefix))
.max_by_key(|(prefix, _)| prefix.len());
match longest {
Some((_, class)) => *class,
None if (2..=9).contains(&digits.at(2)) && digits.len() > 2 => {
Some(DestinationClass::Geographic)
}
None => None,
}
}
}
}
}
fn german_short_code(code: DigitString) -> Option<DestinationClass> {
let starts = |p: &str| digits_start_with(code, 0, p);
match code.len() {
3 if starts("110") || starts("112") => Some(DestinationClass::Emergency),
3 if starts("115") => Some(DestinationClass::Authority),
3 if ["111", "113", "114", "117", "119"]
.iter()
.any(|p| starts(p)) =>
{
Some(DestinationClass::NetworkInternal)
}
6 if starts("116") => Some(DestinationClass::Harmonised),
5 if starts("118") && !starts("1180") => Some(DestinationClass::Directory),
_ => None,
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{AreaCode, Destination, DestinationClass, ShortCode};
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!(
Destination,
"a destination such as \"+49301234567\" or \"110\""
);
string_serde!(ShortCode, "a short code such as \"116117\"");
string_serde!(AreaCode, "an area code such as \"30\"");
string_serde!(
DestinationClass,
"a destination class code such as \"MOBILE\""
);
}
#[cfg(test)]
mod tests {
use super::*;
fn de(area: &str) -> DialContext {
DialContext::germany().with_area_code(area).unwrap()
}
#[test]
fn plus_double_zero_and_trunk_agree() {
let c = de("30");
let a = c.normalise("+49 151 1234567").unwrap();
assert_eq!(c.normalise("0049-151-1234567").unwrap(), a);
assert_eq!(c.normalise("(0151) 1234567").unwrap(), a);
}
#[test]
fn plus_after_digit_is_refused() {
assert_eq!(
de("30").normalise("030+1234567"),
Err(DialError::MisplacedPlus { position: 3 })
);
}
#[test]
fn country_code_without_leading_zeros() {
let us = DialContext::new(1, "011")
.unwrap()
.with_area_code("212")
.unwrap();
assert_eq!(us.normalise("5551234").unwrap().to_string(), "+12125551234");
}
#[test]
fn unknown_ranges_stay_unclassified() {
for n in ["+49101234567", "+49900912345", "+491381234567", "+49121234"] {
let d: Destination = n.parse().unwrap();
assert_eq!(GermanNumberingPlan.classify(&d), None, "{n}");
}
}
}