-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathphonenumberutil.cc
More file actions
3309 lines (3109 loc) · 145 KB
/
phonenumberutil.cc
File metadata and controls
3309 lines (3109 loc) · 145 KB
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2009 The Libphonenumber Authors
//
// 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.
#include "phonenumbers/phonenumberutil.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <iterator>
#include <map>
#include <utility>
#include <vector>
#include <unicode/uchar.h>
#include <unicode/utf8.h>
#include "phonenumbers/asyoutypeformatter.h"
#include "phonenumbers/base/basictypes.h"
#include "phonenumbers/base/logging.h"
#include "phonenumbers/base/memory/singleton.h"
#include "phonenumbers/default_logger.h"
#include "phonenumbers/encoding_utils.h"
#include "phonenumbers/matcher_api.h"
#include "phonenumbers/metadata.h"
#include "phonenumbers/normalize_utf8.h"
#include "phonenumbers/phonemetadata.pb.h"
#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumber.pb.h"
#include "phonenumbers/regex_based_matcher.h"
#include "phonenumbers/regexp_adapter.h"
#include "phonenumbers/regexp_cache.h"
#include "phonenumbers/regexp_factory.h"
#include "phonenumbers/region_code.h"
#include "phonenumbers/stl_util.h"
#include "phonenumbers/stringutil.h"
#include "phonenumbers/utf/unicodetext.h"
#include "phonenumbers/utf/utf.h"
namespace i18n {
namespace phonenumbers {
using google::protobuf::RepeatedField;
using gtl::OrderByFirst;
// static constants
const size_t PhoneNumberUtil::kMinLengthForNsn;
const size_t PhoneNumberUtil::kMaxLengthForNsn;
const size_t PhoneNumberUtil::kMaxLengthCountryCode;
const int PhoneNumberUtil::kNanpaCountryCode;
// static
const char PhoneNumberUtil::kPlusChars[] = "+\xEF\xBC\x8B"; /* "++" */
// Regular expression of acceptable punctuation found in phone numbers, used to
// find numbers in text and to decide what is a viable phone number. This
// excludes diallable characters.
// This consists of dash characters, white space characters, full stops,
// slashes, square brackets, parentheses and tildes. It also includes the letter
// 'x' as that is found as a placeholder for carrier information in some phone
// numbers. Full-width variants are also present.
// To find out the unicode code-point of the characters below in vim, highlight
// the character and type 'ga'. Note that the - is used to express ranges of
// full-width punctuation below, as well as being present in the expression
// itself. In emacs, you can use M-x unicode-what to query information about the
// unicode character.
// static
const char PhoneNumberUtil::kValidPunctuation[] =
/* "-x‐-―−ー--/ <U+200B><U+2060> ()()[].\\[\\]/~⁓∼" */
"-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC"
"\x8F \xC2\xA0\xC2\xAD\xE2\x80\x8B\xE2\x81\xA0\xE3\x80\x80()\xEF\xBC\x88"
"\xEF\xBC\x89\xEF\xBC\xBB\xEF\xBC\xBD.\\[\\]/~\xE2\x81\x93\xE2\x88\xBC";
// static
const char PhoneNumberUtil::kCaptureUpToSecondNumberStart[] = "(.*)[\\\\/] *x";
// static
const char PhoneNumberUtil::kRegionCodeForNonGeoEntity[] = "001";
namespace {
// The kPlusSign signifies the international prefix.
const char kPlusSign[] = "+";
const char kStarSign[] = "*";
const char kRfc3966ExtnPrefix[] = ";ext=";
const char kRfc3966Prefix[] = "tel:";
const char kRfc3966PhoneContext[] = ";phone-context=";
const char kRfc3966IsdnSubaddress[] = ";isub=";
const char kRfc3966VisualSeparator[] = "[\\-\\.\\(\\)]?";
const char kDigits[] = "\\p{Nd}";
// We accept alpha characters in phone numbers, ASCII only. We store lower-case
// here only since our regular expressions are case-insensitive.
const char kValidAlpha[] = "a-z";
const char kValidAlphaInclUppercase[] = "A-Za-z";
// Default extension prefix to use when formatting. This will be put in front of
// any extension component of the number, after the main national number is
// formatted. For example, if you wish the default extension formatting to be "
// extn: 3456", then you should specify " extn: " here as the default extension
// prefix. This can be overridden by region-specific preferences.
const char kDefaultExtnPrefix[] = " ext. ";
const char kPossibleSeparatorsBetweenNumberAndExtLabel[] =
"[ \xC2\xA0\\t,]*";
// Optional full stop (.) or colon, followed by zero or more
// spaces/tabs/commas.
const char kPossibleCharsAfterExtLabel[] =
"[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*";
const char kOptionalExtSuffix[] = "#?";
bool LoadCompiledInMetadata(PhoneMetadataCollection* metadata) {
if (!metadata->ParseFromArray(metadata_get(), metadata_size())) {
LOG(ERROR) << "Could not parse binary data.";
return false;
}
return true;
}
// Returns a pointer to the description inside the metadata of the appropriate
// type.
const PhoneNumberDesc* GetNumberDescByType(
const PhoneMetadata& metadata,
PhoneNumberUtil::PhoneNumberType type) {
switch (type) {
case PhoneNumberUtil::PREMIUM_RATE:
return &metadata.premium_rate();
case PhoneNumberUtil::TOLL_FREE:
return &metadata.toll_free();
case PhoneNumberUtil::MOBILE:
return &metadata.mobile();
case PhoneNumberUtil::FIXED_LINE:
case PhoneNumberUtil::FIXED_LINE_OR_MOBILE:
return &metadata.fixed_line();
case PhoneNumberUtil::SHARED_COST:
return &metadata.shared_cost();
case PhoneNumberUtil::VOIP:
return &metadata.voip();
case PhoneNumberUtil::PERSONAL_NUMBER:
return &metadata.personal_number();
case PhoneNumberUtil::PAGER:
return &metadata.pager();
case PhoneNumberUtil::UAN:
return &metadata.uan();
case PhoneNumberUtil::VOICEMAIL:
return &metadata.voicemail();
default:
return &metadata.general_desc();
}
}
// A helper function that is used by Format and FormatByPattern.
void PrefixNumberWithCountryCallingCode(
int country_calling_code,
PhoneNumberUtil::PhoneNumberFormat number_format,
string* formatted_number) {
switch (number_format) {
case PhoneNumberUtil::E164:
formatted_number->insert(0, StrCat(kPlusSign, country_calling_code));
return;
case PhoneNumberUtil::INTERNATIONAL:
formatted_number->insert(0, StrCat(kPlusSign, country_calling_code, " "));
return;
case PhoneNumberUtil::RFC3966:
formatted_number->insert(0, StrCat(kRfc3966Prefix, kPlusSign,
country_calling_code, "-"));
return;
case PhoneNumberUtil::NATIONAL:
default:
// Do nothing.
return;
}
}
// Returns true when one national number is the suffix of the other or both are
// the same.
bool IsNationalNumberSuffixOfTheOther(const PhoneNumber& first_number,
const PhoneNumber& second_number) {
const string& first_number_national_number =
SimpleItoa(static_cast<uint64>(first_number.national_number()));
const string& second_number_national_number =
SimpleItoa(static_cast<uint64>(second_number.national_number()));
// Note that HasSuffixString returns true if the numbers are equal.
return HasSuffixString(first_number_national_number,
second_number_national_number) ||
HasSuffixString(second_number_national_number,
first_number_national_number);
}
char32 ToUnicodeCodepoint(const char* unicode_char) {
char32 codepoint;
EncodingUtils::DecodeUTF8Char(unicode_char, &codepoint);
return codepoint;
}
// Helper method for constructing regular expressions for parsing. Creates an
// expression that captures up to max_length digits.
std::string ExtnDigits(int max_length) {
return StrCat("([", kDigits, "]{1,", max_length, "})");
}
// Helper initialiser method to create the regular-expression pattern to match
// extensions. Note that:
// - There are currently six capturing groups for the extension itself. If this
// number is changed, MaybeStripExtension needs to be updated.
// - The only capturing groups should be around the digits that you want to
// capture as part of the extension, or else parsing will fail!
std::string CreateExtnPattern(bool for_parsing) {
// We cap the maximum length of an extension based on the ambiguity of the
// way the extension is prefixed. As per ITU, the officially allowed
// length for extensions is actually 40, but we don't support this since we
// haven't seen real examples and this introduces many false interpretations
// as the extension labels are not standardized.
int ext_limit_after_explicit_label = 20;
int ext_limit_after_likely_label = 15;
int ext_limit_after_ambiguous_char = 9;
int ext_limit_when_not_sure = 6;
// Canonical-equivalence doesn't seem to be an option with RE2, so we allow
// two options for representing any non-ASCII character like ó - the character
// itself, and one in the unicode decomposed form with the combining acute
// accent.
// Here the extension is called out in a more explicit way, i.e mentioning it
// obvious patterns like "ext.".
string explicit_ext_labels =
"(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?"
"\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|\xD0\xB4\xD0\xBE\xD0\xB1|"
"anexo)";
// One-character symbols that can be used to indicate an extension, and less
// commonly used or more ambiguous extension labels.
string ambiguous_ext_labels =
"(?:[x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E]|int|"
"\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94)";
// When extension is not separated clearly.
string ambiguous_separator = "[- ]+";
string rfc_extn = StrCat(kRfc3966ExtnPrefix,
ExtnDigits(ext_limit_after_explicit_label));
string explicit_extn = StrCat(
kPossibleSeparatorsBetweenNumberAndExtLabel,
explicit_ext_labels, kPossibleCharsAfterExtLabel,
ExtnDigits(ext_limit_after_explicit_label),
kOptionalExtSuffix);
string ambiguous_extn = StrCat(
kPossibleSeparatorsBetweenNumberAndExtLabel,
ambiguous_ext_labels, kPossibleCharsAfterExtLabel,
ExtnDigits(ext_limit_after_ambiguous_char),
kOptionalExtSuffix);
string american_style_extn_with_suffix = StrCat(
ambiguous_separator, ExtnDigits(ext_limit_when_not_sure), "#");
// The first regular expression covers RFC 3966 format, where the extension is
// added using ";ext=". The second more generic where extension is mentioned
// with explicit labels like "ext:". In both the above cases we allow more
// numbers in extension than any other extension labels. The third one
// captures when single character extension labels or less commonly used
// labels are present. In such cases we capture fewer extension digits in
// order to reduce the chance of falsely interpreting two numbers beside each
// other as a number + extension. The fourth one covers the special case of
// American numbers where the extension is written with a hash at the end,
// such as "- 503#".
string extension_pattern = StrCat(
rfc_extn, "|",
explicit_extn, "|",
ambiguous_extn, "|",
american_style_extn_with_suffix);
// Additional pattern that is supported when parsing extensions, not when
// matching.
if (for_parsing) {
// ",," is commonly used for auto dialling the extension when connected.
// Semi-colon works in Iphone and also in Android to pop up a button with
// the extension number following.
string auto_dialling_and_ext_labels_found = "(?:,{2}|;)";
// This is same as kPossibleSeparatorsBetweenNumberAndExtLabel, but not
// matching comma as extension label may have it.
string possible_separators_number_extLabel_no_comma = "[ \xC2\xA0\\t]*";
string auto_dialling_extn = StrCat(
possible_separators_number_extLabel_no_comma,
auto_dialling_and_ext_labels_found, kPossibleCharsAfterExtLabel,
ExtnDigits(ext_limit_after_likely_label),
kOptionalExtSuffix);
string only_commas_extn = StrCat(
possible_separators_number_extLabel_no_comma,
"(?:,)+", kPossibleCharsAfterExtLabel,
ExtnDigits(ext_limit_after_ambiguous_char),
kOptionalExtSuffix);
// Here the first pattern is exclusive for extension autodialling formats
// which are used when dialling and in this case we accept longer
// extensions. However, the second pattern is more liberal on number of
// commas that acts as extension labels, so we have strict cap on number of
// digits in such extensions.
return StrCat(extension_pattern, "|",
auto_dialling_extn, "|",
only_commas_extn);
}
return extension_pattern;
}
// Normalizes a string of characters representing a phone number by replacing
// all characters found in the accompanying map with the values therein, and
// stripping all other characters if remove_non_matches is true.
// Parameters:
// number - a pointer to a string of characters representing a phone number to
// be normalized.
// normalization_replacements - a mapping of characters to what they should be
// replaced by in the normalized version of the phone number
// remove_non_matches - indicates whether characters that are not able to be
// replaced should be stripped from the number. If this is false, they will be
// left unchanged in the number.
void NormalizeHelper(const std::map<char32, char>& normalization_replacements,
bool remove_non_matches,
string* number) {
DCHECK(number);
UnicodeText number_as_unicode;
number_as_unicode.PointToUTF8(number->data(), static_cast<int>(number->size()));
if (!number_as_unicode.UTF8WasValid()) {
// The input wasn't valid UTF-8. Produce an empty string to indicate an error.
number->clear();
return;
}
string normalized_number;
char unicode_char[5];
for (UnicodeText::const_iterator it = number_as_unicode.begin();
it != number_as_unicode.end();
++it) {
std::map<char32, char>::const_iterator found_glyph_pair =
normalization_replacements.find(*it);
if (found_glyph_pair != normalization_replacements.end()) {
normalized_number.push_back(found_glyph_pair->second);
} else if (!remove_non_matches) {
// Find out how long this unicode char is so we can append it all.
int char_len = it.get_utf8(unicode_char);
normalized_number.append(unicode_char, char_len);
}
// If neither of the above are true, we remove this character.
}
number->assign(normalized_number);
}
// Returns true if there is any possible number data set for a particular
// PhoneNumberDesc.
bool DescHasPossibleNumberData(const PhoneNumberDesc& desc) {
// If this is empty, it means numbers of this type inherit from the "general
// desc" -> the value "-1" means that no numbers exist for this type.
return desc.possible_length_size() != 1 || desc.possible_length(0) != -1;
}
// Note: DescHasData must account for any of MetadataFilter's
// excludableChildFields potentially being absent from the metadata. It must
// check them all. For any changes in DescHasData, ensure that all the
// excludableChildFields are still being checked. If your change is safe simply
// mention why during a review without needing to change MetadataFilter.
// Returns true if there is any data set for a particular PhoneNumberDesc.
bool DescHasData(const PhoneNumberDesc& desc) {
// Checking most properties since we don't know what's present, since a custom
// build may have stripped just one of them (e.g. USE_METADATA_LITE strips
// exampleNumber). We don't bother checking the PossibleLengthsLocalOnly,
// since if this is the only thing that's present we don't really support the
// type at all: no type-specific methods will work with only this data.
return desc.has_example_number() || DescHasPossibleNumberData(desc) ||
desc.has_national_number_pattern();
}
// Returns the types we have metadata for based on the PhoneMetadata object
// passed in.
void GetSupportedTypesForMetadata(
const PhoneMetadata& metadata,
std::set<PhoneNumberUtil::PhoneNumberType>* types) {
DCHECK(types);
for (int i = 0; i <= static_cast<int>(PhoneNumberUtil::kMaxNumberType); ++i) {
PhoneNumberUtil::PhoneNumberType type =
static_cast<PhoneNumberUtil::PhoneNumberType>(i);
if (type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE ||
type == PhoneNumberUtil::UNKNOWN) {
// Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and
// represents that a particular number type can't be
// determined) or UNKNOWN (the non-type).
continue;
}
if (DescHasData(*GetNumberDescByType(metadata, type))) {
types->insert(type);
}
}
}
// Helper method to check a number against possible lengths for this number
// type, and determine whether it matches, or is too short or too long.
PhoneNumberUtil::ValidationResult TestNumberLength(
const string& number, const PhoneMetadata& metadata,
PhoneNumberUtil::PhoneNumberType type) {
const PhoneNumberDesc* desc_for_type = GetNumberDescByType(metadata, type);
// There should always be "possibleLengths" set for every element. This is
// declared in the XML schema which is verified by
// PhoneNumberMetadataSchemaTest. For size efficiency, where a
// sub-description (e.g. fixed-line) has the same possibleLengths as the
// parent, this is missing, so we fall back to the general desc (where no
// numbers of the type exist at all, there is one possible length (-1) which
// is guaranteed not to match the length of any real phone number).
RepeatedField<int> possible_lengths =
desc_for_type->possible_length_size() == 0
? metadata.general_desc().possible_length()
: desc_for_type->possible_length();
RepeatedField<int> local_lengths =
desc_for_type->possible_length_local_only();
if (type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE) {
const PhoneNumberDesc* fixed_line_desc =
GetNumberDescByType(metadata, PhoneNumberUtil::FIXED_LINE);
if (!DescHasPossibleNumberData(*fixed_line_desc)) {
// The rare case has been encountered where no fixedLine data is available
// (true for some non-geographical entities), so we just check mobile.
return TestNumberLength(number, metadata, PhoneNumberUtil::MOBILE);
} else {
const PhoneNumberDesc* mobile_desc =
GetNumberDescByType(metadata, PhoneNumberUtil::MOBILE);
if (DescHasPossibleNumberData(*mobile_desc)) {
// Merge the mobile data in if there was any. Note that when adding the
// possible lengths from mobile, we have to again check they aren't
// empty since if they are this indicates they are the same as the
// general desc and should be obtained from there.
possible_lengths.MergeFrom(
mobile_desc->possible_length_size() == 0
? metadata.general_desc().possible_length()
: mobile_desc->possible_length());
std::sort(possible_lengths.begin(), possible_lengths.end());
if (local_lengths.size() == 0) {
local_lengths = mobile_desc->possible_length_local_only();
} else {
local_lengths.MergeFrom(mobile_desc->possible_length_local_only());
std::sort(local_lengths.begin(), local_lengths.end());
}
}
}
}
// If the type is not suported at all (indicated by the possible lengths
// containing -1 at this point) we return invalid length.
if (possible_lengths.Get(0) == -1) {
return PhoneNumberUtil::INVALID_LENGTH;
}
int actual_length = static_cast<int>(number.length());
// This is safe because there is never an overlap beween the possible lengths
// and the local-only lengths; this is checked at build time.
if (std::find(local_lengths.begin(), local_lengths.end(), actual_length) !=
local_lengths.end()) {
return PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY;
}
int minimum_length = possible_lengths.Get(0);
if (minimum_length == actual_length) {
return PhoneNumberUtil::IS_POSSIBLE;
} else if (minimum_length > actual_length) {
return PhoneNumberUtil::TOO_SHORT;
} else if (*(possible_lengths.end() - 1) < actual_length) {
return PhoneNumberUtil::TOO_LONG;
}
// We skip the first element; we've already checked it.
return std::find(possible_lengths.begin() + 1, possible_lengths.end(),
actual_length) != possible_lengths.end()
? PhoneNumberUtil::IS_POSSIBLE
: PhoneNumberUtil::INVALID_LENGTH;
}
// Helper method to check a number against possible lengths for this region,
// based on the metadata being passed in, and determine whether it matches, or
// is too short or too long.
PhoneNumberUtil::ValidationResult TestNumberLength(
const string& number, const PhoneMetadata& metadata) {
return TestNumberLength(number, metadata, PhoneNumberUtil::UNKNOWN);
}
// Returns a new phone number containing only the fields needed to uniquely
// identify a phone number, rather than any fields that capture the context in
// which the phone number was created.
// These fields correspond to those set in Parse() rather than
// ParseAndKeepRawInput().
void CopyCoreFieldsOnly(const PhoneNumber& number, PhoneNumber* pruned_number) {
pruned_number->set_country_code(number.country_code());
pruned_number->set_national_number(number.national_number());
if (!number.extension().empty()) {
pruned_number->set_extension(number.extension());
}
if (number.italian_leading_zero()) {
pruned_number->set_italian_leading_zero(true);
// This field is only relevant if there are leading zeros at all.
pruned_number->set_number_of_leading_zeros(
number.number_of_leading_zeros());
}
}
// Determines whether the given number is a national number match for the given
// PhoneNumberDesc. Does not check against possible lengths!
bool IsMatch(const MatcherApi& matcher_api,
const string& number, const PhoneNumberDesc& desc) {
return matcher_api.MatchNationalNumber(number, desc, false);
}
} // namespace
void PhoneNumberUtil::SetLogger(Logger* logger) {
logger_.reset(logger);
Logger::set_logger_impl(logger_.get());
}
class PhoneNumberRegExpsAndMappings {
private:
void InitializeMapsAndSets() {
diallable_char_mappings_.insert(std::make_pair('+', '+'));
diallable_char_mappings_.insert(std::make_pair('*', '*'));
diallable_char_mappings_.insert(std::make_pair('#', '#'));
// Here we insert all punctuation symbols that we wish to respect when
// formatting alpha numbers, as they show the intended number groupings.
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("-"), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xEF\xBC\x8D" /* "-" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x80\x90" /* "‐" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x80\x91" /* "‑" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x80\x92" /* "‒" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x80\x93" /* "–" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x80\x94" /* "—" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x80\x95" /* "―" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x88\x92" /* "−" */), '-'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("/"), '/'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xEF\xBC\x8F" /* "/" */), '/'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint(" "), ' '));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE3\x80\x80" /* " " */), ' '));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xE2\x81\xA0"), ' '));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("."), '.'));
all_plus_number_grouping_symbols_.insert(
std::make_pair(ToUnicodeCodepoint("\xEF\xBC\x8E" /* "." */), '.'));
// Only the upper-case letters are added here - the lower-case versions are
// added programmatically.
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("A"), '2'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("B"), '2'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("C"), '2'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("D"), '3'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("E"), '3'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("F"), '3'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("G"), '4'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("H"), '4'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("I"), '4'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("J"), '5'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("K"), '5'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("L"), '5'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("M"), '6'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("N"), '6'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("O"), '6'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("P"), '7'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("Q"), '7'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("R"), '7'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("S"), '7'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("T"), '8'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("U"), '8'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("V"), '8'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("W"), '9'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("X"), '9'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("Y"), '9'));
alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("Z"), '9'));
std::map<char32, char> lower_case_mappings;
std::map<char32, char> alpha_letters;
for (std::map<char32, char>::const_iterator it = alpha_mappings_.begin();
it != alpha_mappings_.end();
++it) {
// Convert all the upper-case ASCII letters to lower-case.
if (it->first < 128) {
char letter_as_upper = static_cast<char>(it->first);
char32 letter_as_lower = static_cast<char32>(tolower(letter_as_upper));
lower_case_mappings.insert(std::make_pair(letter_as_lower, it->second));
// Add the letters in both variants to the alpha_letters map. This just
// pairs each letter with its upper-case representation so that it can
// be retained when normalising alpha numbers.
alpha_letters.insert(std::make_pair(letter_as_lower, letter_as_upper));
alpha_letters.insert(std::make_pair(it->first, letter_as_upper));
}
}
// In the Java version we don't insert the lower-case mappings in the map,
// because we convert to upper case on the fly. Doing this here would
// involve pulling in all of ICU, which we don't want to do if we don't have
// to.
alpha_mappings_.insert(lower_case_mappings.begin(),
lower_case_mappings.end());
alpha_phone_mappings_.insert(alpha_mappings_.begin(),
alpha_mappings_.end());
all_plus_number_grouping_symbols_.insert(alpha_letters.begin(),
alpha_letters.end());
// Add the ASCII digits so that they don't get deleted by NormalizeHelper().
for (char c = '0'; c <= '9'; ++c) {
diallable_char_mappings_.insert(std::make_pair(c, c));
alpha_phone_mappings_.insert(std::make_pair(c, c));
all_plus_number_grouping_symbols_.insert(std::make_pair(c, c));
}
mobile_token_mappings_.insert(std::make_pair(54, '9'));
countries_without_national_prefix_with_area_codes_.insert(52); // Mexico
geo_mobile_countries_without_mobile_area_codes_.insert(86); // China
geo_mobile_countries_.insert(52); // Mexico
geo_mobile_countries_.insert(54); // Argentina
geo_mobile_countries_.insert(55); // Brazil
// Indonesia: some prefixes only (fixed CMDA wireless)
geo_mobile_countries_.insert(62);
geo_mobile_countries_.insert(
geo_mobile_countries_without_mobile_area_codes_.begin(),
geo_mobile_countries_without_mobile_area_codes_.end());
}
// Regular expression of viable phone numbers. This is location independent.
// Checks we have at least three leading digits, and only valid punctuation,
// alpha characters and digits in the phone number. Does not include extension
// data. The symbol 'x' is allowed here as valid punctuation since it is often
// used as a placeholder for carrier codes, for example in Brazilian phone
// numbers. We also allow multiple plus-signs at the start.
// Corresponds to the following:
// [digits]{minLengthNsn}|
// plus_sign*(([punctuation]|[star])*[digits]){3,}
// ([punctuation]|[star]|[digits]|[alpha])*
//
// The first reg-ex is to allow short numbers (two digits long) to be parsed
// if they are entered as "15" etc, but only if there is no punctuation in
// them. The second expression restricts the number of digits to three or
// more, but then allows them to be in international form, and to have
// alpha-characters and punctuation.
const string valid_phone_number_;
// Regexp of all possible ways to write extensions, for use when parsing. This
// will be run as a case-insensitive regexp match. Wide character versions are
// also provided after each ASCII version.
// For parsing, we are slightly more lenient in our interpretation than for
// matching. Here we allow "comma" and "semicolon" as possible extension
// indicators. When matching, these are hardly ever used to indicate this.
const string extn_patterns_for_parsing_;
// Regular expressions of different parts of the phone-context parameter,
// following the syntax defined in RFC3966.
const std::string rfc3966_phone_digit_;
const std::string alphanum_;
const std::string rfc3966_domainlabel_;
const std::string rfc3966_toplabel_;
public:
scoped_ptr<const AbstractRegExpFactory> regexp_factory_;
scoped_ptr<RegExpCache> regexp_cache_;
// A map that contains characters that are essential when dialling. That means
// any of the characters in this map must not be removed from a number when
// dialing, otherwise the call will not reach the intended destination.
std::map<char32, char> diallable_char_mappings_;
// These mappings map a character (key) to a specific digit that should
// replace it for normalization purposes.
std::map<char32, char> alpha_mappings_;
// For performance reasons, store a map of combining alpha_mappings with ASCII
// digits.
std::map<char32, char> alpha_phone_mappings_;
// Separate map of all symbols that we wish to retain when formatting alpha
// numbers. This includes digits, ascii letters and number grouping symbols
// such as "-" and " ".
std::map<char32, char> all_plus_number_grouping_symbols_;
// Map of country calling codes that use a mobile token before the area code.
// One example of when this is relevant is when determining the length of the
// national destination code, which should be the length of the area code plus
// the length of the mobile token.
std::map<int, char> mobile_token_mappings_;
// Set of country codes that doesn't have national prefix, but it has area
// codes.
std::set<int> countries_without_national_prefix_with_area_codes_;
// Set of country codes that have geographically assigned mobile numbers (see
// geo_mobile_countries_ below) which are not based on *area codes*. For
// example, in China mobile numbers start with a carrier indicator, and beyond
// that are geographically assigned: this carrier indicator is not considered
// to be an area code.
std::set<int> geo_mobile_countries_without_mobile_area_codes_;
// Set of country calling codes that have geographically assigned mobile
// numbers. This may not be complete; we add calling codes case by case, as we
// find geographical mobile numbers or hear from user reports.
std::set<int> geo_mobile_countries_;
// Pattern that makes it easy to distinguish whether a region has a single
// international dialing prefix or not. If a region has a single international
// prefix (e.g. 011 in USA), it will be represented as a string that contains
// a sequence of ASCII digits, and possibly a tilde, which signals waiting for
// the tone. If there are multiple available international prefixes in a
// region, they will be represented as a regex string that always contains one
// or more characters that are not ASCII digits or a tilde.
scoped_ptr<const RegExp> single_international_prefix_;
scoped_ptr<const RegExp> digits_pattern_;
scoped_ptr<const RegExp> capturing_digit_pattern_;
scoped_ptr<const RegExp> capturing_ascii_digits_pattern_;
// Regular expression of acceptable characters that may start a phone number
// for the purposes of parsing. This allows us to strip away meaningless
// prefixes to phone numbers that may be mistakenly given to us. This consists
// of digits, the plus symbol and arabic-indic digits. This does not contain
// alpha characters, although they may be used later in the number. It also
// does not include other punctuation, as this will be stripped later during
// parsing and is of no information value when parsing a number. The string
// starting with this valid character is captured.
// This corresponds to VALID_START_CHAR in the java version.
scoped_ptr<const RegExp> valid_start_char_pattern_;
// Regular expression of valid characters before a marker that might indicate
// a second number.
scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_;
// Regular expression of trailing characters that we want to remove. We remove
// all characters that are not alpha or numerical characters. The hash
// character is retained here, as it may signify the previous block was an
// extension. Note the capturing block at the start to capture the rest of the
// number if this was a match.
// This corresponds to UNWANTED_END_CHAR_PATTERN in the java version.
scoped_ptr<const RegExp> unwanted_end_char_pattern_;
// Regular expression of groups of valid punctuation characters.
scoped_ptr<const RegExp> separator_pattern_;
// Regexp of all possible ways to write extensions, for use when finding phone
// numbers in text. This will be run as a case-insensitive regexp match. Wide
// character versions are also provided after each ASCII version.
const string extn_patterns_for_matching_;
// Regexp of all known extension prefixes used by different regions followed
// by 1 or more valid digits, for use when parsing.
scoped_ptr<const RegExp> extn_pattern_;
// We append optionally the extension pattern to the end here, as a valid
// phone number may have an extension prefix appended, followed by 1 or more
// digits.
scoped_ptr<const RegExp> valid_phone_number_pattern_;
// We use this pattern to check if the phone number has at least three letters
// in it - if so, then we treat it as a number where some phone-number digits
// are represented by letters.
scoped_ptr<const RegExp> valid_alpha_phone_pattern_;
scoped_ptr<const RegExp> first_group_capturing_pattern_;
scoped_ptr<const RegExp> carrier_code_pattern_;
scoped_ptr<const RegExp> plus_chars_pattern_;
// Regular expression of valid global-number-digits for the phone-context
// parameter, following the syntax defined in RFC3966.
std::unique_ptr<const RegExp> rfc3966_global_number_digits_pattern_;
// Regular expression of valid domainname for the phone-context parameter,
// following the syntax defined in RFC3966.
std::unique_ptr<const RegExp> rfc3966_domainname_pattern_;
PhoneNumberRegExpsAndMappings()
: valid_phone_number_(
StrCat(kDigits, "{", PhoneNumberUtil::kMinLengthForNsn, "}|[",
PhoneNumberUtil::kPlusChars, "]*(?:[",
PhoneNumberUtil::kValidPunctuation, kStarSign, "]*",
kDigits, "){3,}[", PhoneNumberUtil::kValidPunctuation,
kStarSign, kValidAlpha, kDigits, "]*")),
extn_patterns_for_parsing_(CreateExtnPattern(/* for_parsing= */ true)),
rfc3966_phone_digit_(
StrCat("(", kDigits, "|", kRfc3966VisualSeparator, ")")),
alphanum_(StrCat(kValidAlphaInclUppercase, kDigits)),
rfc3966_domainlabel_(
StrCat("[", alphanum_, "]+((\\-)*[", alphanum_, "])*")),
rfc3966_toplabel_(StrCat("[", kValidAlphaInclUppercase,
"]+((\\-)*[", alphanum_, "])*")),
regexp_factory_(new RegExpFactory()),
regexp_cache_(new RegExpCache(*regexp_factory_.get(), 128)),
diallable_char_mappings_(),
alpha_mappings_(),
alpha_phone_mappings_(),
all_plus_number_grouping_symbols_(),
mobile_token_mappings_(),
countries_without_national_prefix_with_area_codes_(),
geo_mobile_countries_without_mobile_area_codes_(),
geo_mobile_countries_(),
single_international_prefix_(regexp_factory_->CreateRegExp(
/* "[\\d]+(?:[~⁓∼~][\\d]+)?" */
"[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?")),
digits_pattern_(
regexp_factory_->CreateRegExp(StrCat("[", kDigits, "]*"))),
capturing_digit_pattern_(
regexp_factory_->CreateRegExp(StrCat("([", kDigits, "])"))),
capturing_ascii_digits_pattern_(
regexp_factory_->CreateRegExp("(\\d+)")),
valid_start_char_pattern_(regexp_factory_->CreateRegExp(
StrCat("[", PhoneNumberUtil::kPlusChars, kDigits, "]"))),
capture_up_to_second_number_start_pattern_(
regexp_factory_->CreateRegExp(
PhoneNumberUtil::kCaptureUpToSecondNumberStart)),
unwanted_end_char_pattern_(
regexp_factory_->CreateRegExp("[^\\p{N}\\p{L}#]")),
separator_pattern_(regexp_factory_->CreateRegExp(
StrCat("[", PhoneNumberUtil::kValidPunctuation, "]+"))),
extn_patterns_for_matching_(
CreateExtnPattern(/* for_parsing= */ false)),
extn_pattern_(regexp_factory_->CreateRegExp(
StrCat("(?i)(?:", extn_patterns_for_parsing_, ")$"))),
valid_phone_number_pattern_(regexp_factory_->CreateRegExp(
StrCat("(?i)", valid_phone_number_,
"(?:", extn_patterns_for_parsing_, ")?"))),
valid_alpha_phone_pattern_(regexp_factory_->CreateRegExp(
StrCat("(?i)(?:.*?[", kValidAlpha, "]){3}"))),
// The first_group_capturing_pattern was originally set to $1 but there
// are some countries for which the first group is not used in the
// national pattern (e.g. Argentina) so the $1 group does not match
// correctly. Therefore, we use \d, so that the first group actually
// used in the pattern will be matched.
first_group_capturing_pattern_(
regexp_factory_->CreateRegExp("(\\$\\d)")),
carrier_code_pattern_(regexp_factory_->CreateRegExp("\\$CC")),
plus_chars_pattern_(regexp_factory_->CreateRegExp(
StrCat("[", PhoneNumberUtil::kPlusChars, "]+"))),
rfc3966_global_number_digits_pattern_(regexp_factory_->CreateRegExp(
StrCat("^\\", kPlusSign, rfc3966_phone_digit_, "*", kDigits,
rfc3966_phone_digit_, "*$"))),
rfc3966_domainname_pattern_(regexp_factory_->CreateRegExp(StrCat(
"^(", rfc3966_domainlabel_, "\\.)*", rfc3966_toplabel_, "\\.?$"))) {
InitializeMapsAndSets();
}
// This type is neither copyable nor movable.
PhoneNumberRegExpsAndMappings(const PhoneNumberRegExpsAndMappings&) = delete;
PhoneNumberRegExpsAndMappings& operator=(
const PhoneNumberRegExpsAndMappings&) = delete;
};
// Private constructor. Also takes care of initialisation.
PhoneNumberUtil::PhoneNumberUtil()
: logger_(Logger::set_logger_impl(new NullLogger())),
matcher_api_(new RegexBasedMatcher()),
reg_exps_(new PhoneNumberRegExpsAndMappings),
country_calling_code_to_region_code_map_(
new std::vector<IntRegionsPair>()),
nanpa_regions_(new absl::node_hash_set<string>()),
region_to_metadata_map_(new absl::node_hash_map<string, PhoneMetadata>()),
country_code_to_non_geographical_metadata_map_(
new absl::node_hash_map<int, PhoneMetadata>) {
Logger::set_logger_impl(logger_.get());
// TODO: Update the java version to put the contents of the init
// method inside the constructor as well to keep both in sync.
PhoneMetadataCollection metadata_collection;
if (!LoadCompiledInMetadata(&metadata_collection)) {
LOG(DFATAL) << "Could not parse compiled-in metadata.";
return;
}
// Storing data in a temporary map to make it easier to find other regions
// that share a country calling code when inserting data.
std::map<int, std::list<string>* > country_calling_code_to_region_map;
for (RepeatedPtrField<PhoneMetadata>::const_iterator it =
metadata_collection.metadata().begin();
it != metadata_collection.metadata().end();
++it) {
const string& region_code = it->id();
if (region_code == RegionCode::GetUnknown()) {
continue;
}
int country_calling_code = it->country_code();
if (kRegionCodeForNonGeoEntity == region_code) {
country_code_to_non_geographical_metadata_map_->insert(
std::make_pair(country_calling_code, *it));
} else {
region_to_metadata_map_->insert(std::make_pair(region_code, *it));
}
std::map<int, std::list<string>* >::iterator calling_code_in_map =
country_calling_code_to_region_map.find(country_calling_code);
if (calling_code_in_map != country_calling_code_to_region_map.end()) {
if (it->main_country_for_code()) {
calling_code_in_map->second->push_front(region_code);
} else {
calling_code_in_map->second->push_back(region_code);
}
} else {
// For most country calling codes, there will be only one region code.
std::list<string>* list_with_region_code = new std::list<string>();
list_with_region_code->push_back(region_code);
country_calling_code_to_region_map.insert(
std::make_pair(country_calling_code, list_with_region_code));
}
if (country_calling_code == kNanpaCountryCode) {
nanpa_regions_->insert(region_code);
}
}
country_calling_code_to_region_code_map_->insert(
country_calling_code_to_region_code_map_->begin(),
country_calling_code_to_region_map.begin(),
country_calling_code_to_region_map.end());
// Sort all the pairs in ascending order according to country calling code.
std::sort(country_calling_code_to_region_code_map_->begin(),
country_calling_code_to_region_code_map_->end(), OrderByFirst());
}
PhoneNumberUtil::~PhoneNumberUtil() {
gtl::STLDeleteContainerPairSecondPointers(
country_calling_code_to_region_code_map_->begin(),
country_calling_code_to_region_code_map_->end());
}
void PhoneNumberUtil::GetSupportedRegions(std::set<string>* regions)
const {
DCHECK(regions);
for (absl::node_hash_map<string, PhoneMetadata>::const_iterator it =
region_to_metadata_map_->begin(); it != region_to_metadata_map_->end();
++it) {
regions->insert(it->first);
}
}
void PhoneNumberUtil::GetSupportedGlobalNetworkCallingCodes(
std::set<int>* calling_codes) const {
DCHECK(calling_codes);
for (absl::node_hash_map<int, PhoneMetadata>::const_iterator it =
country_code_to_non_geographical_metadata_map_->begin();
it != country_code_to_non_geographical_metadata_map_->end(); ++it) {
calling_codes->insert(it->first);
}
}
void PhoneNumberUtil::GetSupportedCallingCodes(
std::set<int>* calling_codes) const {
DCHECK(calling_codes);
for (std::vector<IntRegionsPair>::const_iterator it =
country_calling_code_to_region_code_map_->begin();
it != country_calling_code_to_region_code_map_->end(); ++it) {
calling_codes->insert(it->first);
}
}
void PhoneNumberUtil::GetSupportedTypesForRegion(
const string& region_code,
std::set<PhoneNumberType>* types) const {
DCHECK(types);
if (!IsValidRegionCode(region_code)) {
LOG(WARNING) << "Invalid or unknown region code provided: " << region_code;
return;
}
const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
GetSupportedTypesForMetadata(*metadata, types);
}
void PhoneNumberUtil::GetSupportedTypesForNonGeoEntity(
int country_calling_code,
std::set<PhoneNumberType>* types) const {
DCHECK(types);
const PhoneMetadata* metadata =
GetMetadataForNonGeographicalRegion(country_calling_code);
if (metadata == NULL) {
LOG(WARNING) << "Unknown country calling code for a non-geographical "
<< "entity provided: "
<< country_calling_code;
return;
}
GetSupportedTypesForMetadata(*metadata, types);
}
// Public wrapper function to get a PhoneNumberUtil instance with the default
// metadata file.
// static
PhoneNumberUtil* PhoneNumberUtil::GetInstance() {
return Singleton<PhoneNumberUtil>::GetInstance();
}
const string& PhoneNumberUtil::GetExtnPatternsForMatching() const {
return reg_exps_->extn_patterns_for_matching_;
}
bool PhoneNumberUtil::StartsWithPlusCharsPattern(const string& number)
const {
const scoped_ptr<RegExpInput> number_string_piece(