02d8fe4d4ac0c7f5f2a123352ffc2a4fb7979d52
[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         // copyOf() disconnects the key set while retaining its order across cache lookup.
103         final Map<K, Integer> offsets = OffsetMapCache.orderedOffsets(m.keySet());
104         @SuppressWarnings("unchecked")
105         final V[] array = (V[]) new Object[offsets.size()];
106         for (Entry<K, V> e : m.entrySet()) {
107             array[offsets.get(e.getKey())] = e.getValue();
108         }
109
110         return new ImmutableOffsetMap<>(offsets, array);
111     }
112
113     @Override
114     public int size() {
115         return offsets.size();
116     }
117
118     @Override
119     public boolean isEmpty() {
120         return offsets.isEmpty();
121     }
122
123     @Override
124     public int hashCode() {
125         if (hashCode != 0) {
126             return hashCode;
127         }
128
129         int result = 0;
130         for (Entry<K, Integer> e : offsets.entrySet()) {
131             result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
132         }
133
134         hashCode = result;
135         return result;
136     }
137
138     @Override
139     public boolean equals(final Object o) {
140         if (o == this) {
141             return true;
142         }
143         if (o == null) {
144             return false;
145         }
146
147         if (o instanceof ImmutableOffsetMap) {
148             final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
149             if (offsets.equals(om.offsets) && Arrays.deepEquals(objects, om.objects)) {
150                 return true;
151             }
152         } else if (o instanceof MutableOffsetMap) {
153             // Let MutableOffsetMap do the actual work.
154             return o.equals(this);
155         } else if (o instanceof Map) {
156             final Map<?, ?> om = (Map<?, ?>)o;
157
158             // Size and key sets have to match
159             if (size() != om.size() || !keySet().equals(om.keySet())) {
160                 return false;
161             }
162
163             try {
164                 // Ensure all objects are present
165                 for (Entry<K, Integer> e : offsets.entrySet()) {
166                     if (!objects[e.getValue()].equals(om.get(e.getKey()))) {
167                         return false;
168                     }
169                 }
170             } catch (ClassCastException e) {
171                 // Can be thrown by om.get() indicating we have incompatible key types
172                 return false;
173             }
174
175             return true;
176         }
177
178         return false;
179     }
180
181     @Override
182     public boolean containsKey(final Object key) {
183         return offsets.containsKey(key);
184     }
185
186     @Override
187     public boolean containsValue(final Object value) {
188         for (Object o : objects) {
189             if (value.equals(o)) {
190                 return true;
191             }
192         }
193         return false;
194     }
195
196     @Override
197     public V get(final Object key) {
198         final Integer offset = offsets.get(key);
199         return offset == null ? null : objects[offset];
200     }
201
202     @Override
203     public V remove(final Object key) {
204         throw new UnsupportedOperationException();
205     }
206
207     @Override
208     public V put(final K key, final V value) {
209         throw new UnsupportedOperationException();
210     }
211
212     @Override
213     public void putAll(final Map<? extends K, ? extends V> m) {
214         throw new UnsupportedOperationException();
215     }
216
217     @Override
218     public void clear() {
219         throw new UnsupportedOperationException();
220     }
221
222     @Override
223     public Set<K> keySet() {
224         return offsets.keySet();
225     }
226
227     @Override
228     public Collection<V> values() {
229         return new ConstantArrayCollection<>(objects);
230     }
231
232     @Override
233     public Set<Entry<K, V>> entrySet() {
234         return new EntrySet();
235     }
236
237     @Override
238     public MutableOffsetMap<K, V> toModifiableMap() {
239         return MutableOffsetMap.copyOf(this);
240     }
241
242     @Override
243     public String toString() {
244         final StringBuilder sb = new StringBuilder("{");
245         final Iterator<K> it = offsets.keySet().iterator();
246         int i = 0;
247         while (it.hasNext()) {
248             sb.append(it.next());
249             sb.append('=');
250             sb.append(objects[i++]);
251
252             if (it.hasNext()) {
253                 sb.append(", ");
254             }
255         }
256
257         return sb.append('}').toString();
258     }
259
260     Map<K, Integer> offsets() {
261         return offsets;
262     }
263
264     V[] objects() {
265         return objects;
266     }
267
268     private final class EntrySet extends AbstractSet<Entry<K, V>> {
269         @Override
270         public Iterator<Entry<K, V>> iterator() {
271             final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
272
273             return new UnmodifiableIterator<Entry<K, V>>() {
274                 @Override
275                 public boolean hasNext() {
276                     return it.hasNext();
277                 }
278
279                 @Override
280                 public Entry<K, V> next() {
281                     final Entry<K, Integer> e = it.next();
282                     return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
283                 }
284             };
285         }
286
287         @Override
288         public int size() {
289             return offsets.size();
290         }
291     }
292
293     private void writeObject(final ObjectOutputStream out) throws IOException {
294         out.writeInt(offsets.size());
295         for (Entry<K, V> e : entrySet()) {
296             out.writeObject(e.getKey());
297             out.writeObject(e.getValue());
298         }
299     }
300
301     private static final Field OFFSETS_FIELD = fieldFor("offsets");
302     private static final Field ARRAY_FIELD = fieldFor("objects");
303
304     private static Field fieldFor(final String name) {
305         final Field f;
306         try {
307             f = ImmutableOffsetMap.class.getDeclaredField(name);
308         } catch (NoSuchFieldException | SecurityException e) {
309             throw new IllegalStateException("Failed to lookup field " + name, e);
310         }
311
312         f.setAccessible(true);
313         return f;
314     }
315
316     private void setField(final Field field, final Object value) throws IOException {
317         try {
318             field.set(this, value);
319         } catch (IllegalArgumentException | IllegalAccessException e) {
320             throw new IOException("Failed to set field " + field, e);
321         }
322     }
323
324     @SuppressWarnings("unchecked")
325     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
326         final int s = in.readInt();
327
328         // ImmutableList.build() does not have a sizing hint ...
329         final List<K> keys = new ArrayList<>(s);
330         final V[] values = (V[]) new Object[s];
331
332         for (int i = 0; i < s; ++i) {
333             keys.add((K)in.readObject());
334             values[i] = (V)in.readObject();
335         }
336
337         setField(OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys));
338         setField(ARRAY_FIELD, values);
339     }
340 }