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