2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.util;
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;
24 import java.util.Objects;
26 import javax.annotation.Nonnull;
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.
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.
36 * @param <K> the type of keys maintained by this map
37 * @param <V> the type of mapped values
40 public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> implements Cloneable, UnmodifiableMapPhase<K, V>, Serializable {
41 private static final long serialVersionUID = 1L;
43 private final Map<K, Integer> offsets;
44 private final Object[] objects;
47 * Construct a new instance backed by specified key-to-offset map and array of objects.
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.
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);
60 * Construct a new instance based on some other instance.
62 * @param m Instance to share data with, may not be null.
64 protected ImmutableOffsetMap(@Nonnull final ImmutableOffsetMap<K, V> m) {
65 this.offsets = m.offsets;
66 this.objects = m.objects;
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
77 * @param m Input map, may not be null.
78 * @return An isolated, immutable copy of the input map
80 @Nonnull public static <K, V> Map<K, V> copyOf(@Nonnull final Map<K, V> m) {
82 if (m instanceof ImmutableOffsetMap) {
87 final int size = m.size();
89 return ImmutableMap.of();
92 return ImmutableMap.copyOf(m);
95 // Familiar and efficient
96 if (m instanceof MutableOffsetMap) {
97 return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
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();
107 return new ImmutableOffsetMap<>(offsets, array);
111 public final int size() {
112 return offsets.size();
116 public final boolean isEmpty() {
117 return offsets.isEmpty();
121 public final boolean containsKey(final Object key) {
122 return offsets.containsKey(key);
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)) {
137 @SuppressWarnings("unchecked")
139 public final V get(final Object key) {
140 final Integer offset = offsets.get(key);
141 if (offset == null) {
145 return objectToValue((K) key, objects[offset]);
149 public final V remove(final Object key) {
150 throw new UnsupportedOperationException();
154 public final void putAll(final Map<? extends K, ? extends V> m) {
155 throw new UnsupportedOperationException();
159 public final void clear() {
160 throw new UnsupportedOperationException();
164 public final Set<K> keySet() {
165 return offsets.keySet();
169 public final Set<Entry<K, V>> entrySet() {
170 return new EntrySet();
174 public MutableOffsetMap<K, V> toModifiableMap() {
175 return new MutableOffsetMap<>(this);
179 public ImmutableOffsetMap<K, V> clone() throws CloneNotSupportedException {
180 return new ImmutableOffsetMap<>(this);
183 Map<K, Integer> offsets() {
191 private final class EntrySet extends AbstractSet<Entry<K, V>> {
193 public Iterator<Entry<K, V>> iterator() {
194 final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
196 return new UnmodifiableIterator<Entry<K, V>>() {
198 public boolean hasNext() {
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()]));
212 return offsets.size();
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());
224 private static final Field OFFSETS_FIELD = fieldFor("offsets");
225 private static final Field ARRAY_FIELD = fieldFor("objects");
227 private static Field fieldFor(final String name) {
230 f = ImmutableOffsetMap.class.getDeclaredField(name);
231 } catch (NoSuchFieldException | SecurityException e) {
232 throw new IllegalStateException("Failed to lookup field " + name, e);
235 f.setAccessible(true);
239 private void setField(final Field field, final Object value) throws IOException {
241 field.set(this, value);
242 } catch (IllegalArgumentException | IllegalAccessException e) {
243 throw new IOException("Failed to set field " + field, e);
247 @SuppressWarnings("unchecked")
248 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
249 final int s = in.readInt();
251 final List<K> keys = new ArrayList<>(s);
252 final V[] values = (V[]) new Object[s];
254 for (int i = 0; i < s; ++i) {
255 keys.add((K)in.readObject());
256 values[i] = (V)in.readObject();
259 setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys));
260 setField(ARRAY_FIELD, values);