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