1/*
2 * Copyright (C) 2010 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.i18n.phonenumbers;
18
19import java.util.LinkedHashMap;
20import java.util.Map;
21import java.util.regex.Pattern;
22
23/**
24 * LRU Cache for compiled regular expressions used by the libphonenumbers libary.
25 *
26 * @author Shaopeng Jia
27 */
28public class RegexCache {
29  private LRUCache<String, Pattern> cache;
30
31  public RegexCache(int size) {
32    cache = new LRUCache<String, Pattern>(size);
33  }
34
35  public Pattern getPatternForRegex(String regex) {
36    Pattern pattern = cache.get(regex);
37    if (pattern == null) {
38      pattern = Pattern.compile(regex);
39      cache.put(regex, pattern);
40    }
41    return pattern;
42  }
43
44  // This method is used for testing.
45  boolean containsRegex(String regex) {
46    return cache.containsKey(regex);
47  }
48
49  private static class LRUCache<K, V> {
50    // LinkedHashMap offers a straightforward implementation of LRU cache.
51    private LinkedHashMap<K, V> map;
52    private int size;
53
54    @SuppressWarnings("serial")
55    public LRUCache(int size) {
56      this.size = size;
57      map = new LinkedHashMap<K, V>(size * 4 / 3 + 1, 0.75f, true) {
58        @Override
59        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
60          return size() > LRUCache.this.size;
61        }
62      };
63    }
64
65    public synchronized V get(K key) {
66      return map.get(key);
67    }
68
69    public synchronized void put(K key, V value) {
70      map.put(key, value);
71    }
72
73    public synchronized boolean containsKey(K key) {
74      return map.containsKey(key);
75    }
76  }
77}
78
79