Skip to content

Commit

Permalink
Remove panic on TooLong in NationalNumber
Browse files Browse the repository at this point in the history
Fix #69
  • Loading branch information
rubdos committed Jul 7, 2024
1 parent 82f2d2e commit a01a7f1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
11 changes: 7 additions & 4 deletions src/national_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ pub struct NationalNumber {
}

impl NationalNumber {
pub fn new(value: u64, zeros: u8) -> Self {
pub fn new(value: u64, zeros: u8) -> Result<Self, crate::error::Parse> {
// E.164 specifies a maximum of 15 decimals, which corresponds to slightly over 48.9 bits.
// 56 bits ought to cut it here.
assert!(value < (1 << 56), "number too long");
Self {
value: ((zeros as u64) << 56) | value,
if value >= (1 << 56) {
return Err(crate::error::Parse::TooLong);
}

Ok(Self {
value: ((zeros as u64) << 56) | value,
})
}

/// The number without any leading zeroes.
Expand Down
14 changes: 7 additions & 7 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub fn parse_with<S: AsRef<str>>(
national: NationalNumber::new(
number.national.parse()?,
number.national.chars().take_while(|&c| c == '0').count() as u8,
),
)?,

extension: number.extension.map(|s| Extension(s.into_owned())),
carrier: number.carrier.map(|s| Carrier(s.into_owned())),
Expand All @@ -109,7 +109,7 @@ mod test {
source: country::Source::Default,
},

national: NationalNumber::new(33316005, 0),
national: NationalNumber::new(33316005, 0).unwrap(),

extension: None,
carrier: None,
Expand Down Expand Up @@ -197,7 +197,7 @@ mod test {
source: country::Source::Number,
},

national: NationalNumber::new(64123456, 0),
national: NationalNumber::new(64123456, 0).unwrap(),

extension: None,
carrier: None,
Expand All @@ -215,7 +215,7 @@ mod test {
source: country::Source::Default,
},

national: NationalNumber::new(30123456, 0),
national: NationalNumber::new(30123456, 0).unwrap(),

extension: None,
carrier: None,
Expand All @@ -230,7 +230,7 @@ mod test {
source: country::Source::Plus,
},

national: NationalNumber::new(2345, 0,),
national: NationalNumber::new(2345, 0,).unwrap(),

extension: None,
carrier: None,
Expand All @@ -245,7 +245,7 @@ mod test {
source: country::Source::Default,
},

national: NationalNumber::new(12, 0,),
national: NationalNumber::new(12, 0,).unwrap(),

extension: None,
carrier: None,
Expand All @@ -260,7 +260,7 @@ mod test {
source: country::Source::Default,
},

national: NationalNumber::new(3121286979, 0),
national: NationalNumber::new(3121286979, 0).unwrap(),

extension: None,
carrier: Some("12".into()),
Expand Down

0 comments on commit a01a7f1

Please sign in to comment.