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;
33 * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
34 * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
35 * class uses a global cache to share the key-to-offset mapping.
37 * @param <K> the type of keys maintained by this map
38 * @param <V> the type of mapped values
41 public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
42 static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
43 private static final long serialVersionUID = 1L;
45 Ordered(final Map<K, Integer> offsets, final V[] objects) {
46 super(offsets, objects);
51 public 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 Map<K, Integer> offsets, final V[] objects) {
66 super(offsets, objects);
71 public MutableOffsetMap<K, V> toModifiableMap() {
72 return MutableOffsetMap.unorderedCopyOf(this);
76 void setFields(final List<K> keys, final V[] values) throws IOException {
77 final Map<K, Integer> newOffsets = OffsetMapCache.unorderedOffsets(keys);
79 setField(this, OFFSETS_FIELD, newOffsets);
80 setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(newOffsets, keys, values));
84 private static final long serialVersionUID = 1L;
86 private final transient Map<K, Integer> offsets;
87 private final transient V[] objects;
88 private transient int hashCode;
91 * Construct a new instance backed by specified key-to-offset map and array of objects.
93 * @param offsets Key-to-offset map, may not be null
94 * @param objects Array of value object, may not be null. The array is stored as is, the caller
95 * is responsible for ensuring its contents remain unmodified.
97 ImmutableOffsetMap(@Nonnull final Map<K, Integer> offsets, @Nonnull final V[] objects) {
98 this.offsets = requireNonNull(offsets);
99 this.objects = requireNonNull(objects);
100 checkArgument(offsets.size() == objects.length);
105 public abstract MutableOffsetMap<K, V> toModifiableMap();
107 abstract void setFields(List<K> keys, V[] values) throws IOException;
110 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This
111 * is actually not completely true, as this method returns an
112 * {@link ImmutableMap} for empty and singleton inputs, as those are more
113 * memory-efficient. This method also recognizes {@link ImmutableOffsetMap}
114 * on input, and returns it back without doing anything else. It also
115 * recognizes {@link MutableOffsetMap} (as returned by
116 * {@link #toModifiableMap()}) and makes an efficient copy of its contents.
117 * All other maps are converted to an {@link ImmutableOffsetMap} with the
118 * same iteration order as input.
121 * Input map, may not be null.
122 * @return An isolated, immutable copy of the input map
124 @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> map) {
125 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
126 if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
130 // Familiar and efficient to copy
131 if (map instanceof MutableOffsetMap) {
132 return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
135 final int size = map.size();
137 // Shares a single object
138 return ImmutableMap.of();
141 // Efficient single-entry implementation
142 final Entry<K, V> e = map.entrySet().iterator().next();
143 return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
146 final Map<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
147 @SuppressWarnings("unchecked")
148 final V[] array = (V[]) new Object[offsets.size()];
149 for (Entry<K, V> e : map.entrySet()) {
150 array[offsets.get(e.getKey())] = e.getValue();
153 return new Ordered<>(offsets, array);
157 * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This
158 * is actually not completely true, as this method returns an
159 * {@link ImmutableMap} for empty and singleton inputs, as those are more
160 * memory-efficient. This method also recognizes {@link ImmutableOffsetMap}
161 * on input, and returns it back without doing anything else. It also
162 * recognizes {@link MutableOffsetMap} (as returned by
163 * {@link #toModifiableMap()}) and makes an efficient copy of its contents.
164 * All other maps are converted to an {@link ImmutableOffsetMap}. Iterator
165 * order is not guaranteed to be retained.
168 * Input map, may not be null.
169 * @return An isolated, immutable copy of the input map
171 @Nonnull public static <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> map) {
172 // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
173 if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
177 // Familiar and efficient to copy
178 if (map instanceof MutableOffsetMap) {
179 return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
182 final int size = map.size();
184 // Shares a single object
185 return ImmutableMap.of();
188 // Efficient single-entry implementation
189 final Entry<K, V> e = map.entrySet().iterator().next();
190 return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
193 final Map<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
194 @SuppressWarnings("unchecked")
195 final V[] array = (V[]) new Object[offsets.size()];
196 for (Entry<K, V> e : map.entrySet()) {
197 array[offsets.get(e.getKey())] = e.getValue();
200 return new Unordered<>(offsets, array);
204 public final int size() {
205 return offsets.size();
209 public final boolean isEmpty() {
210 return offsets.isEmpty();
214 public final int hashCode() {
220 for (Entry<K, Integer> e : offsets.entrySet()) {
221 result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
229 public final boolean equals(final Object obj) {
233 if (!(obj instanceof Map)) {
237 if (obj instanceof ImmutableOffsetMap) {
238 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
240 // If the offset match, the arrays have to match, too
241 if (offsets.equals(om.offsets)) {
242 return Arrays.deepEquals(objects, om.objects);
244 } else if (obj instanceof MutableOffsetMap) {
245 // Let MutableOffsetMap do the actual work.
246 return obj.equals(this);
249 final Map<?, ?> other = (Map<?, ?>)obj;
251 // Size and key sets have to match
252 if (size() != other.size() || !keySet().equals(other.keySet())) {
257 // Ensure all objects are present
258 for (Entry<K, Integer> e : offsets.entrySet()) {
259 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
263 } catch (ClassCastException e) {
264 // Can be thrown by other.get() indicating we have incompatible key types
272 public final boolean containsKey(final Object key) {
273 return offsets.containsKey(key);
277 public final boolean containsValue(final Object value) {
278 for (Object o : objects) {
279 if (value.equals(o)) {
287 public final V get(final Object key) {
288 final Integer offset = offsets.get(key);
289 return offset == null ? null : objects[offset];
293 public final V remove(final Object key) {
294 throw new UnsupportedOperationException();
298 public final V put(final K key, final V value) {
299 throw new UnsupportedOperationException();
303 @SuppressWarnings("checkstyle:parameterName")
304 public final void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
305 throw new UnsupportedOperationException();
309 public final void clear() {
310 throw new UnsupportedOperationException();
314 public final Set<K> keySet() {
315 return offsets.keySet();
320 public final Collection<V> values() {
321 return new ConstantArrayCollection<>(objects);
326 public final Set<Entry<K, V>> entrySet() {
327 return new EntrySet();
331 public final String toString() {
332 final StringBuilder sb = new StringBuilder("{");
333 final Iterator<K> it = offsets.keySet().iterator();
335 while (it.hasNext()) {
336 sb.append(it.next());
338 sb.append(objects[offset++]);
345 return sb.append('}').toString();
348 final Map<K, Integer> offsets() {
352 final V[] objects() {
356 private final class EntrySet extends AbstractSet<Entry<K, V>> {
359 public Iterator<Entry<K, V>> iterator() {
360 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
362 return new UnmodifiableIterator<Entry<K, V>>() {
364 public boolean hasNext() {
369 public Entry<K, V> next() {
370 final Entry<K, Integer> e = it.next();
371 return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
378 return offsets.size();
382 private void writeObject(final ObjectOutputStream out) throws IOException {
383 out.writeInt(offsets.size());
384 for (Entry<K, V> e : entrySet()) {
385 out.writeObject(e.getKey());
386 out.writeObject(e.getValue());
390 private static final Field OFFSETS_FIELD = fieldFor("offsets");
391 private static final Field ARRAY_FIELD = fieldFor("objects");
393 private static Field fieldFor(final String name) {
396 f = ImmutableOffsetMap.class.getDeclaredField(name);
397 } catch (NoSuchFieldException | SecurityException e) {
398 throw new IllegalStateException("Failed to lookup field " + name, e);
401 f.setAccessible(true);
405 private static void setField(final ImmutableOffsetMap<?, ?> map, final Field field, final Object value)
408 field.set(map, value);
409 } catch (IllegalArgumentException | IllegalAccessException e) {
410 throw new IOException("Failed to set field " + field, e);
414 @SuppressWarnings("unchecked")
415 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
416 final int s = in.readInt();
418 final List<K> keys = new ArrayList<>(s);
419 final V[] values = (V[]) new Object[s];
421 for (int i = 0; i < s; ++i) {
422 keys.add((K)in.readObject());
423 values[i] = (V)in.readObject();
426 setFields(keys, values);