1 // Copyright (C) 2012 The Libphonenumber Authors
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // Author: Patrick Mezard
17 #include "phonenumbers/geocoding/area_code_map.h"
21 #include "phonenumbers/geocoding/default_map_storage.h"
22 #include "phonenumbers/phonenumber.pb.h"
23 #include "phonenumbers/phonenumberutil.h"
24 #include "phonenumbers/stringutil.h"
27 namespace phonenumbers {
29 AreaCodeMap::AreaCodeMap()
30 : phone_util_(*PhoneNumberUtil::GetInstance()) {
33 AreaCodeMap::~AreaCodeMap() {
36 void AreaCodeMap::ReadAreaCodeMap(const PrefixDescriptions* descriptions) {
37 DefaultMapStorage* storage = new DefaultMapStorage();
38 storage->ReadFromMap(descriptions);
39 storage_.reset(storage);
42 const char* AreaCodeMap::Lookup(const PhoneNumber& number) const {
43 const int entries = storage_->GetNumOfEntries();
48 string national_number;
49 phone_util_.GetNationalSignificantNumber(number, &national_number);
51 safe_strto64(SimpleItoa(number.country_code()) + national_number,
54 const int* const lengths = storage_->GetPossibleLengths();
55 const int lengths_size = storage_->GetPossibleLengthsSize();
56 int current_index = entries - 1;
57 for (int lengths_index = lengths_size - 1; lengths_index >= 0;
59 const int possible_length = lengths[lengths_index];
60 string phone_prefix_str = SimpleItoa(phone_prefix);
61 if (static_cast<int>(phone_prefix_str.length()) > possible_length) {
62 safe_strto64(phone_prefix_str.substr(0, possible_length), &phone_prefix);
64 current_index = BinarySearch(0, current_index, phone_prefix);
65 if (current_index < 0) {
68 const int32 current_prefix = storage_->GetPrefix(current_index);
69 if (phone_prefix == current_prefix) {
70 return storage_->GetDescription(current_index);
76 int AreaCodeMap::BinarySearch(int start, int end, int64 value) const {
78 while (start <= end) {
79 current = (start + end) / 2;
80 int32 current_value = storage_->GetPrefix(current);
81 if (current_value == value) {
83 } else if (current_value > value) {
93 } // namespace phonenumbers