019722b509af3e0bbff16386effc121389de3287
[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.AbstractSet;
20 import java.util.ArrayList;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Set;
26 import javax.annotation.Nonnull;
27
28 /**
29  * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
30  * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
31  * class uses a global cache to share the key-to-offset mapping.
32  *
33  * This map supports creation of value objects on the fly. To achieve that, subclasses should override {@link #valueToObject(Object)},
34  * {@link #objectToValue(Object, Object)}, {@link #clone()} and {@link #toModifiableMap()} methods.
35  *
36  * @param <K> the type of keys maintained by this map
37  * @param <V> the type of mapped values
38  */
39 @Beta
40 public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> implements Cloneable, UnmodifiableMapPhase<K, V>, Serializable {
41     private static final long serialVersionUID = 1L;
42
43     private final Map<K, Integer> offsets;
44     private final Object[] objects;
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 Object[] 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     protected 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
82         if (m instanceof ImmutableOffsetMap) {
83             return m;
84         }
85
86         // Better-packed
87         final int size = m.size();
88         if (size == 0) {
89             return ImmutableMap.of();
90         }
91         if (size == 1) {
92             return ImmutableMap.copyOf(m);
93         }
94
95         // Familiar and efficient
96         if (m instanceof MutableOffsetMap) {
97             return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
98         }
99
100         final Map<K, Integer> offsets = OffsetMapCache.offsetsFor(m.keySet());
101         @SuppressWarnings("unchecked")
102         final V[] array = (V[]) new Object[offsets.size()];
103         for (Entry<K, V> e : m.entrySet()) {
104             array[offsets.get(e.getKey())] = e.getValue();
105         }
106
107         return new ImmutableOffsetMap<>(offsets, array);
108     }
109
110     @Override
111     public final int size() {
112         return offsets.size();
113     }
114
115     @Override
116     public final boolean isEmpty() {
117         return offsets.isEmpty();
118     }
119
120     @Override
121     public final boolean containsKey(final Object key) {
122         return offsets.containsKey(key);
123     }
124
125     @Override
126     public final boolean containsValue(final Object value) {
127         @SuppressWarnings("unchecked")
128         final Object obj = valueToObject((V)value);
129         for (Object o : objects) {
130             if (Objects.equals(obj, o)) {
131                 return true;
132             }
133         }
134         return false;
135     }
136
137     @SuppressWarnings("unchecked")
138     @Override
139     public final V get(final Object key) {
140         final Integer offset = offsets.get(key);
141         if (offset == null) {
142             return null;
143         }
144
145         return objectToValue((K) key, objects[offset]);
146     }
147
148     @Override
149     public final V remove(final Object key) {
150         throw new UnsupportedOperationException();
151     }
152
153     @Override
154     public final void putAll(final Map<? extends K, ? extends V> m) {
155         throw new UnsupportedOperationException();
156     }
157
158     @Override
159     public final void clear() {
160         throw new UnsupportedOperationException();
161     }
162
163     @Override
164     public final Set<K> keySet() {
165         return offsets.keySet();
166     }
167
168     @Override
169     public final Set<Entry<K, V>> entrySet() {
170         return new EntrySet();
171     }
172
173     @Override
174     public MutableOffsetMap<K, V> toModifiableMap() {
175         return new MutableOffsetMap<>(this);
176     }
177
178     @Override
179     public ImmutableOffsetMap<K, V> clone() throws CloneNotSupportedException {
180         return new ImmutableOffsetMap<>(this);
181     }
182
183     Map<K, Integer> offsets() {
184         return offsets;
185     }
186
187     Object[] objects() {
188         return objects;
189     }
190
191     private final class EntrySet extends AbstractSet<Entry<K, V>> {
192         @Override
193         public Iterator<Entry<K, V>> iterator() {
194             final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
195
196             return new UnmodifiableIterator<Entry<K, V>>() {
197                 @Override
198                 public boolean hasNext() {
199                     return it.hasNext();
200                 }
201
202                 @Override
203                 public Entry<K, V> next() {
204                     final Entry<K, Integer> e = it.next();
205                     return new SimpleEntry<>(e.getKey(), objectToValue(e.getKey(), objects[e.getValue()]));
206                 }
207             };
208         }
209
210         @Override
211         public int size() {
212             return offsets.size();
213         }
214     }
215
216     private void writeObject(final ObjectOutputStream out) throws IOException {
217         out.writeInt(offsets.size());
218         for (Entry<K, V> e : entrySet()) {
219             out.writeObject(e.getKey());
220             out.writeObject(e.getValue());
221         }
222     }
223
224     private static final Field OFFSETS_FIELD = fieldFor("offsets");
225     private static final Field ARRAY_FIELD = fieldFor("objects");
226
227     private static Field fieldFor(final String name) {
228         final Field f;
229         try {
230             f = ImmutableOffsetMap.class.getDeclaredField(name);
231         } catch (NoSuchFieldException | SecurityException e) {
232             throw new IllegalStateException("Failed to lookup field " + name, e);
233         }
234
235         f.setAccessible(true);
236         return f;
237     }
238
239     private void setField(final Field field, final Object value) throws IOException {
240         try {
241             field.set(this, value);
242         } catch (IllegalArgumentException | IllegalAccessException e) {
243             throw new IOException("Failed to set field " + field, e);
244         }
245     }
246
247     @SuppressWarnings("unchecked")
248     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
249         final int s = in.readInt();
250
251         final List<K> keys = new ArrayList<>(s);
252         final V[] values = (V[]) new Object[s];
253
254         for (int i = 0; i < s; ++i) {
255             keys.add((K)in.readObject());
256             values[i] = (V)in.readObject();
257         }
258
259         setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys));
260         setField(ARRAY_FIELD, values);
261     }
262 }