Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mnc/mcc fields to Carrier #59

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 33 additions & 18 deletions src/carrier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,49 @@

use serde_derive::{Deserialize, Serialize};
use std::fmt;
use std::ops::Deref;

use crate::ParseError;

/// A phone number carrier.
/// see: https://en.wikipedia.org/wiki/Mobile_country_code#National_operators
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Hash, Debug)]
pub struct Carrier(pub(crate) String);

impl<T: Into<String>> From<T> for Carrier {
fn from(value: T) -> Carrier {
Carrier(value.into())
}
pub struct Carrier {
pub mcc: u16, // always 3 digits
pub mnc: u16, // 2 or 3 digits
}
Comment on lines +23 to 26
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this one of the rare occasions where we should prefer getters to fields? We might change the representation over time, e.g. by compressing mcc and mnc in a single u16.

Additionally, MNC 001 is not the same as MNC 01, so I'm not sure this representation is the safest.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point, I guess we could make it &str depending on the lifetime of PhoneNumber. I'll rework the PR ASAP.


impl Deref for Carrier {
type Target = str;

fn deref(&self) -> &str {
&self.0
}
}
impl TryFrom<&str> for Carrier {
type Error = ParseError;

impl AsRef<str> for Carrier {
fn as_ref(&self) -> &str {
&self.0
fn try_from(value: &str) -> Result<Self, Self::Error> {
Ok(Self {
mcc: value

Check warning on line 33 in src/carrier.rs

View workflow job for this annotation

GitHub Actions / clippy

unnecessary closure used to substitute value for `Option::None`
.get(0..3)
.and_then(|c| c.parse().ok())
.ok_or_else(|| ParseError::InvalidCountryCode)?,
mnc: value

Check warning on line 37 in src/carrier.rs

View workflow job for this annotation

GitHub Actions / clippy

unnecessary closure used to substitute value for `Option::None`
.get(3..)
.and_then(|c| c.parse().ok())
.ok_or_else(|| ParseError::InvalidNetworkCode)?,
})
}
}

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

#[cfg(test)]
mod test {
use std::convert::TryInto;
use super::Carrier;

#[test]
fn test_mobile_network_codes() {
assert_eq!(Carrier { mcc: 336, mnc: 1}, "336001".try_into().unwrap());
assert_eq!(Carrier { mcc: 336, mnc: 35}, "33635".try_into().unwrap());
}

}
8 changes: 6 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ pub enum Parse {
#[allow(unused)] // This is unused in the build script
NoNumber,

/// The country code supplied did not belong to a supported country or
/// non-geographical entity.
/// The country code supplied is not correct.
#[error("invalid country code")]
#[allow(unused)] // This is unused in the build script
InvalidCountryCode,

/// The network code supplied is not correct
#[error("invalid network code")]
#[allow(unused)] // This is unused in the build script
InvalidNetworkCode,

/// This indicates the string started with an international dialing prefix,
/// but after this was stripped from the number, had less digits than any
/// valid phone number (including country code) could have.
Expand Down
10 changes: 7 additions & 3 deletions src/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use crate::{
consts,
metadata::{Database, Format, Metadata, DATABASE},
phone_number::PhoneNumber,
phone_number::PhoneNumber, Carrier,
};
use std::{borrow::Cow, fmt};

Expand Down Expand Up @@ -234,7 +234,7 @@ fn replace(
meta: &Metadata,
formatter: &Format,
transform: Option<&str>,
carrier: Option<&str>,
carrier: Option<&Carrier>,
) -> String {
formatter
.pattern()
Expand All @@ -249,7 +249,11 @@ fn replace(
.as_str();
let format = transform.replace(*consts::NP, meta.national_prefix().unwrap_or(""));
let format = format.replace(*consts::FG, &format!("${}", first));
let format = format.replace(*consts::CC, carrier.unwrap_or(""));
let format = if let Some(carrier) = carrier.map(|c| c.to_string()) {
format.replace(*consts::CC, &carrier)
} else {
format.replace(*consts::CC, "")
};

consts::FIRST_GROUP.replace(formatter.format(), &*format)
} else {
Expand Down
10 changes: 7 additions & 3 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::carrier::Carrier;
use std::borrow::Borrow;

use crate::consts;
use crate::country;
use crate::error;
Expand Down Expand Up @@ -90,7 +91,10 @@ pub fn parse_with<S: AsRef<str>>(
),

extension: number.extension.map(|s| Extension(s.into_owned())),
carrier: number.carrier.map(|s| Carrier(s.into_owned())),
carrier: number.carrier.and_then(|s| {
let s: &str = s.borrow();
s.try_into().ok()
}),
})
}

Expand Down Expand Up @@ -263,7 +267,7 @@ mod test {
national: NationalNumber::new(3121286979, 0),

extension: None,
carrier: Some("12".into()),
carrier: "12".try_into().ok(),
},
parser::parse(Some(country::BR), "012 3121286979").unwrap()
);
Expand Down
Loading