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 com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.UnmodifiableIterator;
14 import java.io.IOException;
15 import java.io.ObjectInputStream;
16 import java.io.ObjectOutputStream;
17 import java.io.Serializable;
18 import java.lang.reflect.Field;
19 import java.util.AbstractMap.SimpleImmutableEntry;
20 import java.util.AbstractSet;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Iterator;
25 import java.util.List;
28 import javax.annotation.Nonnull;
31 * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
32 * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
33 * class uses a global cache to share the key-to-offset mapping.
35 * @param <K> the type of keys maintained by this map
36 * @param <V> the type of mapped values
39 public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
40 static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
41 private static final long serialVersionUID = 1L;
43 Ordered(final Map<K, Integer> offsets, final V[] objects) {
44 super(offsets, objects);
48 public MutableOffsetMap<K, V> toModifiableMap() {
49 return new MutableOffsetMap<>(this);
53 private static final long serialVersionUID = 1L;
55 private final Map<K, Integer> offsets;
56 private final V[] objects;
60 * Construct a new instance backed by specified key-to-offset map and array of objects.
62 * @param offsets Key-to-offset map, may not be null
63 * @param objects Array of value object, may not be null. The array is stored as is, the caller
64 * is responsible for ensuring its contents remain unmodified.
66 ImmutableOffsetMap(@Nonnull final Map<K, Integer> offsets, @Nonnull final V[] objects) {
67 this.offsets = Preconditions.checkNotNull(offsets);
68 this.objects = Preconditions.checkNotNull(objects);
69 Preconditions.checkArgument(offsets.size() == objects.length);
73 public abstract MutableOffsetMap<K, V> toModifiableMap();
76 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true,
77 * as this method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient.
78 * This method also recognizes {@link ImmutableOffsetMap} on input, and returns it back without doing anything else.
79 * It also recognizes {@link MutableOffsetMap} (as returned by {@link #toModifiableMap()}) and makes an efficient
80 * copy of its contents. All other maps are converted to an {@link ImmutableOffsetMap} with the same iteration
83 * @param m Input map, may not be null.
84 * @return An isolated, immutable copy of the input map
86 @Nonnull public static <K, V> Map<K, V> copyOf(@Nonnull final Map<K, V> m) {
87 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
88 if (m instanceof ImmutableOffsetMap || m instanceof SharedSingletonMap) {
92 // Familiar and efficient to copy
93 if (m instanceof MutableOffsetMap) {
94 return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
97 final int size = m.size();
99 // Shares a single object
100 return ImmutableMap.of();
103 // Efficient single-entry implementation
104 final Entry<K, V> e = m.entrySet().iterator().next();
105 return SharedSingletonMap.of(e.getKey(), e.getValue());
108 final Map<K, Integer> offsets = OffsetMapCache.offsetsFor(m.keySet());
109 @SuppressWarnings("unchecked")
110 final V[] array = (V[]) new Object[offsets.size()];
111 for (Entry<K, V> e : m.entrySet()) {
112 array[offsets.get(e.getKey())] = e.getValue();
115 return new Ordered<>(offsets, array);
119 public final int size() {
120 return offsets.size();
124 public final boolean isEmpty() {
125 return offsets.isEmpty();
129 public final int hashCode() {
135 for (Entry<K, Integer> e : offsets.entrySet()) {
136 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
144 public final boolean equals(final Object o) {
148 if (!(o instanceof Map)) {
152 if (o instanceof ImmutableOffsetMap) {
153 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
155 // If the offset match, the arrays have to match, too
156 if (offsets.equals(om.offsets)) {
157 return Arrays.deepEquals(objects, om.objects);
159 } else if (o instanceof MutableOffsetMap) {
160 // Let MutableOffsetMap do the actual work.
161 return o.equals(this);
164 final Map<?, ?> other = (Map<?, ?>)o;
166 // Size and key sets have to match
167 if (size() != other.size() || !keySet().equals(other.keySet())) {
172 // Ensure all objects are present
173 for (Entry<K, Integer> e : offsets.entrySet()) {
174 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
178 } catch (ClassCastException e) {
179 // Can be thrown by other.get() indicating we have incompatible key types
187 public final boolean containsKey(final Object key) {
188 return offsets.containsKey(key);
192 public final boolean containsValue(final Object value) {
193 for (Object o : objects) {
194 if (value.equals(o)) {
202 public final V get(final Object key) {
203 final Integer offset = offsets.get(key);
204 return offset == null ? null : objects[offset];
208 public final V remove(final Object key) {
209 throw new UnsupportedOperationException();
213 public final V put(final K key, final V value) {
214 throw new UnsupportedOperationException();
218 public final void putAll(final Map<? extends K, ? extends V> m) {
219 throw new UnsupportedOperationException();
223 public final void clear() {
224 throw new UnsupportedOperationException();
228 public final Set<K> keySet() {
229 return offsets.keySet();
233 public final Collection<V> values() {
234 return new ConstantArrayCollection<>(objects);
238 public final Set<Entry<K, V>> entrySet() {
239 return new EntrySet();
243 public final String toString() {
244 final StringBuilder sb = new StringBuilder("{");
245 final Iterator<K> it = offsets.keySet().iterator();
247 while (it.hasNext()) {
248 sb.append(it.next());
250 sb.append(objects[i++]);
257 return sb.append('}').toString();
260 final Map<K, Integer> offsets() {
264 final V[] objects() {
268 private final class EntrySet extends AbstractSet<Entry<K, V>> {
270 public Iterator<Entry<K, V>> iterator() {
271 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
273 return new UnmodifiableIterator<Entry<K, V>>() {
275 public boolean hasNext() {
280 public Entry<K, V> next() {
281 final Entry<K, Integer> e = it.next();
282 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
289 return offsets.size();
293 private void writeObject(final ObjectOutputStream out) throws IOException {
294 out.writeInt(offsets.size());
295 for (Entry<K, V> e : entrySet()) {
296 out.writeObject(e.getKey());
297 out.writeObject(e.getValue());
301 private static final Field OFFSETS_FIELD = fieldFor("offsets");
302 private static final Field ARRAY_FIELD = fieldFor("objects");
304 private static Field fieldFor(final String name) {
307 f = ImmutableOffsetMap.class.getDeclaredField(name);
308 } catch (NoSuchFieldException | SecurityException e) {
309 throw new IllegalStateException("Failed to lookup field " + name, e);
312 f.setAccessible(true);
316 private void setField(final Field field, final Object value) throws IOException {
318 field.set(this, value);
319 } catch (IllegalArgumentException | IllegalAccessException e) {
320 throw new IOException("Failed to set field " + field, e);
324 @SuppressWarnings("unchecked")
325 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
326 final int s = in.readInt();
328 final List<K> keys = new ArrayList<>(s);
329 final V[] values = (V[]) new Object[s];
331 for (int i = 0; i < s; ++i) {
332 keys.add((K)in.readObject());
333 values[i] = (V)in.readObject();
336 setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys));
337 setField(ARRAY_FIELD, values);