1 /******************************************************************************* 2 * Copyright (c) 2009, 2021 Mountainminds GmbH & Co. KG and Contributors 3 * This program and the accompanying materials are made available under 4 * the terms of the Eclipse Public License 2.0 which is available at 5 * http://www.eclipse.org/legal/epl-2.0 6 * 7 * SPDX-License-Identifier: EPL-2.0 8 * 9 * Contributors: 10 * Brock Janiczak - analysis and concept 11 * Marc R. Hoffmann - initial API and implementation 12 * 13 *******************************************************************************/ 14 package org.jacoco.core.internal.analysis; 15 16 import java.util.HashMap; 17 import java.util.Map; 18 19 /** 20 * Utility to normalize {@link String} instances in a way that if 21 * <code>equals()</code> is <code>true</code> for two strings they will be 22 * represented the same instance. While this is exactly what 23 * {@link String#intern()} does, this implementation avoids VM specific side 24 * effects and is supposed to be faster, as neither native code is called nor 25 * synchronization is required for concurrent lookup. 26 */ 27 public final class StringPool { 28 29 private static final String[] EMPTY_ARRAY = new String[0]; 30 31 private final Map<String, String> pool = new HashMap<String, String>(1024); 32 33 /** 34 * Returns a normalized instance that is equal to the given {@link String} . 35 * 36 * @param s 37 * any string or <code>null</code> 38 * @return normalized instance or <code>null</code> 39 */ get(final String s)40 public String get(final String s) { 41 if (s == null) { 42 return null; 43 } 44 final String norm = pool.get(s); 45 if (norm == null) { 46 pool.put(s, s); 47 return s; 48 } 49 return norm; 50 } 51 52 /** 53 * Returns a modified version of the array with all string slots normalized. 54 * It is up to the implementation to replace strings in the array instance 55 * or return a new array instance. 56 * 57 * @param arr 58 * String array or <code>null</code> 59 * @return normalized instance or <code>null</code> 60 */ get(final String[] arr)61 public String[] get(final String[] arr) { 62 if (arr == null) { 63 return null; 64 } 65 if (arr.length == 0) { 66 return EMPTY_ARRAY; 67 } 68 for (int i = 0; i < arr.length; i++) { 69 arr[i] = get(arr[i]); 70 } 71 return arr; 72 } 73 74 } 75