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.
40 * In case the set of keys is statically known, you can use {@link ImmutableOffsetMapTemplate} to efficiently create
41 * {@link ImmutableOffsetMap} instances.
43 * @param <K> the type of keys maintained by this map
44 * @param <V> the type of mapped values
47 public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
48 static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
49 private static final long serialVersionUID = 1L;
51 Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
52 super(offsets, objects);
57 public MutableOffsetMap<K, V> toModifiableMap() {
58 return MutableOffsetMap.orderedCopyOf(this);
62 void setFields(final List<K> keys, final V[] values) throws IOException {
63 setField(this, OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys));
64 setField(this, ARRAY_FIELD, values);
68 static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
69 private static final long serialVersionUID = 1L;
71 Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
72 super(offsets, objects);
77 public MutableOffsetMap<K, V> toModifiableMap() {
78 return MutableOffsetMap.unorderedCopyOf(this);
82 void setFields(final List<K> keys, final V[] values) throws IOException {
83 final Map<K, Integer> newOffsets = OffsetMapCache.unorderedOffsets(keys);
85 setField(this, OFFSETS_FIELD, newOffsets);
86 setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(newOffsets, keys, values));
90 private static final long serialVersionUID = 1L;
92 private final transient @NonNull ImmutableMap<K, Integer> offsets;
93 private final transient @NonNull V[] objects;
94 private transient int hashCode;
97 * Construct a new instance backed by specified key-to-offset map and array of objects.
99 * @param offsets Key-to-offset map, may not be null
100 * @param objects Array of value object, may not be null. The array is stored as is, the caller
101 * is responsible for ensuring its contents remain unmodified.
103 ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
104 this.offsets = requireNonNull(offsets);
105 this.objects = requireNonNull(objects);
106 checkArgument(offsets.size() == objects.length);
111 public abstract MutableOffsetMap<K, V> toModifiableMap();
113 abstract void setFields(List<K> keys, V[] values) throws IOException;
116 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
117 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
118 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
119 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
120 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
121 * {@link ImmutableOffsetMap} with the same iteration order as input.
123 * @param map Input map, may not be null.
124 * @return An isolated, immutable copy of the input map
125 * @throws NullPointerException if {@code map} or any of its elements is null.
127 @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> map) {
128 final Map<K, V> common = commonCopy(map);
129 if (common != null) {
133 final int size = map.size();
135 // Efficient single-entry implementation
136 final Entry<K, V> e = map.entrySet().iterator().next();
137 return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
140 final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
141 @SuppressWarnings("unchecked")
142 final V[] array = (V[]) new Object[offsets.size()];
143 for (Entry<K, V> e : map.entrySet()) {
144 array[offsets.get(e.getKey())] = e.getValue();
147 return new Ordered<>(offsets, array);
151 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
152 * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
153 * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
154 * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
155 * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
156 * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
158 * @param map Input map, may not be null.
159 * @return An isolated, immutable copy of the input map
160 * @throws NullPointerException if {@code map} or any of its elements is null.
162 @Nonnull public static <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> map) {
163 final Map<K, V> common = commonCopy(map);
164 if (common != null) {
168 final int size = map.size();
170 // Efficient single-entry implementation
171 final Entry<K, V> e = map.entrySet().iterator().next();
172 return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
175 final ImmutableMap<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
176 @SuppressWarnings("unchecked")
177 final V[] array = (V[]) new Object[offsets.size()];
178 for (Entry<K, V> e : map.entrySet()) {
179 array[offsets.get(e.getKey())] = e.getValue();
182 return new Unordered<>(offsets, array);
185 private static <K, V> @Nullable Map<K, V> commonCopy(@Nonnull final Map<K, V> map) {
186 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
187 if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
191 // Familiar and efficient to copy
192 if (map instanceof MutableOffsetMap) {
193 return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
197 // Shares a single object
198 return ImmutableMap.of();
205 public final int size() {
206 return offsets.size();
210 public final boolean isEmpty() {
211 return offsets.isEmpty();
215 public final int hashCode() {
221 for (Entry<K, Integer> e : offsets.entrySet()) {
222 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
230 public final boolean equals(final Object obj) {
234 if (!(obj instanceof Map)) {
238 if (obj instanceof ImmutableOffsetMap) {
239 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
241 // If the offset match, the arrays have to match, too
242 if (offsets.equals(om.offsets)) {
243 return Arrays.deepEquals(objects, om.objects);
245 } else if (obj instanceof MutableOffsetMap) {
246 // Let MutableOffsetMap do the actual work.
247 return obj.equals(this);
250 final Map<?, ?> other = (Map<?, ?>)obj;
252 // Size and key sets have to match
253 if (size() != other.size() || !keySet().equals(other.keySet())) {
258 // Ensure all objects are present
259 for (Entry<K, Integer> e : offsets.entrySet()) {
260 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
264 } catch (ClassCastException e) {
265 // Can be thrown by other.get() indicating we have incompatible key types
273 public final boolean containsKey(final Object key) {
274 return offsets.containsKey(key);
278 public final boolean containsValue(final Object value) {
279 for (Object o : objects) {
280 if (value.equals(o)) {
288 public final V get(final Object key) {
289 final Integer offset = offsets.get(key);
290 return offset == null ? null : objects[offset];
294 public final V remove(final Object key) {
295 throw new UnsupportedOperationException();
299 public final V put(final K key, final V value) {
300 throw new UnsupportedOperationException();
304 @SuppressWarnings("checkstyle:parameterName")
305 public final void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
306 throw new UnsupportedOperationException();
310 public final void clear() {
311 throw new UnsupportedOperationException();
315 public final Set<K> keySet() {
316 return offsets.keySet();
321 public final Collection<V> values() {
322 return new ConstantArrayCollection<>(objects);
327 public final Set<Entry<K, V>> entrySet() {
328 return new EntrySet();
332 public final String toString() {
333 final StringBuilder sb = new StringBuilder("{");
334 final Iterator<K> it = offsets.keySet().iterator();
336 while (it.hasNext()) {
337 sb.append(it.next());
339 sb.append(objects[offset++]);
346 return sb.append('}').toString();
349 final @NonNull ImmutableMap<K, Integer> offsets() {
353 final V[] objects() {
357 private final class EntrySet extends AbstractSet<Entry<K, V>> {
360 public Iterator<Entry<K, V>> iterator() {
361 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
363 return new UnmodifiableIterator<Entry<K, V>>() {
365 public boolean hasNext() {
370 public Entry<K, V> next() {
371 final Entry<K, Integer> e = it.next();
372 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
379 return offsets.size();
383 private void writeObject(final ObjectOutputStream out) throws IOException {
384 out.writeInt(offsets.size());
385 for (Entry<K, V> e : entrySet()) {
386 out.writeObject(e.getKey());
387 out.writeObject(e.getValue());
391 private static final Field OFFSETS_FIELD = fieldFor("offsets");
392 private static final Field ARRAY_FIELD = fieldFor("objects");
394 private static Field fieldFor(final String name) {
397 f = ImmutableOffsetMap.class.getDeclaredField(name);
398 } catch (NoSuchFieldException | SecurityException e) {
399 throw new IllegalStateException("Failed to lookup field " + name, e);
402 f.setAccessible(true);
406 private static void setField(final ImmutableOffsetMap<?, ?> map, final Field field, final Object value)
409 field.set(map, value);
410 } catch (IllegalArgumentException | IllegalAccessException e) {
411 throw new IOException("Failed to set field " + field, e);
415 @SuppressWarnings("unchecked")
416 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
417 final int s = in.readInt();
419 final List<K> keys = new ArrayList<>(s);
420 final V[] values = (V[]) new Object[s];
422 for (int i = 0; i < s; ++i) {
423 keys.add((K)in.readObject());
424 values[i] = (V)in.readObject();
427 setFields(keys, values);