1/*******************************************************************************
2 * Copyright (c) 2009, 2017 Mountainminds GmbH & Co. KG and Contributors
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 *    Marc R. Hoffmann - initial API and implementation
10 *
11 *******************************************************************************/
12package org.jacoco.report.internal.html.table;
13
14import java.util.ArrayList;
15import java.util.Collections;
16import java.util.Comparator;
17import java.util.List;
18
19/**
20 * A index on a list of items sorted with a given {@link Comparator}. The index
21 * does not change the list itself.
22 *
23 * @param <T>
24 *            type of the items
25 */
26final class SortIndex<T> {
27
28	private final Comparator<? super T> comparator;
29
30	private class Entry implements Comparable<Entry> {
31
32		final int idx;
33
34		final T item;
35
36		Entry(final int idx, final T item) {
37			this.idx = idx;
38			this.item = item;
39		}
40
41		public int compareTo(final Entry o) {
42			return comparator.compare(item, o.item);
43		}
44
45	}
46
47	private final List<Entry> list = new ArrayList<Entry>();
48
49	private int[] positions;
50
51	/**
52	 * Creates a new index based in the given comparator.
53	 *
54	 * @param comparator
55	 *            comparator to sort items
56	 */
57	public SortIndex(final Comparator<? super T> comparator) {
58		this.comparator = comparator;
59	}
60
61	/**
62	 * Initializes the index for the given list of items.
63	 *
64	 * @param items
65	 *            list of items
66	 */
67	public void init(final List<? extends T> items) {
68		this.list.clear();
69		int idx = 0;
70		for (final T i : items) {
71			final Entry entry = new Entry(idx++, i);
72			this.list.add(entry);
73		}
74		Collections.sort(list);
75		if (positions == null || positions.length < items.size()) {
76			positions = new int[items.size()];
77		}
78		int pos = 0;
79		for (final Entry e : this.list) {
80			positions[e.idx] = pos++;
81		}
82	}
83
84	/**
85	 * Returns the sorted position of the element with the given index in the
86	 * items list provided to the init() method.
87	 *
88	 * @param idx
89	 *            index of a element of the list
90	 * @return its position in a sorted list
91	 */
92	public int getPosition(final int idx) {
93		return positions[idx];
94	}
95
96}
97