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 final class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
40 private static final long serialVersionUID = 1L;
42 private final Map<K, Integer> offsets;
43 private final V[] objects;
47 * Construct a new instance backed by specified key-to-offset map and array of objects.
49 * @param offsets Key-to-offset map, may not be null
50 * @param objects Array of value object, may not be null. The array is stored as is, the caller
51 * is responsible for ensuring its contents remain unmodified.
53 ImmutableOffsetMap(@Nonnull final Map<K, Integer> offsets, @Nonnull final V[] objects) {
54 this.offsets = Preconditions.checkNotNull(offsets);
55 this.objects = Preconditions.checkNotNull(objects);
56 Preconditions.checkArgument(offsets.size() == objects.length);
60 * Construct a new instance based on some other instance.
62 * @param m Instance to share data with, may not be null.
64 ImmutableOffsetMap(@Nonnull final ImmutableOffsetMap<K, V> m) {
65 this.offsets = m.offsets;
66 this.objects = m.objects;
70 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true,
71 * as this method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient.
72 * This method also recognizes {@link ImmutableOffsetMap} on input, and returns it back without doing anything else.
73 * It also recognizes {@link MutableOffsetMap} (as returned by {@link #toModifiableMap()}) and makes an efficient
74 * copy of its contents. All other maps are converted to an {@link ImmutableOffsetMap} with the same iteration
77 * @param m Input map, may not be null.
78 * @return An isolated, immutable copy of the input map
80 @Nonnull public static <K, V> Map<K, V> copyOf(@Nonnull final Map<K, V> m) {
81 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
82 if (m instanceof ImmutableOffsetMap || m instanceof SharedSingletonMap) {
86 // Familiar and efficient to copy
87 if (m instanceof MutableOffsetMap) {
88 return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
91 final int size = m.size();
93 // Shares a single object
94 return ImmutableMap.of();
97 // Efficient single-entry implementation
98 final Entry<K, V> e = m.entrySet().iterator().next();
99 return SharedSingletonMap.of(e.getKey(), e.getValue());
102 final Map<K, Integer> offsets = OffsetMapCache.offsetsFor(m.keySet());
103 @SuppressWarnings("unchecked")
104 final V[] array = (V[]) new Object[offsets.size()];
105 for (Entry<K, V> e : m.entrySet()) {
106 array[offsets.get(e.getKey())] = e.getValue();
109 return new ImmutableOffsetMap<>(offsets, array);
114 return offsets.size();
118 public boolean isEmpty() {
119 return offsets.isEmpty();
123 public int hashCode() {
129 for (Entry<K, Integer> e : offsets.entrySet()) {
130 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
138 public boolean equals(final Object o) {
146 if (o instanceof ImmutableOffsetMap) {
147 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
148 if (offsets.equals(om.offsets) && Arrays.deepEquals(objects, om.objects)) {
151 } else if (o instanceof MutableOffsetMap) {
152 // Let MutableOffsetMap do the actual work.
153 return o.equals(this);
154 } else if (o instanceof Map) {
155 final Map<?, ?> om = (Map<?, ?>)o;
157 // Size and key sets have to match
158 if (size() != om.size() || !keySet().equals(om.keySet())) {
163 // Ensure all objects are present
164 for (Entry<K, Integer> e : offsets.entrySet()) {
165 if (!objects[e.getValue()].equals(om.get(e.getKey()))) {
169 } catch (ClassCastException e) {
170 // Can be thrown by om.get() indicating we have incompatible key types
181 public boolean containsKey(final Object key) {
182 return offsets.containsKey(key);
186 public boolean containsValue(final Object value) {
187 for (Object o : objects) {
188 if (value.equals(o)) {
196 public V get(final Object key) {
197 final Integer offset = offsets.get(key);
198 return offset == null ? null : objects[offset];
202 public V remove(final Object key) {
203 throw new UnsupportedOperationException();
207 public V put(final K key, final V value) {
208 throw new UnsupportedOperationException();
212 public void putAll(final Map<? extends K, ? extends V> m) {
213 throw new UnsupportedOperationException();
217 public void clear() {
218 throw new UnsupportedOperationException();
222 public Set<K> keySet() {
223 return offsets.keySet();
227 public Collection<V> values() {
228 return new ConstantArrayCollection<>(objects);
232 public Set<Entry<K, V>> entrySet() {
233 return new EntrySet();
237 public MutableOffsetMap<K, V> toModifiableMap() {
238 return new MutableOffsetMap<>(this);
242 public String toString() {
243 final StringBuilder sb = new StringBuilder("{");
244 final Iterator<K> it = offsets.keySet().iterator();
246 while (it.hasNext()) {
247 sb.append(it.next());
249 sb.append(objects[i++]);
256 return sb.append('}').toString();
259 Map<K, Integer> offsets() {
267 private final class EntrySet extends AbstractSet<Entry<K, V>> {
269 public Iterator<Entry<K, V>> iterator() {
270 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
272 return new UnmodifiableIterator<Entry<K, V>>() {
274 public boolean hasNext() {
279 public Entry<K, V> next() {
280 final Entry<K, Integer> e = it.next();
281 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
288 return offsets.size();
292 private void writeObject(final ObjectOutputStream out) throws IOException {
293 out.writeInt(offsets.size());
294 for (Entry<K, V> e : entrySet()) {
295 out.writeObject(e.getKey());
296 out.writeObject(e.getValue());
300 private static final Field OFFSETS_FIELD = fieldFor("offsets");
301 private static final Field ARRAY_FIELD = fieldFor("objects");
303 private static Field fieldFor(final String name) {
306 f = ImmutableOffsetMap.class.getDeclaredField(name);
307 } catch (NoSuchFieldException | SecurityException e) {
308 throw new IllegalStateException("Failed to lookup field " + name, e);
311 f.setAccessible(true);
315 private void setField(final Field field, final Object value) throws IOException {
317 field.set(this, value);
318 } catch (IllegalArgumentException | IllegalAccessException e) {
319 throw new IOException("Failed to set field " + field, e);
323 @SuppressWarnings("unchecked")
324 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
325 final int s = in.readInt();
327 final List<K> keys = new ArrayList<>(s);
328 final V[] values = (V[]) new Object[s];
330 for (int i = 0; i < s; ++i) {
331 keys.add((K)in.readObject());
332 values[i] = (V)in.readObject();
335 setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys));
336 setField(ARRAY_FIELD, values);