1 /* 2 * Copyright (C) 2010 The Android Open Source Project 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 libcore.internal; 18 19 /** 20 * A pool of string instances. Unlike the {@link String#intern() VM's 21 * interned strings}, this pool provides no guarantee of reference equality. 22 * It is intended only to save allocations. This class is not thread safe. 23 * 24 * @hide 25 */ 26 public final class StringPool { 27 28 private final String[] pool = new String[512]; 29 StringPool()30 public StringPool() { 31 } 32 contentEquals(String s, char[] chars, int start, int length)33 private static boolean contentEquals(String s, char[] chars, int start, int length) { 34 if (s.length() != length) { 35 return false; 36 } 37 for (int i = 0; i < length; i++) { 38 if (chars[start + i] != s.charAt(i)) { 39 return false; 40 } 41 } 42 return true; 43 } 44 45 /** 46 * Returns a string equal to {@code new String(array, start, length)}. 47 */ get(char[] array, int start, int length)48 public String get(char[] array, int start, int length) { 49 // Compute an arbitrary hash of the content 50 int hashCode = 0; 51 for (int i = start; i < start + length; i++) { 52 hashCode = (hashCode * 31) + array[i]; 53 } 54 55 // Pick a bucket using Doug Lea's supplemental secondaryHash function (from HashMap) 56 hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12); 57 hashCode ^= (hashCode >>> 7) ^ (hashCode >>> 4); 58 int index = hashCode & (pool.length - 1); 59 60 String pooled = pool[index]; 61 if (pooled != null && contentEquals(pooled, array, start, length)) { 62 return pooled; 63 } 64 65 String result = new String(array, start, length); 66 pool[index] = result; 67 return result; 68 } 69 } 70