57a139a46fb11eaa54fac751e2a2a6e4ca3f9b9a
[platform/upstream/libphonenumber.git] / cpp / src / phonenumbers / regexp_cache.cc
1 // Copyright (C) 2011 The Libphonenumber Authors
2 //
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
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 // Author: Fredrik Roubert
16
17 #include "phonenumbers/regexp_cache.h"
18
19 #include <cstddef>
20 #include <string>
21 #include <utility>
22
23 #include "phonenumbers/base/synchronization/lock.h"
24 #include "phonenumbers/regexp_adapter.h"
25
26 using std::make_pair;
27 using std::string;
28
29 namespace i18n {
30 namespace phonenumbers {
31
32 RegExpCache::RegExpCache(const AbstractRegExpFactory& regexp_factory,
33                          size_t min_items)
34     : regexp_factory_(regexp_factory),
35 #ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP
36       cache_impl_(new CacheImpl(min_items))
37 #else
38       cache_impl_(new CacheImpl())
39 #endif
40 {}
41
42 RegExpCache::~RegExpCache() {
43   AutoLock l(lock_);
44   for (CacheImpl::const_iterator
45        it = cache_impl_->begin(); it != cache_impl_->end(); ++it) {
46     delete it->second;
47   }
48 }
49
50 const RegExp& RegExpCache::GetRegExp(const string& pattern) {
51   AutoLock l(lock_);
52   CacheImpl::const_iterator it = cache_impl_->find(pattern);
53   if (it != cache_impl_->end()) return *it->second;
54
55   const RegExp* regexp = regexp_factory_.CreateRegExp(pattern);
56   cache_impl_->insert(make_pair(pattern, regexp));
57   return *regexp;
58 }
59
60 }  // namespace phonenumbers
61 }  // namespace i18n