Skip to main content

faker_rust/default/
phone_number.rs

1//! Phone number generator - generates random phone numbers
2
3use crate::base::{bothify, sample};
4use crate::config::FakerConfig;
5use crate::locale::fetch_locale;
6
7/// Generate a random phone number
8pub fn phone_number() -> String {
9    let formats = ["(###) ###-####",
10        "###-###-####",
11        "(###) ###-####",
12        "###.###.####",
13        "(###) ###-####",
14        "##########"];
15    let config = FakerConfig::current();
16    let format = formats[config.rand_usize(formats.len())];
17    bothify(format)
18}
19
20/// Generate a random phone number with country code
21pub fn phone_number_with_country_code() -> String {
22    let country_code = fetch_locale("phone_number.country_code", "en")
23        .map(|v| sample(&v))
24        .unwrap_or_else(|| "1".to_string());
25    format!("{} {}", country_code, phone_number())
26}
27
28/// Generate a random area code
29pub fn area_code() -> String {
30    fetch_locale("phone_number.area_code", "en")
31        .map(|v| sample(&v))
32        .unwrap_or_else(|| "212".to_string())
33}
34
35/// Generate a random cell phone number
36pub fn cell_phone() -> String {
37    let formats = ["(###) ###-####",
38        "###-###-####",
39        "(###) ###-####",
40        "##########",
41        "+1 (###) ###-####"];
42    let config = FakerConfig::current();
43    let format = formats[config.rand_usize(formats.len())];
44    bothify(format)
45}
46
47/// Generate a random cell phone number in E164 format
48pub fn cell_phone_in_e164() -> String {
49    format!(
50        "+1{}",
51        cell_phone().replace(|c: char| !c.is_ascii_digit(), "")
52    )
53}
54
55/// Generate a random cell phone with country code
56pub fn cell_phone_with_country_code() -> String {
57    let country_code = fetch_locale("phone_number.country_code", "en")
58        .map(|v| sample(&v))
59        .unwrap_or_else(|| "1".to_string());
60    format!("+{} {}", country_code, cell_phone())
61}
62
63/// Generate a random country code
64pub fn country_code() -> String {
65    fetch_locale("phone_number.country_code", "en")
66        .map(|v| sample(&v))
67        .unwrap_or_else(|| "1".to_string())
68}
69
70/// Generate a random extension
71pub fn extension() -> String {
72    let config = FakerConfig::current();
73    let len = config.rand_range(3, 6) as usize;
74    (0..len)
75        .map(|_| config.rand_char(&crate::base::DIGITS))
76        .collect()
77}
78
79/// Generate a random exchange code
80pub fn exchange_code() -> String {
81    let config = FakerConfig::current();
82    format!(
83        "{}{}{}",
84        config.rand_char(&crate::base::DIGITS),
85        config.rand_char(&crate::base::DIGITS),
86        config.rand_char(&crate::base::DIGITS)
87    )
88}
89
90/// Generate a random subscriber number
91pub fn subscriber_number() -> String {
92    bothify("####")
93}