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.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Verify;
14 import com.google.common.collect.ImmutableMap;
15 import java.util.AbstractMap;
16 import java.util.AbstractSet;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.ConcurrentModificationException;
20 import java.util.HashMap;
21 import java.util.Iterator;
22 import java.util.LinkedHashMap;
23 import java.util.List;
25 import java.util.NoSuchElementException;
29 * A mutable version of {@link ImmutableOffsetMap}. It inherits the set of mappings from the immutable version and
30 * allows updating/removing existing mappings. New mappings are stored in a dedicated {@link LinkedHashMap} to preserve
31 * insertion order. It also tracks the need to duplicate the backing array, so the sequence of
33 * ImmutableOffsetMap<K, V> source;
34 * ImmutableOffsetMap<K, V> result = source.createMutableClone().immutableCopy();
36 * results in source and result sharing the backing objects.
38 * This map does not support null keys nor values.
40 * @param <K> the type of keys maintained by this map
41 * @param <V> the type of mapped values
44 public abstract class MutableOffsetMap<K, V> extends AbstractMap<K, V> implements Cloneable, ModifiableMapPhase<K, V> {
45 static final class Ordered<K, V> extends MutableOffsetMap<K, V> {
47 super(new LinkedHashMap<K, V>());
50 Ordered(final Map<K, V> source) {
51 super(OffsetMapCache.orderedOffsets(source.keySet()), source, new LinkedHashMap<K, V>());
54 Ordered(final Map<K, Integer> offsets, final V[] objects) {
55 super(offsets, objects, new LinkedHashMap<K, V>());
59 Object removedObject() {
64 UnmodifiableMapPhase<K, V> modifiedMap(final List<K> keys, final V[] objects) {
65 return new ImmutableOffsetMap.Ordered<>(OffsetMapCache.orderedOffsets(keys), objects);
69 UnmodifiableMapPhase<K, V> unmodifiedMap(final Map<K, Integer> offsets, final V[] objects) {
70 return new ImmutableOffsetMap.Ordered<>(offsets, objects);
74 SharedSingletonMap<K, V> singletonMap() {
75 return SharedSingletonMap.orderedCopyOf(this);
79 static final class Unordered<K, V> extends MutableOffsetMap<K, V> {
81 super(new HashMap<K, V>());
84 Unordered(final Map<K, V> source) {
85 super(OffsetMapCache.unorderedOffsets(source.keySet()), source, new HashMap<K, V>());
88 Unordered(final Map<K, Integer> offsets, final V[] objects) {
89 super(offsets, objects, new HashMap<K, V>());
93 Object removedObject() {
98 UnmodifiableMapPhase<K, V> modifiedMap(final List<K> keys, final V[] objects) {
99 final Map<K, Integer> offsets = OffsetMapCache.unorderedOffsets(keys);
100 return new ImmutableOffsetMap.Unordered<>(offsets, OffsetMapCache.adjustedArray(offsets, keys, objects));
104 UnmodifiableMapPhase<K, V> unmodifiedMap(final Map<K, Integer> offsets, final V[] objects) {
105 return new ImmutableOffsetMap.Unordered<>(offsets, objects);
109 SharedSingletonMap<K, V> singletonMap() {
110 return SharedSingletonMap.unorderedCopyOf(this);
114 private static final Object[] EMPTY_ARRAY = new Object[0];
115 private static final Object REMOVED = new Object();
116 private final Map<K, Integer> offsets;
117 private HashMap<K, V> newKeys;
118 private Object[] objects;
119 private int removed = 0;
120 private transient volatile int modCount;
121 private boolean needClone = true;
123 MutableOffsetMap(final Map<K, Integer> offsets, final V[] objects, final HashMap<K, V> newKeys) {
124 Verify.verify(newKeys.isEmpty());
125 this.offsets = Preconditions.checkNotNull(offsets);
126 this.objects = Preconditions.checkNotNull(objects);
127 this.newKeys = Preconditions.checkNotNull(newKeys);
130 @SuppressWarnings("unchecked")
131 MutableOffsetMap(final HashMap<K, V> newKeys) {
132 this(ImmutableMap.<K, Integer>of(), (V[]) EMPTY_ARRAY, newKeys);
135 @SuppressWarnings("unchecked")
136 MutableOffsetMap(final Map<K, Integer> offsets, final Map<K, V> source, final HashMap<K, V> newKeys) {
137 this(offsets, (V[]) new Object[offsets.size()], newKeys);
139 for (Entry<K, V> e : source.entrySet()) {
140 objects[offsets.get(e.getKey())] = Preconditions.checkNotNull(e.getValue());
143 this.needClone = false;
146 public static <K, V> MutableOffsetMap<K, V> orderedCopyOf(final Map<K, V> m) {
147 if (m instanceof Ordered) {
148 return ((Ordered<K, V>) m).clone();
150 if (m instanceof ImmutableOffsetMap) {
151 final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) m;
152 return new Ordered<>(om.offsets(), om.objects());
155 return new Ordered<>(m);
158 public static <K, V> MutableOffsetMap<K, V> unorderedCopyOf(final Map<K, V> m) {
159 if (m instanceof Unordered) {
160 return ((Unordered<K, V>) m).clone();
162 if (m instanceof ImmutableOffsetMap) {
163 final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) m;
164 return new Unordered<>(om.offsets(), om.objects());
167 return new Unordered<>(m);
170 public static <K, V> MutableOffsetMap<K, V> ordered() {
171 return new MutableOffsetMap.Ordered<>();
174 public static <K, V> MutableOffsetMap<K, V> unordered() {
175 return new MutableOffsetMap.Unordered<>();
178 abstract Object removedObject();
179 abstract UnmodifiableMapPhase<K, V> modifiedMap(List<K> keys, V[] objects);
180 abstract UnmodifiableMapPhase<K, V> unmodifiedMap(Map<K, Integer> offsets, V[] objects);
181 abstract SharedSingletonMap<K, V> singletonMap();
184 public final int size() {
185 return offsets.size() + newKeys.size() - removed;
189 public final boolean isEmpty() {
194 public final boolean containsKey(final Object key) {
195 final Integer offset = offsets.get(key);
196 if (offset != null) {
197 final Object obj = objects[offset];
198 if (!REMOVED.equals(obj)) {
203 return newKeys.containsKey(key);
207 public final V get(final Object key) {
208 final Integer offset = offsets.get(key);
209 if (offset != null) {
210 final Object obj = objects[offset];
213 * This is a bit tricky: Ordered will put REMOVED to removed objects to retain strict insertion order.
214 * Unordered will add null, indicating that the slot may be reused in future. Hence if we see a REMOVED
215 * marker, we need to fall back to checking with new keys.
217 if (!REMOVED.equals(obj)) {
218 @SuppressWarnings("unchecked")
219 final V ret = (V)obj;
224 return newKeys.get(key);
227 private void cloneArray() {
230 if (!EMPTY_ARRAY.equals(objects)) {
231 objects = objects.clone();
237 public final V put(final K key, final V value) {
238 Preconditions.checkNotNull(value);
239 final Integer offset = offsets.get(Preconditions.checkNotNull(key));
240 if (offset != null) {
241 final Object obj = objects[offset];
244 * Put which can potentially replace something in objects. Replacing an object does not cause iterators
245 * to be invalidated and does follow insertion order (since it is not a fresh insert). If the object has
246 * been removed, we fall back to newKeys.
248 if (!REMOVED.equals(obj)) {
249 @SuppressWarnings("unchecked")
250 final V ret = (V)obj;
253 objects[offset] = value;
263 final V ret = newKeys.put(key, value);
271 public final V remove(final Object key) {
272 final Integer offset = offsets.get(key);
273 if (offset != null) {
274 final Object obj = objects[offset];
277 * A previous remove() may have indicated that the objects slot cannot be reused. In that case we need
278 * to fall back to checking with newKeys.
280 if (!REMOVED.equals(obj)) {
283 @SuppressWarnings("unchecked")
284 final V ret = (V)obj;
285 objects[offset] = removedObject();
294 final V ret = newKeys.remove(key);
302 public final void clear() {
306 Arrays.fill(objects, removedObject());
307 removed = objects.length;
313 public final Set<Entry<K, V>> entrySet() {
314 return new EntrySet();
318 public Map<K, V> toUnmodifiableMap() {
319 if (removed == 0 && newKeys.isEmpty()) {
320 // Make sure next modification clones the array, as we leak it to the map we return.
323 // We have ended up with no removed objects, hence this cast is safe
324 @SuppressWarnings("unchecked")
325 final V[] values = (V[])objects;
328 * TODO: we could track the ImmutableOffsetMap from which this one was instantiated and if we do not
329 * perform any modifications, just return the original instance. The trade-off is increased complexity
330 * and an additional field in this class.
332 return unmodifiedMap(offsets, values);
335 final int s = size();
337 return ImmutableMap.of();
340 return singletonMap();
343 // Construct the set of keys
344 final List<K> keyset = new ArrayList<>(s);
346 if (removed != offsets.size()) {
347 for (Entry<K, Integer> e : offsets.entrySet()) {
348 final Object o = objects[e.getValue()];
349 if (o != null && !REMOVED.equals(o)) {
350 keyset.add(e.getKey());
355 keyset.addAll(offsets.keySet());
357 keyset.addAll(newKeys.keySet());
359 // Construct the values
360 @SuppressWarnings("unchecked")
361 final V[] values = (V[])new Object[keyset.size()];
364 if (removed != offsets.size()) {
365 for (Entry<K, Integer> e : offsets.entrySet()) {
366 final Object o = objects[e.getValue()];
367 if (o != null && !REMOVED.equals(o)) {
368 @SuppressWarnings("unchecked")
375 System.arraycopy(objects, 0, values, 0, offsets.size());
378 for (V v : newKeys.values()) {
382 return modifiedMap(keyset, values);
385 @SuppressWarnings("unchecked")
387 public MutableOffsetMap<K, V> clone() {
388 final MutableOffsetMap<K, V> ret;
391 ret = (MutableOffsetMap<K, V>) super.clone();
392 } catch (CloneNotSupportedException e) {
393 throw new IllegalStateException("Clone is expected to work", e);
396 ret.newKeys = (HashMap<K, V>) newKeys.clone();
397 ret.needClone = true;
402 public final int hashCode() {
405 for (Entry<K, Integer> e : offsets.entrySet()) {
406 final Object v = objects[e.getValue()];
408 result += e.getKey().hashCode() ^ v.hashCode();
412 return result + newKeys.hashCode();
416 public final boolean equals(final Object o) {
420 if (!(o instanceof Map)) {
424 if (o instanceof ImmutableOffsetMap) {
425 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
427 if (newKeys.isEmpty() && offsets.equals(om.offsets())) {
428 return Arrays.deepEquals(objects, om.objects());
430 } else if (o instanceof MutableOffsetMap) {
431 final MutableOffsetMap<?, ?> om = (MutableOffsetMap<?, ?>) o;
433 if (offsets.equals(om.offsets)) {
434 return Arrays.deepEquals(objects, om.objects) && newKeys.equals(om.newKeys);
438 // Fall back to brute map compare
439 final Map<?, ?> other = (Map<?, ?>)o;
441 // Size and key sets have to match
442 if (size() != other.size() || !keySet().equals(other.keySet())) {
447 // Ensure all newKeys are present. Note newKeys is guaranteed to
448 // not contain null value.
449 for (Entry<K, V> e : newKeys.entrySet()) {
450 if (!e.getValue().equals(other.get(e.getKey()))) {
455 // Ensure all objects are present
456 for (Entry<K, Integer> e : offsets.entrySet()) {
457 final Object obj = objects[e.getValue()];
458 if (obj != null && !REMOVED.equals(obj) && !obj.equals(other.get(e.getKey()))) {
462 } catch (ClassCastException e) {
463 // Can be thrown by other.get() and indicate we have incompatible key types
471 public final Set<K> keySet() {
476 final boolean needClone() {
481 final Object array() {
486 final Object newKeys() {
490 private final class EntrySet extends AbstractSet<Entry<K, V>> {
492 public Iterator<Entry<K, V>> iterator() {
493 return new AbstractSetIterator<Entry<K, V>>() {
495 public Entry<K, V> next() {
496 final K key = nextKey();
497 return new SimpleEntry<>(key, get(key));
504 return MutableOffsetMap.this.size();
508 public boolean contains(final Object o) {
509 if (!(o instanceof Entry)) {
513 @SuppressWarnings("unchecked")
514 final Entry<K,V> e = (Entry<K,V>) o;
515 if (e.getValue() == null) {
519 return e.getValue().equals(MutableOffsetMap.this.get(e.getKey()));
523 public boolean add(final Entry<K, V> e) {
524 Preconditions.checkNotNull(e.getValue());
525 final V p = MutableOffsetMap.this.put(e.getKey(), e.getValue());
526 return !e.getValue().equals(p);
530 public boolean remove(final Object o) {
531 if (!(o instanceof Entry)) {
535 @SuppressWarnings("unchecked")
536 final Entry<K,V> e = (Entry<K,V>) o;
537 if (e.getValue() == null) {
541 final V v = MutableOffsetMap.this.get(e.getKey());
542 if (e.getValue().equals(v)) {
543 MutableOffsetMap.this.remove(e.getKey());
550 public void clear() {
551 MutableOffsetMap.this.clear();
555 private final class KeySet extends AbstractSet<K> {
557 public Iterator<K> iterator() {
558 return new AbstractSetIterator<K>() {
568 return MutableOffsetMap.this.size();
572 private abstract class AbstractSetIterator<E> implements Iterator<E> {
573 private final Iterator<Entry<K, Integer>> oldIterator = offsets.entrySet().iterator();
574 private final Iterator<K> newIterator = newKeys.keySet().iterator();
575 private int expectedModCount = modCount;
576 private K currentKey, nextKey;
578 AbstractSetIterator() {
582 private void updateNextKey() {
583 while (oldIterator.hasNext()) {
584 final Entry<K, Integer> e = oldIterator.next();
585 final Object obj = objects[e.getValue()];
586 if (obj != null && !REMOVED.equals(obj)) {
587 nextKey = e.getKey();
592 nextKey = newIterator.hasNext() ? newIterator.next() : null;
595 private void checkModCount() {
596 if (modCount != expectedModCount) {
597 throw new ConcurrentModificationException();
602 public final boolean hasNext() {
604 return nextKey != null;
608 public final void remove() {
609 Preconditions.checkState(currentKey != null);
612 final Integer offset = offsets.get(currentKey);
613 if (offset != null) {
615 objects[offset] = removedObject();
618 newIterator.remove();
621 expectedModCount = ++modCount;
625 protected final K nextKey() {
626 if (nextKey == null) {
627 throw new NoSuchElementException();
631 currentKey = nextKey;