Skip to main content

uz_types/
phone_number.rs

1use crate::macros::string_newtype;
2
3string_newtype! {
4    /// O'zbekiston telefon raqami — ichkarida har doim `998` + 9 raqam (12 raqam, `+` siz).
5    ///
6    /// `parse()` **strukturani** tekshiradi va formatga toqatli:
7    /// `+998 (90) 123-45-67`, `998.90.123.45.67`, `+998901234567` — hammasi `998901234567`.
8    /// Tashlab yuboriladigan ajratuvchilar: bo'shliq, `-`, `(`, `)`, `.` va boshidagi `+`.
9    /// Operator/hudud kodi ro'yxati — o'zgaruvchan biznes fakti — `parse` ichida emas:
10    /// [`PhoneNumber::is_known_operator`], [`PhoneNumber::is_mobile`] yoki [`PhoneNumber::parse_strict`].
11    pub struct PhoneNumber;
12    error = PhoneNumberError;
13    expecting = "an Uzbek phone number: 998 followed by 9 digits";
14}
15
16impl PhoneNumber {
17    /// `+` siz raqamlar soni.
18    pub const DIGIT_LEN: usize = 12;
19    /// Davlat kodi.
20    pub const COUNTRY_CODE: &str = "998";
21    /// Operator/hudud kodi uzunligi.
22    pub const OPERATOR_CODE_LEN: usize = 2;
23
24    /// Ma'lum mobil kodlar. **Slice** — yangi kod qo'shish breaking emas.
25    ///
26    /// Boshlang'ich reja: ITU'ning 2023-02-10 dagi
27    /// [E.164 yangilanishi](https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-OB.1263-2023-OAS-PDF-E.pdf).
28    /// Keyingi manbalar: [20](https://beeline.uz/uz/phone-codes) (2026-09-07 da
29    /// tekshirildi), [70](https://uztelecom.uz/uz/yangiliklar/yangiliklar/uztelecom-yangi-operator-kodi-plus998-70-ni-taqdim-etadi/)
30    /// (2025-03-19), [80](https://perfectum.uz/uz/cdma) (2026-09-07 da tekshirildi),
31    /// [87](https://company.mobi.uz/uz/press/2026/101857/) (2026-04-16) va
32    /// [92](https://beeline.uz/uz/events/news/novyy-kod-beeline-uzbekistan_92)
33    /// (7-noyabr; 2026-09-07 da tekshirildi).
34    ///
35    /// `70` kodi mobil va geografik xizmatlarda ishlatiladi, shuning uchun tasniflar
36    /// o'zaro istisno emas. Registry vaqt o'tishi bilan eskirishi mumkin;
37    /// [`parse`](Self::parse) undan foydalanmaydi.
38    pub const MOBILE_CODES: &[&str] = &[
39        "20", "33", "50", "70", "77", "80", "87", "88", "90", "91", "92", "93", "94", "95", "97",
40        "98", "99",
41    ];
42
43    /// Geografik PSTN kodlari.
44    ///
45    /// Manba: ITU'ning 2023-02-10 dagi
46    /// [O'zbekiston E.164 rejasi](https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-OB.1263-2023-OAS-PDF-E.pdf).
47    /// `70` keyinchalik mobil xizmatga ham ajratilgan; shu sabab u ikki to'plamda bor.
48    pub const GEOGRAPHIC_CODES: &[&str] = &[
49        "61", "62", "65", "66", "67", "69", "70", "71", "72", "73", "74", "75", "76", "79",
50    ];
51
52    /// SIP xizmat kodi.
53    ///
54    /// Manba: ITU'ning 2023-02-10 dagi
55    /// [O'zbekiston E.164 rejasi](https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-OB.1263-2023-OAS-PDF-E.pdf).
56    pub const SIP_CODES: &[&str] = &["55"];
57
58    /// Geografik bo'lmagan statsionar tarmoq xizmat kodi.
59    ///
60    /// Manba: ITU'ning 2023-02-10 dagi
61    /// [O'zbekiston E.164 rejasi](https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-OB.1263-2023-OAS-PDF-E.pdf).
62    pub const NON_GEOGRAPHIC_FIXED_CODES: &[&str] = &["78"];
63
64    /// Eski shahar/hudud oralig'i; aniq tasnif uchun ishlatilmaydi.
65    #[deprecated(note = "aniq hudud kodlari uchun PhoneNumber::GEOGRAPHIC_CODES dan foydalaning")]
66    pub const REGIONAL_CODES: core::ops::RangeInclusive<u8> = 60..=79;
67
68    fn normalize(s: &mut String) {
69        if s.starts_with('+') {
70            s.remove(0);
71        }
72        // Ajratuvchilar faqat kerak bo'lganda tozalanadi (tez yo'l: toza 12 raqam).
73        if !s.bytes().all(|b| b.is_ascii_digit()) {
74            s.retain(|c| !(c.is_ascii_whitespace() || matches!(c, '-' | '(' | ')' | '.')));
75        }
76    }
77
78    fn validate(s: &str) -> Result<(), PhoneNumberError> {
79        if !s.bytes().all(|b| b.is_ascii_digit()) {
80            return Err(PhoneNumberError::Format);
81        }
82        if s.len() != Self::DIGIT_LEN {
83            return Err(PhoneNumberError::Length);
84        }
85        if !s.starts_with(Self::COUNTRY_CODE) {
86            return Err(PhoneNumberError::Prefix);
87        }
88        Ok(())
89    }
90
91    /// Struktura + mobil/geografik/SIP/statsionar kod exact ro'yxatda bo'lishi shart.
92    ///
93    /// Ro'yxat crate bilan birga keladi va eskirishi mumkin. DB/Kafka/Serde replay
94    /// uchun [`parse`](Self::parse) ni, o'z registringiz bo'lsa
95    /// [`operator_code`](Self::operator_code) ni ishlating.
96    pub fn parse_strict(value: &str) -> Result<Self, PhoneNumberError> {
97        let phone = Self::parse(value)?;
98        if !phone.is_known_operator() {
99            return Err(PhoneNumberError::UnknownOperatorCode);
100        }
101        Ok(phone)
102    }
103
104    /// Kod (`90`, `71`) — xom, ro'yxatga qaramasdan.
105    ///
106    /// Bu crate registridan chiqish yo'li: kod ajratmalari vaqt bilan o'zgaradi va
107    /// crate snapshot'i eskirishi mumkin. Joriy ro'yxat sizga config yoki DB'dan
108    /// kelsa, `is_*()` metodlarini emas, shu accessor'ni ishlating — `parse()`
109    /// strukturasi barqaror qoladi, siyosat esa sizniki bo'ladi:
110    ///
111    /// ```
112    /// use uz_types::PhoneNumber;
113    ///
114    /// // Ro'yxat sizniki: config, DB yoki remote'dan keladi.
115    /// let allowed = ["90", "91", "99"];
116    ///
117    /// let phone = PhoneNumber::parse("998911234567").unwrap();
118    /// assert!(allowed.contains(&phone.operator_code()));
119    ///
120    /// // Crate registri hali bilmaydigan yangi kod ham shu yo'l bilan o'tadi.
121    /// let fresh = PhoneNumber::parse("998001234567").unwrap();
122    /// assert!(!fresh.is_known_operator());
123    /// assert_eq!(fresh.operator_code(), "00");
124    /// ```
125    #[inline]
126    #[must_use]
127    pub fn operator_code(&self) -> &str {
128        let start = Self::COUNTRY_CODE.len();
129        &self.0[start..start + Self::OPERATOR_CODE_LEN]
130    }
131
132    /// Abonent raqami (`1234567`).
133    #[inline]
134    #[must_use]
135    pub fn subscriber_number(&self) -> &str {
136        &self.0[Self::COUNTRY_CODE.len() + Self::OPERATOR_CODE_LEN..]
137    }
138
139    /// Kod crate'dagi mobil ro'yxatda bormi.
140    #[inline]
141    #[must_use]
142    pub fn is_mobile(&self) -> bool {
143        Self::MOBILE_CODES.contains(&self.operator_code())
144    }
145
146    /// Kod crate'dagi aniq geografik PSTN ro'yxatida bormi.
147    #[inline]
148    #[must_use]
149    pub fn is_geographic(&self) -> bool {
150        Self::GEOGRAPHIC_CODES.contains(&self.operator_code())
151    }
152
153    /// Kod crate'dagi SIP ro'yxatida bormi.
154    #[inline]
155    #[must_use]
156    pub fn is_sip(&self) -> bool {
157        Self::SIP_CODES.contains(&self.operator_code())
158    }
159
160    /// Kod crate'dagi geografik bo'lmagan statsionar ro'yxatda bormi.
161    #[inline]
162    #[must_use]
163    pub fn is_non_geographic_fixed(&self) -> bool {
164        Self::NON_GEOGRAPHIC_FIXED_CODES.contains(&self.operator_code())
165    }
166
167    /// Kod crate'dagi aniq mobil, geografik, SIP yoki statsionar ro'yxatda bormi.
168    ///
169    /// Bu **crate snapshot'iga** nisbatan javob, mutlaq haqiqat emas. Yangi kod
170    /// ajratilsa, crate yangilanmaguncha bu metod `false` qaytaradi va
171    /// [`parse_strict`](Self::parse_strict) rad etadi — [`parse`](Self::parse) esa
172    /// ta'sirlanmaydi. Registrni o'zingiz boshqarmoqchi bo'lsangiz
173    /// [`operator_code`](Self::operator_code) misoliga qarang.
174    #[must_use]
175    pub fn is_known_operator(&self) -> bool {
176        self.is_mobile() || self.is_geographic() || self.is_sip() || self.is_non_geographic_fixed()
177    }
178
179    /// `+998901234567` (yangi `String`).
180    #[must_use]
181    pub fn to_international(&self) -> String {
182        format!("+{}", self.0)
183    }
184}
185
186/// `PhoneNumber` validatsiya xatolari.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
188#[non_exhaustive]
189pub enum PhoneNumberError {
190    /// Raqamlar soni 12 emas.
191    #[error("phone number length is invalid, expected 12 digits")]
192    Length,
193    /// Raqamdan boshqa belgi.
194    #[error("phone number format is invalid")]
195    Format,
196    /// `998` bilan boshlanmaydi.
197    #[error("phone number must start with 998")]
198    Prefix,
199    /// Kod ro'yxatda yo'q (faqat `parse_strict`).
200    #[error("phone number has an unknown operator or region code")]
201    UnknownOperatorCode,
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn separators_are_tolerated() {
210        for input in [
211            "+998 (90) 123-45-67",
212            "998 90 123 45 67",
213            "+998901234567",
214            "998901234567",
215            " +998-90-123-45-67 ",
216            "998.90.123.45.67",
217            "+998 (90) 123.45.67",
218        ] {
219            assert_eq!(
220                PhoneNumber::parse(input).unwrap().as_str(),
221                "998901234567",
222                "{input}"
223            );
224        }
225    }
226
227    #[test]
228    fn structure_vs_registry() {
229        let fake = PhoneNumber::parse("998000000000").unwrap(); // struktura o'tadi
230        assert!(!fake.is_known_operator());
231        assert_eq!(
232            PhoneNumber::parse_strict("998000000000"),
233            Err(PhoneNumberError::UnknownOperatorCode)
234        );
235        assert!(
236            PhoneNumber::parse("998711234567")
237                .unwrap()
238                .is_known_operator()
239        );
240        assert_eq!(
241            PhoneNumber::parse("997901234567"),
242            Err(PhoneNumberError::Prefix)
243        );
244        assert_eq!(
245            PhoneNumber::parse("99890123456"),
246            Err(PhoneNumberError::Length)
247        );
248        assert_eq!(
249            PhoneNumber::parse("998a01234567"),
250            Err(PhoneNumberError::Format)
251        );
252        assert_eq!(
253            PhoneNumber::parse("998+901234567"),
254            Err(PhoneNumberError::Format)
255        );
256    }
257
258    fn with_code(code: &str) -> String {
259        format!("998{code}1234567")
260    }
261
262    #[test]
263    fn exact_code_sets_are_classified() {
264        assert_eq!(
265            PhoneNumber::MOBILE_CODES,
266            &[
267                "20", "33", "50", "70", "77", "80", "87", "88", "90", "91", "92", "93", "94", "95",
268                "97", "98", "99"
269            ]
270        );
271        assert_eq!(
272            PhoneNumber::GEOGRAPHIC_CODES,
273            &[
274                "61", "62", "65", "66", "67", "69", "70", "71", "72", "73", "74", "75", "76", "79"
275            ]
276        );
277        assert_eq!(PhoneNumber::SIP_CODES, &["55"]);
278        assert_eq!(PhoneNumber::NON_GEOGRAPHIC_FIXED_CODES, &["78"]);
279
280        let overlap = PhoneNumber::parse(&with_code("70")).unwrap();
281        assert!(overlap.is_mobile());
282        assert!(overlap.is_geographic());
283
284        for code in ["80", "87", "92"] {
285            let value = with_code(code);
286            let phone = PhoneNumber::parse_strict(&value).unwrap();
287            assert!(phone.is_mobile());
288        }
289
290        let sip = PhoneNumber::parse(&with_code("55")).unwrap();
291        assert!(sip.is_known_operator());
292        assert!(sip.is_sip());
293        assert!(!sip.is_mobile());
294
295        let fixed = PhoneNumber::parse(&with_code("78")).unwrap();
296        assert!(fixed.is_known_operator());
297        assert!(fixed.is_non_geographic_fixed());
298
299        let geographic = PhoneNumber::parse(&with_code("71")).unwrap();
300        assert!(geographic.is_geographic());
301        assert!(!geographic.is_mobile());
302    }
303
304    #[test]
305    fn unassigned_codes_are_only_structurally_valid() {
306        for code in ["00", "60", "63", "64", "68"] {
307            let value = with_code(code);
308            let phone = PhoneNumber::parse(&value).unwrap();
309            assert!(!phone.is_known_operator(), "{code}");
310            assert_eq!(
311                PhoneNumber::parse_strict(&value),
312                Err(PhoneNumberError::UnknownOperatorCode),
313                "{code}"
314            );
315        }
316    }
317}