-
Notifications
You must be signed in to change notification settings - Fork 54
/
national_number.rs
76 lines (68 loc) · 2.73 KB
/
national_number.rs
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
// Copyright (C) 2017 1aim GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use serde_derive::{Deserialize, Serialize};
use std::fmt;
/// The national number part of a phone number.
#[derive(Copy, Clone, Eq, PartialEq, Serialize, Deserialize, Hash, Debug)]
pub struct NationalNumber {
pub(crate) value: u64,
}
impl NationalNumber {
pub fn new(value: u64, zeros: u8) -> Self {
// 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,
}
}
/// The number without any leading zeroes.
pub fn value(&self) -> u64 {
self.value & 0x00ffffffffffffff
}
/// The number of leading zeroes.
///
/// In some countries, the national (significant) number starts with one or
/// more "0"s without this being a national prefix or trunk code of some
/// kind. For example, the leading zero in the national (significant) number
/// of an Italian phone number indicates the number is a fixed-line number.
/// There have been plans to migrate fixed-line numbers to start with the
/// digit two since December 2000, but it has not happened yet. See
/// http://en.wikipedia.org/wiki/%2B39 for more details.
///
/// These fields can be safely ignored (there is no need to set them) for
/// most countries. Some limited number of countries behave like Italy - for
/// these cases, if the leading zero(s) of a number would be retained even
/// when dialling internationally, set this flag to true, and also set the
/// number of leading zeros.
///
/// Clients who use the parsing or conversion functionality of the i18n phone
/// number libraries will have these fields set if necessary automatically.
pub fn zeros(&self) -> u8 {
(self.value >> 56) as u8
}
}
impl From<NationalNumber> for u64 {
fn from(n: NationalNumber) -> u64 {
n.value
}
}
impl fmt::Display for NationalNumber {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for _ in 0..self.zeros() {
write!(f, "0")?;
}
write!(f, "{}", self.value())
}
}