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