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