OLD | NEW |
(Empty) | |
| 1 // Copyright (C) 2011 Google Inc. |
| 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 <roubert@google.com> |
| 16 |
| 17 #include "re2_cache.h" |
| 18 |
| 19 #include <cstddef> |
| 20 #include <string> |
| 21 #include <utility> |
| 22 |
| 23 #include <re2/re2.h> |
| 24 |
| 25 #include "base/logging.h" |
| 26 #include "base/synchronization/lock.h" |
| 27 |
| 28 using std::string; |
| 29 |
| 30 // A basic text book string hash function implementation, this one taken from |
| 31 // The Practice of Programming (Kernighan and Pike 1999). It could be a good |
| 32 // idea in the future to evaluate how well it actually performs and possibly |
| 33 // switch to another hash function better suited to this particular use case. |
| 34 namespace __gnu_cxx { |
| 35 template<> struct hash<string> { |
| 36 enum { MULTIPLIER = 31 }; |
| 37 size_t operator()(const string& key) const { |
| 38 size_t h = 0; |
| 39 for (const char* p = key.c_str(); *p != '\0'; ++p) { |
| 40 h *= MULTIPLIER; |
| 41 h += *p; |
| 42 } |
| 43 return h; |
| 44 } |
| 45 }; |
| 46 } // namespace __gnu_cxx |
| 47 |
| 48 namespace i18n { |
| 49 namespace phonenumbers { |
| 50 |
| 51 RE2Cache::RE2Cache(size_t min_items) : cache_impl_(new CacheImpl(min_items)) {} |
| 52 RE2Cache::~RE2Cache() { |
| 53 base::AutoLock l(lock_); |
| 54 LOG(2) << "Cache entries upon destruction: " << cache_impl_->size(); |
| 55 for (CacheImpl::const_iterator |
| 56 it = cache_impl_->begin(); it != cache_impl_->end(); ++it) { |
| 57 delete it->second; |
| 58 } |
| 59 } |
| 60 |
| 61 RE2Cache::ScopedAccess::ScopedAccess(RE2Cache* cache, const string& pattern) { |
| 62 DCHECK(cache); |
| 63 base::AutoLock l(cache->lock_); |
| 64 CacheImpl* const cache_impl = cache->cache_impl_.get(); |
| 65 CacheImpl::const_iterator it = cache_impl->find(pattern); |
| 66 if (it != cache_impl->end()) { |
| 67 regexp_ = it->second; |
| 68 } else { |
| 69 regexp_ = new RE2(pattern); |
| 70 cache_impl->insert(make_pair(pattern, regexp_)); |
| 71 } |
| 72 } |
| 73 |
| 74 } // namespace phonenumbers |
| 75 } // namespace i18n |
OLD | NEW |