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 com.android.internal.util;
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 @android.ravenwood.annotation.RavenwoodKeepWholeClass
27 public final class StringPool {
28 
29     private final String[] mPool = new String[512];
30 
31     /**
32      * Constructs string pool.
33      */
StringPool()34     public StringPool() {
35     }
36 
contentEquals(String s, char[] chars, int start, int length)37     private static boolean contentEquals(String s, char[] chars, int start, int length) {
38         if (s.length() != length) {
39             return false;
40         }
41         for (int i = 0; i < length; i++) {
42             if (chars[start + i] != s.charAt(i)) {
43                 return false;
44             }
45         }
46         return true;
47     }
48 
49     /**
50      * Returns a string equal to {@code new String(array, start, length)}.
51      *
52      * @param array  buffer containing string chars
53      * @param start  offset in {@code array} where string starts
54      * @param length length of string
55      * @return string equal to {@code new String(array, start, length)}
56      */
get(char[] array, int start, int length)57     public String get(char[] array, int start, int length) {
58         // Compute an arbitrary hash of the content
59         int hashCode = 0;
60         for (int i = start; i < start + length; i++) {
61             hashCode = (hashCode * 31) + array[i];
62         }
63 
64         // Pick a bucket using Doug Lea's supplemental secondaryHash function (from HashMap)
65         hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
66         hashCode ^= (hashCode >>> 7) ^ (hashCode >>> 4);
67         int index = hashCode & (mPool.length - 1);
68 
69         String pooled = mPool[index];
70         if (pooled != null && contentEquals(pooled, array, start, length)) {
71             return pooled;
72         }
73 
74         String result = new String(array, start, length);
75         mPool[index] = result;
76         return result;
77     }
78 }
79