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