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 static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.ImmutableMap;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.util.AbstractMap;
18 import java.util.AbstractSet;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.ConcurrentModificationException;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.LinkedHashMap;
25 import java.util.List;
27 import java.util.NoSuchElementException;
29 import javax.annotation.Nonnull;
32 * A mutable version of {@link ImmutableOffsetMap}. It inherits the set of mappings from the immutable version and
33 * allows updating/removing existing mappings. New mappings are stored in a dedicated {@link LinkedHashMap} to preserve
34 * insertion order. It also tracks the need to duplicate the backing array, so the sequence of
36 * ImmutableOffsetMap<K, V> source;
37 * ImmutableOffsetMap<K, V> result = source.createMutableClone().immutableCopy();
39 * results in source and result sharing the backing objects.
41 * <p>This map does not support null keys nor values.
43 * @param <K> the type of keys maintained by this map
44 * @param <V> the type of mapped values
47 public abstract class MutableOffsetMap<K, V> extends AbstractMap<K, V> implements Cloneable, ModifiableMapPhase<K, V> {
48 static final class Ordered<K, V> extends MutableOffsetMap<K, V> {
50 super(new LinkedHashMap<>());
53 Ordered(final Map<K, V> source) {
54 super(OffsetMapCache.orderedOffsets(source.keySet()), source, new LinkedHashMap<>());
57 Ordered(final Map<K, Integer> offsets, final V[] objects) {
58 super(offsets, objects, new LinkedHashMap<>());
62 Object removedObject() {
67 UnmodifiableMapPhase<K, V> modifiedMap(final List<K> keys, final V[] values) {
68 return new ImmutableOffsetMap.Ordered<>(OffsetMapCache.orderedOffsets(keys), values);
72 UnmodifiableMapPhase<K, V> unmodifiedMap(final Map<K, Integer> offsetMap, final V[] values) {
73 return new ImmutableOffsetMap.Ordered<>(offsetMap, values);
77 SharedSingletonMap<K, V> singletonMap() {
78 return SharedSingletonMap.orderedCopyOf(this);
82 static final class Unordered<K, V> extends MutableOffsetMap<K, V> {
84 super(new HashMap<>());
87 Unordered(final Map<K, V> source) {
88 super(OffsetMapCache.unorderedOffsets(source.keySet()), source, new HashMap<>());
91 Unordered(final Map<K, Integer> offsets, final V[] objects) {
92 super(offsets, objects, new HashMap<>());
96 Object removedObject() {
101 UnmodifiableMapPhase<K, V> modifiedMap(final List<K> keys, final V[] values) {
102 final Map<K, Integer> offsets = OffsetMapCache.unorderedOffsets(keys);
103 return new ImmutableOffsetMap.Unordered<>(offsets, OffsetMapCache.adjustedArray(offsets, keys, values));
107 UnmodifiableMapPhase<K, V> unmodifiedMap(final Map<K, Integer> offsetMap, final V[] values) {
108 return new ImmutableOffsetMap.Unordered<>(offsetMap, values);
112 SharedSingletonMap<K, V> singletonMap() {
113 return SharedSingletonMap.unorderedCopyOf(this);
117 private static final Object[] EMPTY_ARRAY = new Object[0];
118 private static final Object REMOVED = new Object();
119 private final Map<K, Integer> offsets;
120 private HashMap<K, V> newKeys;
121 private Object[] objects;
122 private int removed = 0;
124 // Fail-fast iterator guard, see java.util.ArrayList for reference.
125 @SuppressFBWarnings("VO_VOLATILE_INCREMENT")
126 private transient volatile int modCount;
127 private boolean needClone = true;
129 MutableOffsetMap(final Map<K, Integer> offsets, final V[] objects, final HashMap<K, V> newKeys) {
130 verify(newKeys.isEmpty());
131 this.offsets = requireNonNull(offsets);
132 this.objects = requireNonNull(objects);
133 this.newKeys = requireNonNull(newKeys);
136 @SuppressWarnings("unchecked")
137 MutableOffsetMap(final HashMap<K, V> newKeys) {
138 this(ImmutableMap.of(), (V[]) EMPTY_ARRAY, newKeys);
141 @SuppressWarnings("unchecked")
142 MutableOffsetMap(final Map<K, Integer> offsets, final Map<K, V> source, final HashMap<K, V> newKeys) {
143 this(offsets, (V[]) new Object[offsets.size()], newKeys);
145 for (Entry<K, V> e : source.entrySet()) {
146 objects[offsets.get(e.getKey())] = requireNonNull(e.getValue());
149 this.needClone = false;
152 public static <K, V> MutableOffsetMap<K, V> orderedCopyOf(final Map<K, V> map) {
153 if (map instanceof Ordered) {
154 return ((Ordered<K, V>) map).clone();
156 if (map instanceof ImmutableOffsetMap) {
157 final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) map;
158 return new Ordered<>(om.offsets(), om.objects());
161 return new Ordered<>(map);
164 public static <K, V> MutableOffsetMap<K, V> unorderedCopyOf(final Map<K, V> map) {
165 if (map instanceof Unordered) {
166 return ((Unordered<K, V>) map).clone();
168 if (map instanceof ImmutableOffsetMap) {
169 final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) map;
170 return new Unordered<>(om.offsets(), om.objects());
173 return new Unordered<>(map);
176 public static <K, V> MutableOffsetMap<K, V> ordered() {
177 return new MutableOffsetMap.Ordered<>();
180 public static <K, V> MutableOffsetMap<K, V> unordered() {
181 return new MutableOffsetMap.Unordered<>();
184 abstract Object removedObject();
186 abstract UnmodifiableMapPhase<K, V> modifiedMap(List<K> keys, V[] values);
188 abstract UnmodifiableMapPhase<K, V> unmodifiedMap(Map<K, Integer> offsetMap, V[] values);
190 abstract SharedSingletonMap<K, V> singletonMap();
193 public final int size() {
194 return offsets.size() + newKeys.size() - removed;
198 public final boolean isEmpty() {
203 public final boolean containsKey(final Object key) {
204 final Integer offset = offsets.get(key);
205 if (offset != null) {
206 final Object obj = objects[offset];
207 if (!REMOVED.equals(obj)) {
212 return newKeys.containsKey(key);
216 public final V get(final Object key) {
217 final Integer offset = offsets.get(key);
218 if (offset != null) {
219 final Object obj = objects[offset];
222 * This is a bit tricky: Ordered will put REMOVED to removed objects to retain strict insertion order.
223 * Unordered will add null, indicating that the slot may be reused in future. Hence if we see a REMOVED
224 * marker, we need to fall back to checking with new keys.
226 if (!REMOVED.equals(obj)) {
227 @SuppressWarnings("unchecked")
228 final V ret = (V)obj;
233 return newKeys.get(key);
236 private void cloneArray() {
239 if (objects.length != 0) {
240 objects = objects.clone();
246 public final V put(final K key, final V value) {
247 requireNonNull(value);
248 final Integer offset = offsets.get(requireNonNull(key));
249 if (offset != null) {
250 final Object obj = objects[offset];
253 * Put which can potentially replace something in objects. Replacing an object does not cause iterators
254 * to be invalidated and does follow insertion order (since it is not a fresh insert). If the object has
255 * been removed, we fall back to newKeys.
257 if (!REMOVED.equals(obj)) {
258 @SuppressWarnings("unchecked")
259 final V ret = (V)obj;
262 objects[offset] = value;
272 final V ret = newKeys.put(key, value);
280 public final V remove(final Object key) {
281 final Integer offset = offsets.get(key);
282 if (offset != null) {
283 final Object obj = objects[offset];
286 * A previous remove() may have indicated that the objects slot cannot be reused. In that case we need
287 * to fall back to checking with newKeys.
289 if (!REMOVED.equals(obj)) {
292 @SuppressWarnings("unchecked")
293 final V ret = (V)obj;
294 objects[offset] = removedObject();
303 final V ret = newKeys.remove(key);
311 public final void clear() {
315 Arrays.fill(objects, removedObject());
316 removed = objects.length;
323 public final Set<Entry<K, V>> entrySet() {
324 return new EntrySet();
329 public Map<K, V> toUnmodifiableMap() {
330 if (removed == 0 && newKeys.isEmpty()) {
331 // Make sure next modification clones the array, as we leak it to the map we return.
334 // We have ended up with no removed objects, hence this cast is safe
335 @SuppressWarnings("unchecked")
336 final V[] values = (V[])objects;
339 * TODO: we could track the ImmutableOffsetMap from which this one was instantiated and if we do not
340 * perform any modifications, just return the original instance. The trade-off is increased complexity
341 * and an additional field in this class.
343 return unmodifiedMap(offsets, values);
346 final int s = size();
348 return ImmutableMap.of();
351 return singletonMap();
354 // Construct the set of keys
355 final List<K> keyset = new ArrayList<>(s);
357 if (removed != offsets.size()) {
358 for (Entry<K, Integer> e : offsets.entrySet()) {
359 final Object o = objects[e.getValue()];
360 if (o != null && !REMOVED.equals(o)) {
361 keyset.add(e.getKey());
366 keyset.addAll(offsets.keySet());
368 keyset.addAll(newKeys.keySet());
370 // Construct the values
371 @SuppressWarnings("unchecked")
372 final V[] values = (V[])new Object[keyset.size()];
375 if (removed != offsets.size()) {
376 for (Entry<K, Integer> e : offsets.entrySet()) {
377 final Object o = objects[e.getValue()];
378 if (o != null && !REMOVED.equals(o)) {
379 @SuppressWarnings("unchecked")
381 values[offset++] = v;
386 System.arraycopy(objects, 0, values, 0, offsets.size());
387 offset = offsets.size();
389 for (V v : newKeys.values()) {
390 values[offset++] = v;
393 return modifiedMap(keyset, values);
396 @SuppressWarnings("unchecked")
398 public MutableOffsetMap<K, V> clone() {
399 final MutableOffsetMap<K, V> ret;
402 ret = (MutableOffsetMap<K, V>) super.clone();
403 } catch (CloneNotSupportedException e) {
404 throw new IllegalStateException("Clone is expected to work", e);
407 ret.newKeys = (HashMap<K, V>) newKeys.clone();
408 ret.needClone = true;
413 public final int hashCode() {
416 for (Entry<K, Integer> e : offsets.entrySet()) {
417 final Object v = objects[e.getValue()];
419 result += e.getKey().hashCode() ^ v.hashCode();
423 return result + newKeys.hashCode();
427 public final boolean equals(final Object obj) {
431 if (!(obj instanceof Map)) {
435 if (obj instanceof ImmutableOffsetMap) {
436 final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
438 if (newKeys.isEmpty() && offsets.equals(om.offsets())) {
439 return Arrays.deepEquals(objects, om.objects());
441 } else if (obj instanceof MutableOffsetMap) {
442 final MutableOffsetMap<?, ?> om = (MutableOffsetMap<?, ?>) obj;
444 if (offsets.equals(om.offsets)) {
445 return Arrays.deepEquals(objects, om.objects) && newKeys.equals(om.newKeys);
449 // Fall back to brute map compare
450 final Map<?, ?> other = (Map<?, ?>)obj;
452 // Size and key sets have to match
453 if (size() != other.size() || !keySet().equals(other.keySet())) {
458 // Ensure all newKeys are present. Note newKeys is guaranteed to
459 // not contain null value.
460 for (Entry<K, V> e : newKeys.entrySet()) {
461 if (!e.getValue().equals(other.get(e.getKey()))) {
466 // Ensure all objects are present
467 for (Entry<K, Integer> e : offsets.entrySet()) {
468 final Object val = objects[e.getValue()];
469 if (val != null && !REMOVED.equals(val) && !val.equals(other.get(e.getKey()))) {
473 } catch (ClassCastException e) {
474 // Can be thrown by other.get() and indicate we have incompatible key types
483 public final Set<K> keySet() {
488 final boolean needClone() {
493 final Object array() {
498 final Object newKeys() {
502 private final class EntrySet extends AbstractSet<Entry<K, V>> {
505 public Iterator<Entry<K, V>> iterator() {
506 return new AbstractSetIterator<Entry<K, V>>() {
508 public Entry<K, V> next() {
509 final K key = nextKey();
510 return new SimpleEntry<>(key, get(key));
517 return MutableOffsetMap.this.size();
521 @SuppressWarnings("checkstyle:parameterName")
522 public boolean contains(final Object o) {
523 if (!(o instanceof Entry)) {
527 @SuppressWarnings("unchecked")
528 final Entry<K,V> e = (Entry<K,V>) o;
529 if (e.getValue() == null) {
533 return e.getValue().equals(MutableOffsetMap.this.get(e.getKey()));
537 @SuppressWarnings("checkstyle:parameterName")
538 public boolean add(final Entry<K, V> e) {
539 final V v = requireNonNull(e.getValue());
540 final V p = MutableOffsetMap.this.put(e.getKey(), v);
545 @SuppressWarnings("checkstyle:parameterName")
546 public boolean remove(final Object o) {
547 if (!(o instanceof Entry)) {
551 @SuppressWarnings("unchecked")
552 final Entry<K,V> e = (Entry<K,V>) o;
553 if (e.getValue() == null) {
557 final V v = MutableOffsetMap.this.get(e.getKey());
558 if (e.getValue().equals(v)) {
559 MutableOffsetMap.this.remove(e.getKey());
566 public void clear() {
567 MutableOffsetMap.this.clear();
571 private final class KeySet extends AbstractSet<K> {
574 public Iterator<K> iterator() {
575 return new AbstractSetIterator<K>() {
585 return MutableOffsetMap.this.size();
589 private abstract class AbstractSetIterator<E> implements Iterator<E> {
590 private final Iterator<Entry<K, Integer>> oldIterator = offsets.entrySet().iterator();
591 private final Iterator<K> newIterator = newKeys.keySet().iterator();
592 private int expectedModCount = modCount;
593 private K currentKey;
596 AbstractSetIterator() {
600 private void updateNextKey() {
601 while (oldIterator.hasNext()) {
602 final Entry<K, Integer> e = oldIterator.next();
603 final Object obj = objects[e.getValue()];
604 if (obj != null && !REMOVED.equals(obj)) {
605 nextKey = e.getKey();
610 nextKey = newIterator.hasNext() ? newIterator.next() : null;
613 private void checkModCount() {
614 if (modCount != expectedModCount) {
615 throw new ConcurrentModificationException();
620 public final boolean hasNext() {
622 return nextKey != null;
626 public final void remove() {
627 requireNonNull(currentKey != null);
630 final Integer offset = offsets.get(currentKey);
631 if (offset != null) {
633 objects[offset] = removedObject();
636 newIterator.remove();
639 expectedModCount = ++modCount;
643 protected final K nextKey() {
644 if (nextKey == null) {
645 throw new NoSuchElementException();
649 currentKey = nextKey;