844086df746c1c314f3a2625dd1aa268543cc0ef
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / ImmutableOffsetMap.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.UnmodifiableIterator;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.io.IOException;
18 import java.io.ObjectInputStream;
19 import java.io.ObjectOutputStream;
20 import java.io.Serializable;
21 import java.lang.reflect.Field;
22 import java.util.AbstractMap.SimpleImmutableEntry;
23 import java.util.AbstractSet;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
33
34 /**
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.
38  *
39  * <p>
40  * In case the set of keys is statically known, you can use {@link ImmutableOffsetMapTemplate} to efficiently create
41  * {@link ImmutableOffsetMap} instances.
42  *
43  * @param <K> the type of keys maintained by this map
44  * @param <V> the type of mapped values
45  */
46 @Beta
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;
50
51         Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
52             super(offsets, objects);
53         }
54
55         @Override
56         public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
57             return MutableOffsetMap.orderedCopyOf(this);
58         }
59
60         @Override
61         void setFields(final List<K> keys, final V[] values) throws IOException {
62             setField(this, OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys));
63             setField(this, ARRAY_FIELD, values);
64         }
65     }
66
67     static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
68         private static final long serialVersionUID = 1L;
69
70         Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
71             super(offsets, objects);
72         }
73
74         @Override
75         public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
76             return MutableOffsetMap.unorderedCopyOf(this);
77         }
78
79         @Override
80         void setFields(final List<K> keys, final V[] values) throws IOException {
81             final Map<K, Integer> newOffsets = OffsetMapCache.unorderedOffsets(keys);
82
83             setField(this, OFFSETS_FIELD, newOffsets);
84             setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(newOffsets, keys, values));
85         }
86     }
87
88     private static final long serialVersionUID = 1L;
89
90     private final transient @NonNull ImmutableMap<K, Integer> offsets;
91     private final transient @NonNull V[] objects;
92     private transient int hashCode;
93
94     /**
95      * Construct a new instance backed by specified key-to-offset map and array of objects.
96      *
97      * @param offsets Key-to-offset map, may not be null
98      * @param objects Array of value object, may not be null. The array is stored as is, the caller
99      *              is responsible for ensuring its contents remain unmodified.
100      */
101     ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
102         this.offsets = requireNonNull(offsets);
103         this.objects = requireNonNull(objects);
104         checkArgument(offsets.size() == objects.length);
105     }
106
107     @Override
108     public abstract @NonNull MutableOffsetMap<K, V> toModifiableMap();
109
110     abstract void setFields(List<K> keys, V[] values) throws IOException;
111
112     /**
113      * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
114      * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
115      * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
116      * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
117      * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
118      * {@link ImmutableOffsetMap} with the same iteration order as input.
119      *
120      * @param map Input map, may not be null.
121      * @return An isolated, immutable copy of the input map
122      * @throws NullPointerException if {@code map} or any of its elements is null.
123      */
124     public static <K, V> @NonNull Map<K, V> orderedCopyOf(final @NonNull Map<K, V> map) {
125         final Map<K, V> common = commonCopy(map);
126         if (common != null) {
127             return common;
128         }
129
130         final int size = map.size();
131         if (size == 1) {
132             // Efficient single-entry implementation
133             final Entry<K, V> e = map.entrySet().iterator().next();
134             return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
135         }
136
137         final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
138         @SuppressWarnings("unchecked")
139         final V[] array = (V[]) new Object[offsets.size()];
140         for (Entry<K, V> e : map.entrySet()) {
141             array[offsets.get(e.getKey())] = e.getValue();
142         }
143
144         return new Ordered<>(offsets, array);
145     }
146
147     /**
148      * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
149      * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
150      * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
151      * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
152      * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
153      * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
154      *
155      * @param map Input map, may not be null.
156      * @return An isolated, immutable copy of the input map
157      * @throws NullPointerException if {@code map} or any of its elements is null.
158      */
159     public static <K, V> @NonNull Map<K, V> unorderedCopyOf(final @NonNull Map<K, V> map) {
160         final Map<K, V> common = commonCopy(map);
161         if (common != null) {
162             return common;
163         }
164
165         if (map.size() == 1) {
166             // Efficient single-entry implementation
167             final Entry<K, V> e = map.entrySet().iterator().next();
168             return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
169         }
170
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();
176         }
177
178         return new Unordered<>(offsets, array);
179     }
180
181     private static <K, V> @Nullable Map<K, V> commonCopy(final @NonNull 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) {
184             return map;
185         }
186
187         // Familiar and efficient to copy
188         if (map instanceof MutableOffsetMap) {
189             return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
190         }
191
192         if (map.isEmpty()) {
193             // Shares a single object
194             return ImmutableMap.of();
195         }
196
197         return null;
198     }
199
200     @Override
201     public final int size() {
202         return offsets.size();
203     }
204
205     @Override
206     public final boolean isEmpty() {
207         return offsets.isEmpty();
208     }
209
210     @Override
211     public final int hashCode() {
212         if (hashCode != 0) {
213             return hashCode;
214         }
215
216         int result = 0;
217         for (Entry<K, Integer> e : offsets.entrySet()) {
218             result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
219         }
220
221         hashCode = result;
222         return result;
223     }
224
225     @Override
226     public final boolean equals(final Object obj) {
227         if (obj == this) {
228             return true;
229         }
230         if (!(obj instanceof Map)) {
231             return false;
232         }
233
234         if (obj instanceof ImmutableOffsetMap) {
235             final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
236
237             // If the offset match, the arrays have to match, too
238             if (offsets.equals(om.offsets)) {
239                 return Arrays.deepEquals(objects, om.objects);
240             }
241         } else if (obj instanceof MutableOffsetMap) {
242             // Let MutableOffsetMap do the actual work.
243             return obj.equals(this);
244         }
245
246         final Map<?, ?> other = (Map<?, ?>)obj;
247
248         // Size and key sets have to match
249         if (size() != other.size() || !keySet().equals(other.keySet())) {
250             return false;
251         }
252
253         try {
254             // Ensure all objects are present
255             for (Entry<K, Integer> e : offsets.entrySet()) {
256                 if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
257                     return false;
258                 }
259             }
260         } catch (ClassCastException e) {
261             // Can be thrown by other.get() indicating we have incompatible key types
262             return false;
263         }
264
265         return true;
266     }
267
268     @Override
269     public final boolean containsKey(final Object key) {
270         return offsets.containsKey(key);
271     }
272
273     @Override
274     public final boolean containsValue(final Object value) {
275         for (Object o : objects) {
276             if (value.equals(o)) {
277                 return true;
278             }
279         }
280         return false;
281     }
282
283     @Override
284     public final V get(final Object key) {
285         Integer offset;
286         return (offset = offsets.get(key)) == null ? null : objects[offset];
287     }
288
289     @Override
290     public final V remove(final Object key) {
291         throw new UnsupportedOperationException();
292     }
293
294     @Override
295     public final V put(final K key, final V value) {
296         throw new UnsupportedOperationException();
297     }
298
299     @Override
300     @SuppressWarnings("checkstyle:parameterName")
301     public final void putAll(final Map<? extends K, ? extends V> m) {
302         throw new UnsupportedOperationException();
303     }
304
305     @Override
306     public final void clear() {
307         throw new UnsupportedOperationException();
308     }
309
310     @Override
311     public final Set<K> keySet() {
312         return offsets.keySet();
313     }
314
315     @Override
316     public final @NonNull Collection<V> values() {
317         return new ConstantArrayCollection<>(objects);
318     }
319
320     @Override
321     public final @NonNull Set<Entry<K, V>> entrySet() {
322         return new EntrySet();
323     }
324
325     @Override
326     public final String toString() {
327         final StringBuilder sb = new StringBuilder("{");
328         final Iterator<K> it = offsets.keySet().iterator();
329         int offset = 0;
330         while (it.hasNext()) {
331             sb.append(it.next()).append('=').append(objects[offset++]);
332
333             if (it.hasNext()) {
334                 sb.append(", ");
335             }
336         }
337
338         return sb.append('}').toString();
339     }
340
341     final @NonNull ImmutableMap<K, Integer> offsets() {
342         return offsets;
343     }
344
345     final @NonNull V[] objects() {
346         return objects;
347     }
348
349     private final class EntrySet extends AbstractSet<Entry<K, V>> {
350         @Override
351         public @NonNull Iterator<Entry<K, V>> iterator() {
352             final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
353             return new UnmodifiableIterator<>() {
354                 @Override
355                 public boolean hasNext() {
356                     return it.hasNext();
357                 }
358
359                 @Override
360                 public Entry<K, V> next() {
361                     final Entry<K, Integer> e = it.next();
362                     return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
363                 }
364             };
365         }
366
367         @Override
368         public int size() {
369             return offsets.size();
370         }
371     }
372
373     private void writeObject(final ObjectOutputStream out) throws IOException {
374         out.writeInt(offsets.size());
375         for (Entry<K, V> e : entrySet()) {
376             out.writeObject(e.getKey());
377             out.writeObject(e.getValue());
378         }
379     }
380
381     private static final Field OFFSETS_FIELD = fieldFor("offsets");
382     private static final Field ARRAY_FIELD = fieldFor("objects");
383
384     private static @NonNull Field fieldFor(final @NonNull String name) {
385         final Field f;
386         try {
387             f = ImmutableOffsetMap.class.getDeclaredField(name);
388         } catch (NoSuchFieldException | SecurityException e) {
389             throw new IllegalStateException("Failed to lookup field " + name, e);
390         }
391
392         f.setAccessible(true);
393         return f;
394     }
395
396     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
397             justification = "https://github.com/spotbugs/spotbugs/issues/811")
398     private static void setField(final @NonNull ImmutableOffsetMap<?, ?> map, final @NonNull Field field,
399             final Object value) throws IOException {
400         try {
401             field.set(map, value);
402         } catch (IllegalArgumentException | IllegalAccessException e) {
403             throw new IOException("Failed to set field " + field, e);
404         }
405     }
406
407     @SuppressWarnings("unchecked")
408     private void readObject(final @NonNull ObjectInputStream in) throws IOException, ClassNotFoundException {
409         final int s = in.readInt();
410
411         final List<K> keys = new ArrayList<>(s);
412         final V[] values = (V[]) new Object[s];
413
414         for (int i = 0; i < s; ++i) {
415             keys.add((K)in.readObject());
416             values[i] = (V)in.readObject();
417         }
418
419         setFields(keys, values);
420     }
421 }