Make OffsetMaps work on direct values
[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 final class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
40     private static final long serialVersionUID = 1L;
41
42     private final Map<K, Integer> offsets;
43     private final V[] objects;
44     private int hashCode;
45
46     /**
47      * Construct a new instance backed by specified key-to-offset map and array of objects.
48      *
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.
52      */
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);
57     }
58
59     /**
60      * Construct a new instance based on some other instance.
61      *
62      * @param m Instance to share data with, may not be null.
63      */
64     ImmutableOffsetMap(@Nonnull final ImmutableOffsetMap<K, V> m) {
65         this.offsets = m.offsets;
66         this.objects = m.objects;
67     }
68
69     /**
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
75      * order as input.
76      *
77      * @param m Input map, may not be null.
78      * @return An isolated, immutable copy of the input map
79      */
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) {
83             return m;
84         }
85
86         // Familiar and efficient to copy
87         if (m instanceof MutableOffsetMap) {
88             return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
89         }
90
91         final int size = m.size();
92         if (size == 0) {
93             // Shares a single object
94             return ImmutableMap.of();
95         }
96         if (size == 1) {
97             // Efficient single-entry implementation
98             final Entry<K, V> e = m.entrySet().iterator().next();
99             return SharedSingletonMap.of(e.getKey(), e.getValue());
100         }
101
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();
107         }
108
109         return new ImmutableOffsetMap<>(offsets, array);
110     }
111
112     @Override
113     public int size() {
114         return offsets.size();
115     }
116
117     @Override
118     public boolean isEmpty() {
119         return offsets.isEmpty();
120     }
121
122     @Override
123     public int hashCode() {
124         if (hashCode != 0) {
125             return hashCode;
126         }
127
128         int result = 0;
129         for (Entry<K, Integer> e : offsets.entrySet()) {
130             result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
131         }
132
133         hashCode = result;
134         return result;
135     }
136
137     @Override
138     public boolean equals(final Object o) {
139         if (o == this) {
140             return true;
141         }
142         if (o == null) {
143             return false;
144         }
145
146         if (o instanceof ImmutableOffsetMap) {
147             final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
148             if (offsets.equals(om.offsets) && Arrays.deepEquals(objects, om.objects)) {
149                 return true;
150             }
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;
156
157             // Size and key sets have to match
158             if (size() != om.size() || !keySet().equals(om.keySet())) {
159                 return false;
160             }
161
162             try {
163                 // Ensure all objects are present
164                 for (Entry<K, Integer> e : offsets.entrySet()) {
165                     if (!objects[e.getValue()].equals(om.get(e.getKey()))) {
166                         return false;
167                     }
168                 }
169             } catch (ClassCastException e) {
170                 // Can be thrown by om.get() indicating we have incompatible key types
171                 return false;
172             }
173
174             return true;
175         }
176
177         return false;
178     }
179
180     @Override
181     public boolean containsKey(final Object key) {
182         return offsets.containsKey(key);
183     }
184
185     @Override
186     public boolean containsValue(final Object value) {
187         for (Object o : objects) {
188             if (value.equals(o)) {
189                 return true;
190             }
191         }
192         return false;
193     }
194
195     @Override
196     public V get(final Object key) {
197         final Integer offset = offsets.get(key);
198         return offset == null ? null : objects[offset];
199     }
200
201     @Override
202     public V remove(final Object key) {
203         throw new UnsupportedOperationException();
204     }
205
206     @Override
207     public V put(final K key, final V value) {
208         throw new UnsupportedOperationException();
209     }
210
211     @Override
212     public void putAll(final Map<? extends K, ? extends V> m) {
213         throw new UnsupportedOperationException();
214     }
215
216     @Override
217     public void clear() {
218         throw new UnsupportedOperationException();
219     }
220
221     @Override
222     public Set<K> keySet() {
223         return offsets.keySet();
224     }
225
226     @Override
227     public Collection<V> values() {
228         return new ConstantArrayCollection<>(objects);
229     }
230
231     @Override
232     public Set<Entry<K, V>> entrySet() {
233         return new EntrySet();
234     }
235
236     @Override
237     public MutableOffsetMap<K, V> toModifiableMap() {
238         return new MutableOffsetMap<>(this);
239     }
240
241     Map<K, Integer> offsets() {
242         return offsets;
243     }
244
245     V[] objects() {
246         return objects;
247     }
248
249     private final class EntrySet extends AbstractSet<Entry<K, V>> {
250         @Override
251         public Iterator<Entry<K, V>> iterator() {
252             final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
253
254             return new UnmodifiableIterator<Entry<K, V>>() {
255                 @Override
256                 public boolean hasNext() {
257                     return it.hasNext();
258                 }
259
260                 @Override
261                 public Entry<K, V> next() {
262                     final Entry<K, Integer> e = it.next();
263                     return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
264                 }
265             };
266         }
267
268         @Override
269         public int size() {
270             return offsets.size();
271         }
272     }
273
274     private void writeObject(final ObjectOutputStream out) throws IOException {
275         out.writeInt(offsets.size());
276         for (Entry<K, V> e : entrySet()) {
277             out.writeObject(e.getKey());
278             out.writeObject(e.getValue());
279         }
280     }
281
282     private static final Field OFFSETS_FIELD = fieldFor("offsets");
283     private static final Field ARRAY_FIELD = fieldFor("objects");
284
285     private static Field fieldFor(final String name) {
286         final Field f;
287         try {
288             f = ImmutableOffsetMap.class.getDeclaredField(name);
289         } catch (NoSuchFieldException | SecurityException e) {
290             throw new IllegalStateException("Failed to lookup field " + name, e);
291         }
292
293         f.setAccessible(true);
294         return f;
295     }
296
297     private void setField(final Field field, final Object value) throws IOException {
298         try {
299             field.set(this, value);
300         } catch (IllegalArgumentException | IllegalAccessException e) {
301             throw new IOException("Failed to set field " + field, e);
302         }
303     }
304
305     @SuppressWarnings("unchecked")
306     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
307         final int s = in.readInt();
308
309         final List<K> keys = new ArrayList<>(s);
310         final V[] values = (V[]) new Object[s];
311
312         for (int i = 0; i < s; ++i) {
313             keys.add((K)in.readObject());
314             values[i] = (V)in.readObject();
315         }
316
317         setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys));
318         setField(ARRAY_FIELD, values);
319     }
320 }