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// RegExpCache is a simple wrapper around hash_map<> to store RegExp objects.
18//
19// To get a cached RegExp object for a regexp pattern string, call the
20// GetRegExp() method of the class RegExpCache providing the pattern string. If
21// a RegExp object corresponding to the pattern string doesn't already exist, it
22// will be created by the GetRegExp() method.
23//
24// RegExpCache cache;
25// const RegExp& regexp = cache.GetRegExp("\d");
26
27#ifndef I18N_PHONENUMBERS_REGEXP_CACHE_H_
28#define I18N_PHONENUMBERS_REGEXP_CACHE_H_
29
30#include <cstddef>
31#include <string>
32
33#include "phonenumbers/base/basictypes.h"
34#include "phonenumbers/base/memory/scoped_ptr.h"
35#include "phonenumbers/base/synchronization/lock.h"
36
37#ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP
38#  include <tr1/unordered_map>
39#else
40#  include <map>
41#endif
42
43namespace i18n {
44namespace phonenumbers {
45
46using std::string;
47
48class AbstractRegExpFactory;
49class RegExp;
50
51class RegExpCache {
52 private:
53#ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP
54  typedef std::tr1::unordered_map<string, const RegExp*> CacheImpl;
55#else
56  typedef std::map<string, const RegExp*> CacheImpl;
57#endif
58
59 public:
60  explicit RegExpCache(const AbstractRegExpFactory& regexp_factory,
61                       size_t min_items);
62  ~RegExpCache();
63
64  const RegExp& GetRegExp(const string& pattern);
65
66 private:
67  const AbstractRegExpFactory& regexp_factory_;
68  Lock lock_;  // protects cache_impl_
69  scoped_ptr<CacheImpl> cache_impl_;  // protected by lock_
70  friend class RegExpCacheTest_CacheConstructor_Test;
71  DISALLOW_COPY_AND_ASSIGN(RegExpCache);
72};
73
74}  // namespace phonenumbers
75}  // namespace i18n
76
77#endif  // I18N_PHONENUMBERS_REGEXP_CACHE_H_
78