aboutsummaryrefslogtreecommitdiffstats
path: root/org.jacoco.core/src/org/jacoco/core/analysis/StringPool.java
blob: 5386b31863809905c2a3765d1afc7fb5492b5a4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*******************************************************************************
 * Copyright (c) 2009, 2011 Mountainminds GmbH & Co. KG and Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Brock Janiczak - analysis and concept 
 *    Marc R. Hoffmann - initial API and implementation
 *    
 *******************************************************************************/
package org.jacoco.core.analysis;

import java.util.HashMap;
import java.util.Map;

/**
 * Utility to normalize {@link String} instances in a way that if
 * <code>equals()</code> is <code>true</code> for two strings they will be
 * represented the same instance. While this is exactly what
 * {@link String#intern()} does, this implementation avoids VM specific side
 * effects and is supposed to be faster, as neither native code is called nor
 * synchronization is required for concurrent lookup.
 * 
 * @author Marc R. Hoffmann
 * @version $qualified.bundle.version$
 */
public final class StringPool {

	private static final String[] EMPTY_ARRAY = new String[0];

	private final Map<String, String> pool = new HashMap<String, String>(1024);

	/**
	 * Returns a normalized instance that is equal to the given {@link String} .
	 * 
	 * @param s
	 *            any string or <code>null</code>
	 * @return normalized instance or <code>null</code>
	 */
	public String get(final String s) {
		if (s == null) {
			return null;
		}
		final String norm = pool.get(s);
		if (norm == null) {
			pool.put(s, s);
			return s;
		}
		return norm;
	}

	/**
	 * Returns a modified version of the array with all string slots normalized.
	 * It is up to the implementation to replace strings in the array instance
	 * or return a new array instance.
	 * 
	 * @param arr
	 *            String array or <code>null</code>
	 * @return normalized instance or <code>null</code>
	 */
	public String[] get(final String[] arr) {
		if (arr == null) {
			return null;
		}
		if (arr.length == 0) {
			return EMPTY_ARRAY;
		}
		for (int i = 0; i < arr.length; i++) {
			arr[i] = get(arr[i]);
		}
		return arr;
	}

}