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 javax.annotation.Nonnull;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
35 * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
36 * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
37 * class uses a global cache to share the key-to-offset mapping.
39 * @param <K> the type of keys maintained by this map
40 * @param <V> the type of mapped values
43 public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
44 static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
45 private static final long serialVersionUID = 1L;
47 Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
48 super(offsets, objects);
53 public MutableOffsetMap<K, V> toModifiableMap() {
54 return MutableOffsetMap.orderedCopyOf(this);
58 void setFields(final List<K> keys, final V[] values) throws IOException {
59 setField(this, OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys));
60 setField(this, ARRAY_FIELD, values);
64 static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
65 private static final long serialVersionUID = 1L;
67 Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
68 super(offsets, objects);
73 public MutableOffsetMap<K, V> toModifiableMap() {
74 return MutableOffsetMap.unorderedCopyOf(this);
78 void setFields(final List<K> keys, final V[] values) throws IOException {
79 final Map<K, Integer> newOffsets = OffsetMapCache.unorderedOffsets(keys);
81 setField(this, OFFSETS_FIELD, newOffsets);
82 setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(newOffsets, keys, values));
86 private static final long serialVersionUID = 1L;
88 private final transient @NonNull ImmutableMap<K, Integer> offsets;
89 private final transient @NonNull V[] objects;
90 private transient int hashCode;
93 * Construct a new instance backed by specified key-to-offset map and array of objects.
95 * @param offsets Key-to-offset map, may not be null
96 * @param objects Array of value object, may not be null. The array is stored as is, the caller
97 * is responsible for ensuring its contents remain unmodified.
99 ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
100 this.offsets = requireNonNull(offsets);
101 this.objects = requireNonNull(objects);
102 checkArgument(offsets.size() == objects.length);
107 public abstract MutableOffsetMap<K, V> toModifiableMap();
109 abstract void setFields(List<K> keys, V[] values) throws IOException;
112 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
113 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
114 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
115 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
116 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
117 * {@link ImmutableOffsetMap} with the same iteration order as input.
119 * @param map Input map, may not be null.
120 * @return An isolated, immutable copy of the input map
121 * @throws NullPointerException if {@code map} or any of its elements is null.
123 @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> map) {
124 final Map<K, V> common = commonCopy(map);
125 if (common != null) {
129 final int size = map.size();
131 // Efficient single-entry implementation
132 final Entry<K, V> e = map.entrySet().iterator().next();
133 return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
136 final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
137 @SuppressWarnings("unchecked")
138 final V[] array = (V[]) new Object[offsets.size()];
139 for (Entry<K, V> e : map.entrySet()) {
140 array[offsets.get(e.getKey())] = e.getValue();
143 return new Ordered<>(offsets, array);
147 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
148 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
149 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
150 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
151 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
152 * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
154 * @param map Input map, may not be null.
155 * @return An isolated, immutable copy of the input map
156 * @throws NullPointerException if {@code map} or any of its elements is null.
158 @Nonnull public static <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> map) {
159 final Map<K, V> common = commonCopy(map);
160 if (common != null) {
164 final int size = map.size();
166 // Efficient single-entry implementation
167 final Entry<K, V> e = map.entrySet().iterator().next();
168 return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
171 final ImmutableMap<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
172 @SuppressWarnings("unchecked")
173 final V[] array = (V[]) new Object[offsets.size()];
174 for (Entry<K, V> e : map.entrySet()) {
175 array[offsets.get(e.getKey())] = e.getValue();
178 return new Unordered<>(offsets, array);
181 private static <K, V> @Nullable Map<K, V> commonCopy(@Nonnull final Map<K, V> map) {
182 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
183 if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
187 // Familiar and efficient to copy
188 if (map instanceof MutableOffsetMap) {
189 return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
193 // Shares a single object
194 return ImmutableMap.of();
201 public final int size() {
202 return offsets.size();
206 public final boolean isEmpty() {
207 return offsets.isEmpty();
211 public final int hashCode() {
217 for (Entry<K, Integer> e : offsets.entrySet()) {
218 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
226 public final boolean equals(final Object obj) {
230 if (!(obj instanceof Map)) {
234 if (obj instanceof ImmutableOffsetMap) {
235 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
237 // If the offset match, the arrays have to match, too
238 if (offsets.equals(om.offsets)) {
239 return Arrays.deepEquals(objects, om.objects);
241 } else if (obj instanceof MutableOffsetMap) {
242 // Let MutableOffsetMap do the actual work.
243 return obj.equals(this);
246 final Map<?, ?> other = (Map<?, ?>)obj;
248 // Size and key sets have to match
249 if (size() != other.size() || !keySet().equals(other.keySet())) {
254 // Ensure all objects are present
255 for (Entry<K, Integer> e : offsets.entrySet()) {
256 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
260 } catch (ClassCastException e) {
261 // Can be thrown by other.get() indicating we have incompatible key types
269 public final boolean containsKey(final Object key) {
270 return offsets.containsKey(key);
274 public final boolean containsValue(final Object value) {
275 for (Object o : objects) {
276 if (value.equals(o)) {
284 public final V get(final Object key) {
285 final Integer offset = offsets.get(key);
286 return offset == null ? null : objects[offset];
290 public final V remove(final Object key) {
291 throw new UnsupportedOperationException();
295 public final V put(final K key, final V value) {
296 throw new UnsupportedOperationException();
300 @SuppressWarnings("checkstyle:parameterName")
301 public final void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
302 throw new UnsupportedOperationException();
306 public final void clear() {
307 throw new UnsupportedOperationException();
311 public final Set<K> keySet() {
312 return offsets.keySet();
317 public final Collection<V> values() {
318 return new ConstantArrayCollection<>(objects);
323 public final Set<Entry<K, V>> entrySet() {
324 return new EntrySet();
328 public final String toString() {
329 final StringBuilder sb = new StringBuilder("{");
330 final Iterator<K> it = offsets.keySet().iterator();
332 while (it.hasNext()) {
333 sb.append(it.next());
335 sb.append(objects[offset++]);
342 return sb.append('}').toString();
345 final @NonNull ImmutableMap<K, Integer> offsets() {
349 final V[] objects() {
353 private final class EntrySet extends AbstractSet<Entry<K, V>> {
356 public Iterator<Entry<K, V>> iterator() {
357 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
359 return new UnmodifiableIterator<Entry<K, V>>() {
361 public boolean hasNext() {
366 public Entry<K, V> next() {
367 final Entry<K, Integer> e = it.next();
368 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
375 return offsets.size();
379 private void writeObject(final ObjectOutputStream out) throws IOException {
380 out.writeInt(offsets.size());
381 for (Entry<K, V> e : entrySet()) {
382 out.writeObject(e.getKey());
383 out.writeObject(e.getValue());
387 private static final Field OFFSETS_FIELD = fieldFor("offsets");
388 private static final Field ARRAY_FIELD = fieldFor("objects");
390 private static Field fieldFor(final String name) {
393 f = ImmutableOffsetMap.class.getDeclaredField(name);
394 } catch (NoSuchFieldException | SecurityException e) {
395 throw new IllegalStateException("Failed to lookup field " + name, e);
398 f.setAccessible(true);
402 private static void setField(final ImmutableOffsetMap<?, ?> map, final Field field, final Object value)
405 field.set(map, value);
406 } catch (IllegalArgumentException | IllegalAccessException e) {
407 throw new IOException("Failed to set field " + field, e);
411 @SuppressWarnings("unchecked")
412 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
413 final int s = in.readInt();
415 final List<K> keys = new ArrayList<>(s);
416 final V[] values = (V[]) new Object[s];
418 for (int i = 0; i < s; ++i) {
419 keys.add((K)in.readObject());
420 values[i] = (V)in.readObject();
423 setFields(keys, values);