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 public final class StringPool {
25 
26     private final String[] pool = new String[512];
27 
contentEquals(String s, char[] chars, int start, int length)28     private static boolean contentEquals(String s, char[] chars, int start, int length) {
29         if (s.length() != length) {
30             return false;
31         }
32         for (int i = 0; i < length; i++) {
33             if (chars[start + i] != s.charAt(i)) {
34                 return false;
35             }
36         }
37         return true;
38     }
39 
40     /**
41      * Returns a string equal to {@code new String(array, start, length)}.
42      */
get(char[] array, int start, int length)43     public String get(char[] array, int start, int length) {
44         // Compute an arbitrary hash of the content
45         int hashCode = 0;
46         for (int i = start; i < start + length; i++) {
47             hashCode = (hashCode * 31) + array[i];
48         }
49 
50         // Pick a bucket using Doug Lea's supplemental secondaryHash function (from HashMap)
51         hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
52         hashCode ^= (hashCode >>> 7) ^ (hashCode >>> 4);
53         int index = hashCode & (pool.length - 1);
54 
55         String pooled = pool[index];
56         if (pooled != null && contentEquals(pooled, array, start, length)) {
57             return pooled;
58         }
59 
60         String result = new String(array, start, length);
61         pool[index] = result;
62         return result;
63     }
64 }
65