• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Libphonenumber Authors
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 
17 package com.google.i18n.phonenumbers;
18 
19 import java.util.LinkedHashMap;
20 import java.util.Map;
21 import java.util.regex.Pattern;
22 
23 /**
24  * LRU Cache for compiled regular expressions used by the libphonenumbers libary.
25  *
26  * @author Shaopeng Jia
27  */
28 public class RegexCache {
29   private LRUCache<String, Pattern> cache;
30 
RegexCache(int size)31   public RegexCache(int size) {
32     cache = new LRUCache<String, Pattern>(size);
33   }
34 
getPatternForRegex(String regex)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   // @VisibleForTesting
containsRegex(String regex)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")
LRUCache(int size)55     public LRUCache(int size) {
56       this.size = size;
57       // Using access-order instead of insertion-order.
58       map = new LinkedHashMap<K, V>(size * 4 / 3 + 1, 0.75f, true) {
59         @Override
60         protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
61           return size() > LRUCache.this.size;
62         }
63       };
64     }
65 
get(K key)66     public synchronized V get(K key) {
67       return map.get(key);
68     }
69 
put(K key, V value)70     public synchronized void put(K key, V value) {
71       map.put(key, value);
72     }
73 
containsKey(K key)74     public synchronized boolean containsKey(K key) {
75       return map.containsKey(key);
76     }
77   }
78 }
79