rlibphonenumber 2.1.0

A high-performance Rust port of Google's libphonenumber for parsing, formatting, and validating international phone numbers.
Documentation
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::ops::Deref;
use std::sync::Arc;

#[cfg(feature = "global_static")]
use std::sync::LazyLock;

use crate::alternate_formats::AlternateFormats;
use crate::enums::Region;
use crate::interfaces::AsOriginal;
use crate::phonenumber_matcher::leniency::Leniency;
use crate::phonenumber_matcher::matcher_internal::{
    PhoneNumberMatcher, PhoneNumberMatcherFallible,
};
use crate::phonenumber_matcher::matcher_regex::MatcherRegex;
use crate::phonenumberutil::phonenumberutil_internal::PhoneNumberUtilInternal;

#[cfg(feature = "global_static")]
use crate::{PHONE_NUMBER_UTIL, PhoneNumberUtil};

// =============================================================================
// PhoneNumberMatcherFactory
// =============================================================================

/// A factory for creating phone number matchers.
///
/// This struct holds the underlying utility and regex configurations
/// needed to efficiently parse text and extract phone numbers. By caching
/// the compiled regular expressions and alternate formats, it significantly
/// improves performance when creating matchers for multiple strings.
#[derive(Clone)]
pub struct PhoneNumberMatcherFactory<
    U: AsOriginal<PhoneNumberUtilInternal>,
    T: Deref<Target = U> + Clone,
> {
    regexps: Arc<MatcherRegex>,
    alternate_formats: Option<Arc<AlternateFormats>>,
    phone_util: T,
}

impl<U: AsOriginal<PhoneNumberUtilInternal>, T: Deref<Target = U> + Clone>
    PhoneNumberMatcherFactory<U, T>
{
    /// Creates a new factory using the provided phone utility instance.
    ///
    /// This constructor initializes the factory with default alternate formats.
    #[cfg(feature = "builtin_metadata")]
    pub fn new_for_util(phone_util: T) -> Self {
        Self::new_for_util_with_formats(phone_util, Some(Arc::new(AlternateFormats::new())))
    }

    /// Creates a new factory with a custom set of alternate formats.
    ///
    /// If `formats` is `None`, alternate format matching will be disabled.
    pub fn new_for_util_with_formats(
        phone_util: T,
        formats: Option<Arc<AlternateFormats>>,
    ) -> Self {
        Self {
            alternate_formats: formats,
            phone_util,
            regexps: Arc::new(MatcherRegex::new()),
        }
    }

    /// Starts building a matcher configuration via a fluent builder pattern.
    ///
    /// This is the recommended way to configure and instantiate a matcher,
    /// allowing you to specify leniency, maximum tries, and preferred region
    /// in a clear and readable manner.
    pub fn matcher_builder<'a, 'f>(&'f self, text: &'a str) -> MatcherBuilder<'a, 'f, U, T> {
        MatcherBuilder::new(self, text)
    }

    /// Creates a standard (infallible) matcher directly.
    ///
    /// The returned iterator yields valid phone numbers found in the text.
    /// Any underlying parsing errors will cause the segment to be skipped silently.
    ///
    /// *Note: Consider using[`matcher_builder`](Self::matcher_builder) instead for a more ergonomic API.*
    pub fn create_matcher<'a>(
        &self,
        text: &'a str,
        leniency: Leniency,
        max_tries: u64,
        preferred_region: Option<Region>,
    ) -> PhoneNumberMatcher<'a, U, T> {
        PhoneNumberMatcher::new_for_util(
            self.phone_util.clone(),
            self.regexps.clone(),
            text,
            preferred_region,
            leniency,
            max_tries,
            self.alternate_formats.clone(),
        )
    }

    /// Creates a fallible matcher directly.
    ///
    /// The returned iterator yields `Result` values, allowing the caller to handle
    /// and inspect parsing errors instead of silently skipping them.
    ///
    /// *Note: Consider using [`matcher_builder`](Self::matcher_builder) instead for a more ergonomic API.*
    pub fn create_matcher_fallible<'a>(
        &self,
        text: &'a str,
        leniency: Leniency,
        max_tries: u64,
        preferred_region: Option<Region>,
    ) -> PhoneNumberMatcherFallible<'a, U, T> {
        PhoneNumberMatcherFallible::new_for_util(
            self.phone_util.clone(),
            self.regexps.clone(),
            text,
            preferred_region,
            leniency,
            max_tries,
            self.alternate_formats.clone(),
        )
    }

    /// Creates a standard (infallible) matcher that auto-detects the region of
    /// national-format numbers instead of assuming a fixed one.
    ///
    /// Numbers written in international format are resolved exactly as with
    /// [`create_matcher`](Self::create_matcher). National-format numbers are
    /// tried against every supported region, preferring the most-recently
    /// matched one to keep ambiguous numbers stable and fast to resolve.
    ///
    /// * `initial_region` – an optional seed for the most-recently used region
    ///   (e.g. the region detected in a previously processed text chunk), or
    ///   `None` to start without a preference.
    ///
    /// *Note: Consider using [`matcher_builder`](Self::matcher_builder) instead for a more ergonomic API.*
    pub fn create_matcher_auto<'a>(
        &self,
        text: &'a str,
        leniency: Leniency,
        max_tries: u64,
        initial_region: Option<Region>,
    ) -> PhoneNumberMatcher<'a, U, T> {
        PhoneNumberMatcher::new_for_util_auto_region(
            self.phone_util.clone(),
            self.regexps.clone(),
            text,
            initial_region,
            leniency,
            max_tries,
            self.alternate_formats.clone(),
        )
    }

    /// Creates a fallible matcher that auto-detects the region of
    /// national-format numbers. See [`create_matcher_auto`](Self::create_matcher_auto)
    /// for the region-resolution behaviour and [`create_matcher_fallible`](Self::create_matcher_fallible)
    /// for the meaning of "fallible".
    pub fn create_matcher_auto_fallible<'a>(
        &self,
        text: &'a str,
        leniency: Leniency,
        max_tries: u64,
        initial_region: Option<Region>,
    ) -> PhoneNumberMatcherFallible<'a, U, T> {
        PhoneNumberMatcherFallible::new_for_util_auto_region(
            self.phone_util.clone(),
            self.regexps.clone(),
            text,
            initial_region,
            leniency,
            max_tries,
            self.alternate_formats.clone(),
        )
    }
}

#[cfg(feature = "global_static")]
impl PhoneNumberMatcherFactory<PhoneNumberUtil, &'static PhoneNumberUtil> {
    /// Creates a new factory using the globally static `PhoneNumberUtil`.
    pub fn new() -> Self {
        Self::new_for_util(&PHONE_NUMBER_UTIL)
    }
}

#[cfg(feature = "global_static")]
impl Default for PhoneNumberMatcherFactory<PhoneNumberUtil, &'static PhoneNumberUtil> {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// MatcherBuilder
// =============================================================================

/// How the matcher should determine the region of national-format numbers.
#[derive(Debug, Clone, Copy)]
enum RegionMode {
    /// Assume a single fixed region (`None` = only international `+` numbers).
    Fixed(Option<Region>),
    /// Auto-detect the region, optionally seeded with an initial most-recently
    /// used region hint.
    Auto(Option<Region>),
}

/// A fluent builder for configuring phone number matchers.
///
/// This builder allows you to chain configuration methods to set up the region,
/// strictness (leniency), and iteration limits before building the final matcher
/// iterator.
pub struct MatcherBuilder<
    'a,
    'f,
    U: AsOriginal<PhoneNumberUtilInternal>,
    T: Deref<Target = U> + Clone,
> {
    factory: &'f PhoneNumberMatcherFactory<U, T>,
    text: &'a str,
    leniency: Leniency,
    max_tries: u64,
    region_mode: RegionMode,
}

impl<'a, 'f, U: AsOriginal<PhoneNumberUtilInternal>, T: Deref<Target = U> + Clone>
    MatcherBuilder<'a, 'f, U, T>
{
    /// Constructs a new builder with sensible defaults.
    fn new(factory: &'f PhoneNumberMatcherFactory<U, T>, text: &'a str) -> Self {
        Self {
            factory,
            text,
            leniency: Leniency::Valid,            // Sensible default
            max_tries: u64::MAX,                  // Sensible default
            region_mode: RegionMode::Fixed(None), // Sensible default
        }
    }

    /// Sets the leniency level for the matcher.
    ///
    /// Leniency determines how strictly the text must comply to be considered
    /// a valid phone number. The default is `Leniency::Valid`.
    pub fn leniency(mut self, leniency: Leniency) -> Self {
        self.leniency = leniency;
        self
    }

    /// Sets the maximum number of iterations/tries.
    ///
    /// This is particularly useful for preventing excessive processing time
    /// on massive or highly complex strings. The default is `u64::MAX`.
    pub fn max_tries(mut self, max_tries: u64) -> Self {
        self.max_tries = max_tries;
        self
    }

    /// Sets the preferred region for parsing.
    ///
    /// The preferred region is used as a fallback for phone numbers that are
    /// found without explicit country codes (e.g., numbers without a `+` prefix).
    ///
    /// Calling this method switches the builder back to fixed-region mode,
    /// overriding any previous call to [`auto_region`](Self::auto_region).
    pub fn preferred_region(mut self, region: impl Into<Option<Region>>) -> Self {
        self.region_mode = RegionMode::Fixed(region.into());
        self
    }

    /// Enables automatic region detection.
    ///
    /// Instead of assuming a single region, national-format numbers are tried
    /// against every supported region until one yields a valid number,
    /// preferring the most-recently matched region. International (`+`) numbers
    /// are resolved from their own country code as usual.
    ///
    /// This is the recommended way to find numbers in text that may contain
    /// numbers from arbitrary regions. Note that it is more expensive than a
    /// fixed region, since a candidate may be tried against many regions.
    ///
    /// Calling this method overrides any previous call to
    /// [`preferred_region`](Self::preferred_region).
    pub fn auto_region(mut self) -> Self {
        self.region_mode = RegionMode::Auto(None);
        self
    }

    /// Like [`auto_region`](Self::auto_region), but seeds the most-recently
    /// used region with `region`.
    ///
    /// This is useful when processing text in independent chunks: pass the
    /// region detected in the previous chunk so that detection stays
    /// consistent across the boundary. Pass `None` for no initial preference.
    pub fn auto_region_with_hint(mut self, region: impl Into<Option<Region>>) -> Self {
        self.region_mode = RegionMode::Auto(region.into());
        self
    }

    /// Builds and returns the standard, infallible `PhoneNumberMatcher` iterator.
    ///
    /// Invalid phone numbers found in the text will be silently skipped.
    ///
    /// # Panics
    /// This iterator will **panic** if it encounters internal metadata errors
    /// (e.g., invalid regular expressions). If you are using the default built-in
    /// metadata, this will never happen. If you are using custom metadata, ensure
    /// it is pre-validated (e.g., via the `rlibphonenumber` CLI).
    pub fn build(self) -> PhoneNumberMatcher<'a, U, T> {
        match self.region_mode {
            RegionMode::Fixed(region) => {
                self.factory
                    .create_matcher(self.text, self.leniency, self.max_tries, region)
            }
            RegionMode::Auto(initial_region) => self.factory.create_matcher_auto(
                self.text,
                self.leniency,
                self.max_tries,
                initial_region,
            ),
        }
    }

    /// Builds and returns a `PhoneNumberMatcherFallible` iterator.
    ///
    /// This iterator yields `Result` values, providing access to underlying internal
    /// metadata errors instead of panicking.
    ///
    /// # Note on Errors
    /// The errors returned are **strictly internal errors** (e.g., malformed regexes
    /// from custom metadata), *not* text parsing errors. It is generally recommended
    /// to test custom metadata thoroughly using the `rlibphonenumber` CLI and use
    /// the infallible [`build`](Self::build) method instead.
    pub fn build_fallible(self) -> PhoneNumberMatcherFallible<'a, U, T> {
        match self.region_mode {
            RegionMode::Fixed(region) => self.factory.create_matcher_fallible(
                self.text,
                self.leniency,
                self.max_tries,
                region,
            ),
            RegionMode::Auto(initial_region) => self.factory.create_matcher_auto_fallible(
                self.text,
                self.leniency,
                self.max_tries,
                initial_region,
            ),
        }
    }
}

#[cfg(feature = "global_static")]
/// A globally available instance of `PhoneNumberMatcherFactory`.
///
/// This avoids the overhead of recompiling regexes and reallocating alternate
/// formats each time a matcher is needed.
pub static PHONE_MATCHER_FACTORY: LazyLock<
    PhoneNumberMatcherFactory<PhoneNumberUtil, &'static PhoneNumberUtil>,
> = LazyLock::new(PhoneNumberMatcherFactory::new);

// =============================================================================
// Extension Traits
// =============================================================================

#[cfg(feature = "global_static")]
/// Extension trait adding immediate phone number matching capabilities to strings.
///
/// This trait is available when the `global_static` feature is enabled. It provides
/// convenient methods directly on string types (`&str`, `String`) to find phone numbers
/// without having to manually instantiate factories or utilities.
pub trait FindNumberExt {
    /// Extracts valid phone numbers from the string using default settings.
    ///
    /// Uses `Leniency::Valid` and no preferred region.
    ///
    /// # Example
    /// ```rust
    /// use crate::rlibphonenumber::phonenumber_matcher::FindNumberExt;
    ///
    /// let text = "Call +1 555-0199 for more details.";
    /// for match_result in text.find_phone_numbers() {
    ///     // Process matches
    /// }
    /// ```
    fn find_phone_numbers(
        &self,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil>;

    /// Extracts phone numbers from the string using a specific leniency level.
    fn find_phone_numbers_with_leniency(
        &self,
        leniency: Leniency,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil>;

    /// Extracts phone numbers using a preferred region for numbers without country codes.
    fn find_phone_numbers_with_preferred_region(
        &self,
        region: impl Into<Option<Region>>,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil>;

    /// Extracts phone numbers without committing to a single region.
    ///
    /// National-format numbers are auto-detected by trying every supported
    /// region (preferring the most-recently matched one), while international
    /// (`+`) numbers are resolved from their own country code. Use this when
    /// the text may contain numbers from arbitrary regions.
    ///
    /// # Example
    /// ```rust
    /// use crate::rlibphonenumber::phonenumber_matcher::FindNumberExt;
    ///
    /// let text = "GB: 020 7183 8750, FR: 01 70 18 99 00";
    /// for number in text.find_phone_numbers_auto_region() {
    ///     // Each number carries the country code of its detected region.
    /// }
    /// ```
    fn find_phone_numbers_auto_region(
        &self,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil>;

    /// Returns a `MatcherBuilder` to fully configure the matching process directly
    /// from the string.
    ///
    /// # Example
    /// ```rust
    /// use crate::rlibphonenumber::phonenumber_matcher::FindNumberExt;
    /// use rlibphonenumber::phonenumber_matcher::Leniency;
    /// use rlibphonenumber::enums::Region;
    ///
    /// let text = "Contact us at 020 7183 8750";
    /// let matcher = text.phone_number_matcher_builder()
    ///     .leniency(Leniency::Possible)
    ///     .preferred_region(Region::GB)
    ///     .max_tries(10)
    ///     .build();
    /// ```
    fn phone_number_matcher_builder(
        &self,
    ) -> MatcherBuilder<'_, 'static, PhoneNumberUtil, &'static PhoneNumberUtil>;
}

#[cfg(feature = "global_static")]
impl FindNumberExt for str {
    fn find_phone_numbers(
        &self,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil> {
        self.phone_number_matcher_builder().build()
    }

    fn find_phone_numbers_with_leniency(
        &self,
        leniency: Leniency,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil> {
        self.phone_number_matcher_builder()
            .leniency(leniency)
            .build()
    }

    fn find_phone_numbers_with_preferred_region(
        &self,
        region: impl Into<Option<Region>>,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil> {
        self.phone_number_matcher_builder()
            .preferred_region(region)
            .build()
    }

    fn find_phone_numbers_auto_region(
        &self,
    ) -> PhoneNumberMatcher<'_, PhoneNumberUtil, &'static PhoneNumberUtil> {
        self.phone_number_matcher_builder().auto_region().build()
    }

    fn phone_number_matcher_builder(
        &self,
    ) -> MatcherBuilder<'_, 'static, PhoneNumberUtil, &'static PhoneNumberUtil> {
        PHONE_MATCHER_FACTORY.matcher_builder(self)
    }
}