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 java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.UnmodifiableIterator;
16 import java.io.IOException;
17 import java.io.ObjectInputStream;
18 import java.io.ObjectOutputStream;
19 import java.io.Serializable;
20 import java.lang.reflect.Field;
21 import java.util.AbstractMap.SimpleImmutableEntry;
22 import java.util.AbstractSet;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.List;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
34 * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
35 * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
36 * class uses a global cache to share the key-to-offset mapping.
38 * @param <K> the type of keys maintained by this map
39 * @param <V> the type of mapped values
42 public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
43 static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
44 private static final long serialVersionUID = 1L;
46 Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
47 super(offsets, objects);
51 public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
52 return MutableOffsetMap.orderedCopyOf(this);
56 void setFields(final List<K> keys, final V[] values) throws IOException {
57 setField(this, OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys));
58 setField(this, ARRAY_FIELD, values);
62 static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
63 private static final long serialVersionUID = 1L;
65 Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
66 super(offsets, objects);
70 public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
71 return MutableOffsetMap.unorderedCopyOf(this);
75 void setFields(final List<K> keys, final V[] values) throws IOException {
76 final Map<K, Integer> newOffsets = OffsetMapCache.unorderedOffsets(keys);
78 setField(this, OFFSETS_FIELD, newOffsets);
79 setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(newOffsets, keys, values));
83 private static final long serialVersionUID = 1L;
85 private final transient @NonNull ImmutableMap<K, Integer> offsets;
86 private final transient @NonNull V[] objects;
87 private transient int hashCode;
90 * Construct a new instance backed by specified key-to-offset map and array of objects.
92 * @param offsets Key-to-offset map, may not be null
93 * @param objects Array of value object, may not be null. The array is stored as is, the caller
94 * is responsible for ensuring its contents remain unmodified.
96 ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
97 this.offsets = requireNonNull(offsets);
98 this.objects = requireNonNull(objects);
99 checkArgument(offsets.size() == objects.length);
103 public abstract @NonNull MutableOffsetMap<K, V> toModifiableMap();
105 abstract void setFields(List<K> keys, V[] values) throws IOException;
108 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
109 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
110 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
111 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
112 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
113 * {@link ImmutableOffsetMap} with the same iteration order as input.
115 * @param map Input map, may not be null.
116 * @return An isolated, immutable copy of the input map
117 * @throws NullPointerException if {@code map} or any of its elements is null.
119 public static <K, V> @NonNull Map<K, V> orderedCopyOf(final @NonNull Map<K, V> map) {
120 final Map<K, V> common = commonCopy(map);
121 if (common != null) {
125 final int size = map.size();
127 // Efficient single-entry implementation
128 final Entry<K, V> e = map.entrySet().iterator().next();
129 return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
132 final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
133 @SuppressWarnings("unchecked")
134 final V[] array = (V[]) new Object[offsets.size()];
135 for (Entry<K, V> e : map.entrySet()) {
136 array[offsets.get(e.getKey())] = e.getValue();
139 return new Ordered<>(offsets, array);
143 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
144 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
145 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
146 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
147 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
148 * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
150 * @param map Input map, may not be null.
151 * @return An isolated, immutable copy of the input map
152 * @throws NullPointerException if {@code map} or any of its elements is null.
154 public static <K, V> @NonNull Map<K, V> unorderedCopyOf(final @NonNull Map<K, V> map) {
155 final Map<K, V> common = commonCopy(map);
156 if (common != null) {
160 final int size = map.size();
162 // Efficient single-entry implementation
163 final Entry<K, V> e = map.entrySet().iterator().next();
164 return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
167 final ImmutableMap<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
168 @SuppressWarnings("unchecked")
169 final V[] array = (V[]) new Object[offsets.size()];
170 for (Entry<K, V> e : map.entrySet()) {
171 array[offsets.get(e.getKey())] = e.getValue();
174 return new Unordered<>(offsets, array);
177 private static <K, V> @Nullable Map<K, V> commonCopy(final @NonNull Map<K, V> map) {
178 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
179 if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
183 // Familiar and efficient to copy
184 if (map instanceof MutableOffsetMap) {
185 return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
189 // Shares a single object
190 return ImmutableMap.of();
197 public final int size() {
198 return offsets.size();
202 public final boolean isEmpty() {
203 return offsets.isEmpty();
207 public final int hashCode() {
213 for (Entry<K, Integer> e : offsets.entrySet()) {
214 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
222 public final boolean equals(final Object obj) {
226 if (!(obj instanceof Map)) {
230 if (obj instanceof ImmutableOffsetMap) {
231 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
233 // If the offset match, the arrays have to match, too
234 if (offsets.equals(om.offsets)) {
235 return Arrays.deepEquals(objects, om.objects);
237 } else if (obj instanceof MutableOffsetMap) {
238 // Let MutableOffsetMap do the actual work.
239 return obj.equals(this);
242 final Map<?, ?> other = (Map<?, ?>)obj;
244 // Size and key sets have to match
245 if (size() != other.size() || !keySet().equals(other.keySet())) {
250 // Ensure all objects are present
251 for (Entry<K, Integer> e : offsets.entrySet()) {
252 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
256 } catch (ClassCastException e) {
257 // Can be thrown by other.get() indicating we have incompatible key types
265 public final boolean containsKey(final Object key) {
266 return offsets.containsKey(key);
270 public final boolean containsValue(final Object value) {
271 for (Object o : objects) {
272 if (value.equals(o)) {
280 public final V get(final Object key) {
281 final Integer offset = offsets.get(key);
282 return offset == null ? null : objects[offset];
286 public final V remove(final Object key) {
287 throw new UnsupportedOperationException();
291 public final V put(final K key, final V value) {
292 throw new UnsupportedOperationException();
296 @SuppressWarnings("checkstyle:parameterName")
297 public final void putAll(final Map<? extends K, ? extends V> m) {
298 throw new UnsupportedOperationException();
302 public final void clear() {
303 throw new UnsupportedOperationException();
307 public final Set<K> keySet() {
308 return offsets.keySet();
312 public final @NonNull Collection<V> values() {
313 return new ConstantArrayCollection<>(objects);
317 public final @NonNull Set<Entry<K, V>> entrySet() {
318 return new EntrySet();
322 public final String toString() {
323 final StringBuilder sb = new StringBuilder("{");
324 final Iterator<K> it = offsets.keySet().iterator();
326 while (it.hasNext()) {
327 sb.append(it.next());
329 sb.append(objects[offset++]);
336 return sb.append('}').toString();
339 final @NonNull ImmutableMap<K, Integer> offsets() {
343 final @NonNull V[] objects() {
347 private final class EntrySet extends AbstractSet<Entry<K, V>> {
349 public @NonNull Iterator<Entry<K, V>> iterator() {
350 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
351 return new UnmodifiableIterator<Entry<K, V>>() {
353 public boolean hasNext() {
358 public Entry<K, V> next() {
359 final Entry<K, Integer> e = it.next();
360 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
367 return offsets.size();
371 private void writeObject(final ObjectOutputStream out) throws IOException {
372 out.writeInt(offsets.size());
373 for (Entry<K, V> e : entrySet()) {
374 out.writeObject(e.getKey());
375 out.writeObject(e.getValue());
379 private static final Field OFFSETS_FIELD = fieldFor("offsets");
380 private static final Field ARRAY_FIELD = fieldFor("objects");
382 private static @NonNull Field fieldFor(final @NonNull String name) {
385 f = ImmutableOffsetMap.class.getDeclaredField(name);
386 } catch (NoSuchFieldException | SecurityException e) {
387 throw new IllegalStateException("Failed to lookup field " + name, e);
390 f.setAccessible(true);
394 private static void setField(final @NonNull ImmutableOffsetMap<?, ?> map, final @NonNull Field field,
395 final Object value) throws IOException {
397 field.set(map, value);
398 } catch (IllegalArgumentException | IllegalAccessException e) {
399 throw new IOException("Failed to set field " + field, e);
403 @SuppressWarnings("unchecked")
404 private void readObject(final @NonNull ObjectInputStream in) throws IOException, ClassNotFoundException {
405 final int s = in.readInt();
407 final List<K> keys = new ArrayList<>(s);
408 final V[] values = (V[]) new Object[s];
410 for (int i = 0; i < s; ++i) {
411 keys.add((K)in.readObject());
412 values[i] = (V)in.readObject();
415 setFields(keys, values);