2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.UnmodifiableIterator;
16 import java.io.Serializable;
17 import java.util.AbstractMap.SimpleImmutableEntry;
18 import java.util.AbstractSet;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Iterator;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
28 * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
29 * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
30 * class uses a global cache to share the key-to-offset mapping.
33 * In case the set of keys is statically known, you can use {@link ImmutableOffsetMapTemplate} to efficiently create
34 * {@link ImmutableOffsetMap} instances.
36 * @param <K> the type of keys maintained by this map
37 * @param <V> the type of mapped values
39 public abstract sealed class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
40 static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
42 private static final long serialVersionUID = 1L;
44 Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
45 super(offsets, objects);
49 public MutableOffsetMap<K, V> toModifiableMap() {
50 return MutableOffsetMap.orderedCopyOf(this);
54 Object writeReplace() {
55 return new OIOMv1(this);
59 static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
61 private static final long serialVersionUID = 1L;
63 Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
64 super(offsets, objects);
68 public MutableOffsetMap<K, V> toModifiableMap() {
69 return MutableOffsetMap.unorderedCopyOf(this);
73 Object writeReplace() {
74 return new UIOMv1(this);
79 private static final long serialVersionUID = 1L;
81 private final @NonNull ImmutableMap<K, Integer> offsets;
82 private final @NonNull V[] objects;
83 private transient int hashCode;
86 * Construct a new instance backed by specified key-to-offset map and array of objects.
88 * @param offsets Key-to-offset map, may not be null
89 * @param objects Array of value object, may not be null. The array is stored as is, the caller
90 * is responsible for ensuring its contents remain unmodified.
92 private ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
93 this.offsets = requireNonNull(offsets);
94 this.objects = requireNonNull(objects);
95 checkArgument(offsets.size() == objects.length);
99 public abstract @NonNull MutableOffsetMap<K, V> toModifiableMap();
102 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
103 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
104 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
105 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
106 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
107 * {@link ImmutableOffsetMap} with the same iteration order as input.
109 * @param <K> the type of keys maintained by the map
110 * @param <V> the type of mapped values
111 * @param map Input map, may not be null.
112 * @return An isolated, immutable copy of the input map
113 * @throws NullPointerException if {@code map} or any of its elements is null.
115 public static <K, V> @NonNull Map<K, V> orderedCopyOf(final @NonNull Map<K, V> map) {
116 final Map<K, V> common = commonCopy(map);
117 if (common != null) {
121 final int size = map.size();
123 // Efficient single-entry implementation
124 final Entry<K, V> e = map.entrySet().iterator().next();
125 return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
128 final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
129 return new Ordered<>(offsets, createArray(offsets, map));
133 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
134 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
135 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
136 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
137 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
138 * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
140 * @param <K> the type of keys maintained by the map
141 * @param <V> the type of mapped values
142 * @param map Input map, may not be null.
143 * @return An isolated, immutable copy of the input map
144 * @throws NullPointerException if {@code map} or any of its elements is null.
146 public static <K, V> @NonNull Map<K, V> unorderedCopyOf(final @NonNull Map<K, V> map) {
147 final Map<K, V> common = commonCopy(map);
148 if (common != null) {
152 if (map.size() == 1) {
153 // Efficient single-entry implementation
154 final Entry<K, V> e = map.entrySet().iterator().next();
155 return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
158 final ImmutableMap<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
159 return new Unordered<>(offsets, createArray(offsets, map));
162 private static <K, V> V[] createArray(final ImmutableMap<K, Integer> offsets, final Map<K, V> map) {
163 @SuppressWarnings("unchecked")
164 final V[] array = (V[]) new Object[offsets.size()];
165 for (Entry<K, V> e : map.entrySet()) {
166 array[verifyNotNull(offsets.get(e.getKey()))] = e.getValue();
171 private static <K, V> @Nullable Map<K, V> commonCopy(final @NonNull Map<K, V> map) {
172 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
173 if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
177 // Familiar and efficient to copy
178 if (map instanceof MutableOffsetMap<K, V> mop) {
179 return mop.toUnmodifiableMap();
183 // Shares a single object
184 return ImmutableMap.of();
191 public final int size() {
192 return offsets.size();
196 public final boolean isEmpty() {
197 return offsets.isEmpty();
201 public final int hashCode() {
207 for (Entry<K, Integer> e : offsets.entrySet()) {
208 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
216 public final boolean equals(final Object obj) {
220 if (!(obj instanceof Map<?, ?> other)) {
224 if (obj instanceof ImmutableOffsetMap<?, ?> om) {
225 // If the offset match, the arrays have to match, too
226 if (offsets.equals(om.offsets)) {
227 return Arrays.deepEquals(objects, om.objects);
229 } else if (obj instanceof MutableOffsetMap) {
230 // Let MutableOffsetMap do the actual work.
231 return obj.equals(this);
234 // Size and key sets have to match
235 if (size() != other.size() || !keySet().equals(other.keySet())) {
240 // Ensure all objects are present
241 for (Entry<K, Integer> e : offsets.entrySet()) {
242 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
246 } catch (ClassCastException e) {
247 // Can be thrown by other.get() indicating we have incompatible key types
255 public final boolean containsKey(final Object key) {
256 return offsets.containsKey(key);
260 public final boolean containsValue(final Object value) {
261 for (Object o : objects) {
262 if (value.equals(o)) {
270 public final V get(final Object key) {
272 return (offset = offsets.get(key)) == null ? null : objects[offset];
276 public final V remove(final Object key) {
277 throw new UnsupportedOperationException();
281 public final V put(final K key, final V value) {
282 throw new UnsupportedOperationException();
286 @SuppressWarnings("checkstyle:parameterName")
287 public final void putAll(final Map<? extends K, ? extends V> m) {
288 throw new UnsupportedOperationException();
292 public final void clear() {
293 throw new UnsupportedOperationException();
297 public final Set<K> keySet() {
298 return offsets.keySet();
302 public final @NonNull Collection<V> values() {
303 return new ConstantArrayCollection<>(objects);
307 public final @NonNull Set<Entry<K, V>> entrySet() {
308 return new EntrySet();
312 public final String toString() {
313 final StringBuilder sb = new StringBuilder("{");
314 final Iterator<K> it = offsets.keySet().iterator();
316 while (it.hasNext()) {
317 sb.append(it.next()).append('=').append(objects[offset++]);
324 return sb.append('}').toString();
327 final @NonNull ImmutableMap<K, Integer> offsets() {
331 final @NonNull V[] objects() {
335 private final class EntrySet extends AbstractSet<Entry<K, V>> {
337 public @NonNull Iterator<Entry<K, V>> iterator() {
338 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
339 return new UnmodifiableIterator<>() {
341 public boolean hasNext() {
346 public Entry<K, V> next() {
347 final Entry<K, Integer> e = it.next();
348 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
355 return offsets.size();
360 abstract Object writeReplace();