001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.collect.CollectPreconditions.checkNonnegative;
020import static com.google.common.collect.CollectPreconditions.checkRemove;
021import static com.google.common.collect.Hashing.smearedHash;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.base.Objects;
026import com.google.common.collect.Maps.IteratorBasedAbstractMap;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import com.google.j2objc.annotations.RetainedWith;
029import com.google.j2objc.annotations.WeakOuter;
030import java.io.IOException;
031import java.io.ObjectInputStream;
032import java.io.ObjectOutputStream;
033import java.io.Serializable;
034import java.util.Arrays;
035import java.util.ConcurrentModificationException;
036import java.util.Iterator;
037import java.util.Map;
038import java.util.NoSuchElementException;
039import java.util.Set;
040import java.util.function.BiConsumer;
041import java.util.function.BiFunction;
042import javax.annotation.Nullable;
043
044/**
045 * A {@link BiMap} backed by two hash tables. This implementation allows null keys and values. A
046 * {@code HashBiMap} and its inverse are both serializable.
047 *
048 * <p>This implementation guarantees insertion-based iteration order of its keys.
049 *
050 * <p>See the Guava User Guide article on <a href=
051 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap"> {@code BiMap} </a>.
052 *
053 * @author Louis Wasserman
054 * @author Mike Bostock
055 * @since 2.0
056 */
057@GwtCompatible(emulated = true)
058public final class HashBiMap<K, V> extends IteratorBasedAbstractMap<K, V>
059    implements BiMap<K, V>, Serializable {
060
061  /**
062   * Returns a new, empty {@code HashBiMap} with the default initial capacity (16).
063   */
064  public static <K, V> HashBiMap<K, V> create() {
065    return create(16);
066  }
067
068  /**
069   * Constructs a new, empty bimap with the specified expected size.
070   *
071   * @param expectedSize the expected number of entries
072   * @throws IllegalArgumentException if the specified expected size is negative
073   */
074  public static <K, V> HashBiMap<K, V> create(int expectedSize) {
075    return new HashBiMap<>(expectedSize);
076  }
077
078  /**
079   * Constructs a new bimap containing initial values from {@code map}. The bimap is created with an
080   * initial capacity sufficient to hold the mappings in the specified map.
081   */
082  public static <K, V> HashBiMap<K, V> create(Map<? extends K, ? extends V> map) {
083    HashBiMap<K, V> bimap = create(map.size());
084    bimap.putAll(map);
085    return bimap;
086  }
087
088  private static final class BiEntry<K, V> extends ImmutableEntry<K, V> {
089    final int keyHash;
090    final int valueHash;
091
092    @Nullable BiEntry<K, V> nextInKToVBucket;
093    @Nullable BiEntry<K, V> nextInVToKBucket;
094
095    @Nullable BiEntry<K, V> nextInKeyInsertionOrder;
096    @Nullable BiEntry<K, V> prevInKeyInsertionOrder;
097
098    BiEntry(K key, int keyHash, V value, int valueHash) {
099      super(key, value);
100      this.keyHash = keyHash;
101      this.valueHash = valueHash;
102    }
103  }
104
105  private static final double LOAD_FACTOR = 1.0;
106
107  private transient BiEntry<K, V>[] hashTableKToV;
108  private transient BiEntry<K, V>[] hashTableVToK;
109  private transient BiEntry<K, V> firstInKeyInsertionOrder;
110  private transient BiEntry<K, V> lastInKeyInsertionOrder;
111  private transient int size;
112  private transient int mask;
113  private transient int modCount;
114
115  private HashBiMap(int expectedSize) {
116    init(expectedSize);
117  }
118
119  private void init(int expectedSize) {
120    checkNonnegative(expectedSize, "expectedSize");
121    int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR);
122    this.hashTableKToV = createTable(tableSize);
123    this.hashTableVToK = createTable(tableSize);
124    this.firstInKeyInsertionOrder = null;
125    this.lastInKeyInsertionOrder = null;
126    this.size = 0;
127    this.mask = tableSize - 1;
128    this.modCount = 0;
129  }
130
131  /**
132   * Finds and removes {@code entry} from the bucket linked lists in both the
133   * key-to-value direction and the value-to-key direction.
134   */
135  private void delete(BiEntry<K, V> entry) {
136    int keyBucket = entry.keyHash & mask;
137    BiEntry<K, V> prevBucketEntry = null;
138    for (BiEntry<K, V> bucketEntry = hashTableKToV[keyBucket];
139        true;
140        bucketEntry = bucketEntry.nextInKToVBucket) {
141      if (bucketEntry == entry) {
142        if (prevBucketEntry == null) {
143          hashTableKToV[keyBucket] = entry.nextInKToVBucket;
144        } else {
145          prevBucketEntry.nextInKToVBucket = entry.nextInKToVBucket;
146        }
147        break;
148      }
149      prevBucketEntry = bucketEntry;
150    }
151
152    int valueBucket = entry.valueHash & mask;
153    prevBucketEntry = null;
154    for (BiEntry<K, V> bucketEntry = hashTableVToK[valueBucket];
155        true;
156        bucketEntry = bucketEntry.nextInVToKBucket) {
157      if (bucketEntry == entry) {
158        if (prevBucketEntry == null) {
159          hashTableVToK[valueBucket] = entry.nextInVToKBucket;
160        } else {
161          prevBucketEntry.nextInVToKBucket = entry.nextInVToKBucket;
162        }
163        break;
164      }
165      prevBucketEntry = bucketEntry;
166    }
167
168    if (entry.prevInKeyInsertionOrder == null) {
169      firstInKeyInsertionOrder = entry.nextInKeyInsertionOrder;
170    } else {
171      entry.prevInKeyInsertionOrder.nextInKeyInsertionOrder = entry.nextInKeyInsertionOrder;
172    }
173
174    if (entry.nextInKeyInsertionOrder == null) {
175      lastInKeyInsertionOrder = entry.prevInKeyInsertionOrder;
176    } else {
177      entry.nextInKeyInsertionOrder.prevInKeyInsertionOrder = entry.prevInKeyInsertionOrder;
178    }
179
180    size--;
181    modCount++;
182  }
183
184  private void insert(BiEntry<K, V> entry, @Nullable BiEntry<K, V> oldEntryForKey) {
185    int keyBucket = entry.keyHash & mask;
186    entry.nextInKToVBucket = hashTableKToV[keyBucket];
187    hashTableKToV[keyBucket] = entry;
188
189    int valueBucket = entry.valueHash & mask;
190    entry.nextInVToKBucket = hashTableVToK[valueBucket];
191    hashTableVToK[valueBucket] = entry;
192
193    if (oldEntryForKey == null) {
194      entry.prevInKeyInsertionOrder = lastInKeyInsertionOrder;
195      entry.nextInKeyInsertionOrder = null;
196      if (lastInKeyInsertionOrder == null) {
197        firstInKeyInsertionOrder = entry;
198      } else {
199        lastInKeyInsertionOrder.nextInKeyInsertionOrder = entry;
200      }
201      lastInKeyInsertionOrder = entry;
202    } else {
203      entry.prevInKeyInsertionOrder = oldEntryForKey.prevInKeyInsertionOrder;
204      if (entry.prevInKeyInsertionOrder == null) {
205        firstInKeyInsertionOrder = entry;
206      } else {
207        entry.prevInKeyInsertionOrder.nextInKeyInsertionOrder = entry;
208      }
209      entry.nextInKeyInsertionOrder = oldEntryForKey.nextInKeyInsertionOrder;
210      if (entry.nextInKeyInsertionOrder == null) {
211        lastInKeyInsertionOrder = entry;
212      } else {
213        entry.nextInKeyInsertionOrder.prevInKeyInsertionOrder = entry;
214      }
215    }
216
217    size++;
218    modCount++;
219  }
220
221  private BiEntry<K, V> seekByKey(@Nullable Object key, int keyHash) {
222    for (BiEntry<K, V> entry = hashTableKToV[keyHash & mask];
223        entry != null;
224        entry = entry.nextInKToVBucket) {
225      if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) {
226        return entry;
227      }
228    }
229    return null;
230  }
231
232  private BiEntry<K, V> seekByValue(@Nullable Object value, int valueHash) {
233    for (BiEntry<K, V> entry = hashTableVToK[valueHash & mask];
234        entry != null;
235        entry = entry.nextInVToKBucket) {
236      if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) {
237        return entry;
238      }
239    }
240    return null;
241  }
242
243  @Override
244  public boolean containsKey(@Nullable Object key) {
245    return seekByKey(key, smearedHash(key)) != null;
246  }
247
248  @Override
249  public boolean containsValue(@Nullable Object value) {
250    return seekByValue(value, smearedHash(value)) != null;
251  }
252
253  @Nullable
254  @Override
255  public V get(@Nullable Object key) {
256    return Maps.valueOrNull(seekByKey(key, smearedHash(key)));
257  }
258
259  @CanIgnoreReturnValue
260  @Override
261  public V put(@Nullable K key, @Nullable V value) {
262    return put(key, value, false);
263  }
264
265  @CanIgnoreReturnValue
266  @Override
267  public V forcePut(@Nullable K key, @Nullable V value) {
268    return put(key, value, true);
269  }
270
271  private V put(@Nullable K key, @Nullable V value, boolean force) {
272    int keyHash = smearedHash(key);
273    int valueHash = smearedHash(value);
274
275    BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash);
276    if (oldEntryForKey != null
277        && valueHash == oldEntryForKey.valueHash
278        && Objects.equal(value, oldEntryForKey.value)) {
279      return value;
280    }
281
282    BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash);
283    if (oldEntryForValue != null) {
284      if (force) {
285        delete(oldEntryForValue);
286      } else {
287        throw new IllegalArgumentException("value already present: " + value);
288      }
289    }
290
291    BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, value, valueHash);
292    if (oldEntryForKey != null) {
293      delete(oldEntryForKey);
294      insert(newEntry, oldEntryForKey);
295      oldEntryForKey.prevInKeyInsertionOrder = null;
296      oldEntryForKey.nextInKeyInsertionOrder = null;
297      rehashIfNecessary();
298      return oldEntryForKey.value;
299    } else {
300      insert(newEntry, null);
301      rehashIfNecessary();
302      return null;
303    }
304  }
305
306  @Nullable
307  private K putInverse(@Nullable V value, @Nullable K key, boolean force) {
308    int valueHash = smearedHash(value);
309    int keyHash = smearedHash(key);
310
311    BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash);
312    BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash);
313    if (oldEntryForValue != null
314        && keyHash == oldEntryForValue.keyHash
315        && Objects.equal(key, oldEntryForValue.key)) {
316      return key;
317    } else if (oldEntryForKey != null && !force) {
318      throw new IllegalArgumentException("key already present: " + key);
319    }
320
321    /*
322     * The ordering here is important: if we deleted the key entry and then the value entry,
323     * the key entry's prev or next pointer might point to the dead value entry, and when we
324     * put the new entry in the key entry's position in iteration order, it might invalidate
325     * the linked list.
326     */
327
328    if (oldEntryForValue != null) {
329      delete(oldEntryForValue);
330    }
331
332    if (oldEntryForKey != null) {
333      delete(oldEntryForKey);
334    }
335
336    BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, value, valueHash);
337    insert(newEntry, oldEntryForKey);
338
339    if (oldEntryForKey != null) {
340      oldEntryForKey.prevInKeyInsertionOrder = null;
341      oldEntryForKey.nextInKeyInsertionOrder = null;
342    }
343    if (oldEntryForValue != null) {
344      oldEntryForValue.prevInKeyInsertionOrder = null;
345      oldEntryForValue.nextInKeyInsertionOrder = null;
346    }
347    rehashIfNecessary();
348    return Maps.keyOrNull(oldEntryForValue);
349  }
350
351  private void rehashIfNecessary() {
352    BiEntry<K, V>[] oldKToV = hashTableKToV;
353    if (Hashing.needsResizing(size, oldKToV.length, LOAD_FACTOR)) {
354      int newTableSize = oldKToV.length * 2;
355
356      this.hashTableKToV = createTable(newTableSize);
357      this.hashTableVToK = createTable(newTableSize);
358      this.mask = newTableSize - 1;
359      this.size = 0;
360
361      for (BiEntry<K, V> entry = firstInKeyInsertionOrder;
362          entry != null;
363          entry = entry.nextInKeyInsertionOrder) {
364        insert(entry, entry);
365      }
366      this.modCount++;
367    }
368  }
369
370  @SuppressWarnings("unchecked")
371  private BiEntry<K, V>[] createTable(int length) {
372    return new BiEntry[length];
373  }
374
375  @CanIgnoreReturnValue
376  @Override
377  public V remove(@Nullable Object key) {
378    BiEntry<K, V> entry = seekByKey(key, smearedHash(key));
379    if (entry == null) {
380      return null;
381    } else {
382      delete(entry);
383      entry.prevInKeyInsertionOrder = null;
384      entry.nextInKeyInsertionOrder = null;
385      return entry.value;
386    }
387  }
388
389  @Override
390  public void clear() {
391    size = 0;
392    Arrays.fill(hashTableKToV, null);
393    Arrays.fill(hashTableVToK, null);
394    firstInKeyInsertionOrder = null;
395    lastInKeyInsertionOrder = null;
396    modCount++;
397  }
398
399  @Override
400  public int size() {
401    return size;
402  }
403
404  abstract class Itr<T> implements Iterator<T> {
405    BiEntry<K, V> next = firstInKeyInsertionOrder;
406    BiEntry<K, V> toRemove = null;
407    int expectedModCount = modCount;
408
409    @Override
410    public boolean hasNext() {
411      if (modCount != expectedModCount) {
412        throw new ConcurrentModificationException();
413      }
414      return next != null;
415    }
416
417    @Override
418    public T next() {
419      if (!hasNext()) {
420        throw new NoSuchElementException();
421      }
422
423      BiEntry<K, V> entry = next;
424      next = entry.nextInKeyInsertionOrder;
425      toRemove = entry;
426      return output(entry);
427    }
428
429    @Override
430    public void remove() {
431      if (modCount != expectedModCount) {
432        throw new ConcurrentModificationException();
433      }
434      checkRemove(toRemove != null);
435      delete(toRemove);
436      expectedModCount = modCount;
437      toRemove = null;
438    }
439
440    abstract T output(BiEntry<K, V> entry);
441  }
442
443  @Override
444  public Set<K> keySet() {
445    return new KeySet();
446  }
447
448  @WeakOuter
449  private final class KeySet extends Maps.KeySet<K, V> {
450    KeySet() {
451      super(HashBiMap.this);
452    }
453
454    @Override
455    public Iterator<K> iterator() {
456      return new Itr<K>() {
457        @Override
458        K output(BiEntry<K, V> entry) {
459          return entry.key;
460        }
461      };
462    }
463
464    @Override
465    public boolean remove(@Nullable Object o) {
466      BiEntry<K, V> entry = seekByKey(o, smearedHash(o));
467      if (entry == null) {
468        return false;
469      } else {
470        delete(entry);
471        entry.prevInKeyInsertionOrder = null;
472        entry.nextInKeyInsertionOrder = null;
473        return true;
474      }
475    }
476  }
477
478  @Override
479  public Set<V> values() {
480    return inverse().keySet();
481  }
482
483  @Override
484  Iterator<Entry<K, V>> entryIterator() {
485    return new Itr<Entry<K, V>>() {
486      @Override
487      Entry<K, V> output(BiEntry<K, V> entry) {
488        return new MapEntry(entry);
489      }
490
491      class MapEntry extends AbstractMapEntry<K, V> {
492        BiEntry<K, V> delegate;
493
494        MapEntry(BiEntry<K, V> entry) {
495          this.delegate = entry;
496        }
497
498        @Override
499        public K getKey() {
500          return delegate.key;
501        }
502
503        @Override
504        public V getValue() {
505          return delegate.value;
506        }
507
508        @Override
509        public V setValue(V value) {
510          V oldValue = delegate.value;
511          int valueHash = smearedHash(value);
512          if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) {
513            return value;
514          }
515          checkArgument(seekByValue(value, valueHash) == null, "value already present: %s", value);
516          delete(delegate);
517          BiEntry<K, V> newEntry = new BiEntry<>(delegate.key, delegate.keyHash, value, valueHash);
518          insert(newEntry, delegate);
519          delegate.prevInKeyInsertionOrder = null;
520          delegate.nextInKeyInsertionOrder = null;
521          expectedModCount = modCount;
522          if (toRemove == delegate) {
523            toRemove = newEntry;
524          }
525          delegate = newEntry;
526          return oldValue;
527        }
528      }
529    };
530  }
531
532  @Override
533  public void forEach(BiConsumer<? super K, ? super V> action) {
534    checkNotNull(action);
535    for (BiEntry<K, V> entry = firstInKeyInsertionOrder;
536        entry != null;
537        entry = entry.nextInKeyInsertionOrder) {
538      action.accept(entry.key, entry.value);
539    }
540  }
541
542  @Override
543  public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
544    checkNotNull(function);
545    BiEntry<K, V> oldFirst = firstInKeyInsertionOrder;
546    clear();
547    for (BiEntry<K, V> entry = oldFirst; entry != null; entry = entry.nextInKeyInsertionOrder) {
548      put(entry.key, function.apply(entry.key, entry.value));
549    }
550  }
551
552  @RetainedWith
553  private transient BiMap<V, K> inverse;
554
555  @Override
556  public BiMap<V, K> inverse() {
557    return (inverse == null) ? inverse = new Inverse() : inverse;
558  }
559
560  private final class Inverse extends IteratorBasedAbstractMap<V, K>
561      implements BiMap<V, K>, Serializable {
562    BiMap<K, V> forward() {
563      return HashBiMap.this;
564    }
565
566    @Override
567    public int size() {
568      return size;
569    }
570
571    @Override
572    public void clear() {
573      forward().clear();
574    }
575
576    @Override
577    public boolean containsKey(@Nullable Object value) {
578      return forward().containsValue(value);
579    }
580
581    @Override
582    public K get(@Nullable Object value) {
583      return Maps.keyOrNull(seekByValue(value, smearedHash(value)));
584    }
585
586    @CanIgnoreReturnValue
587    @Override
588    public K put(@Nullable V value, @Nullable K key) {
589      return putInverse(value, key, false);
590    }
591
592    @Override
593    public K forcePut(@Nullable V value, @Nullable K key) {
594      return putInverse(value, key, true);
595    }
596
597    @Override
598    public K remove(@Nullable Object value) {
599      BiEntry<K, V> entry = seekByValue(value, smearedHash(value));
600      if (entry == null) {
601        return null;
602      } else {
603        delete(entry);
604        entry.prevInKeyInsertionOrder = null;
605        entry.nextInKeyInsertionOrder = null;
606        return entry.key;
607      }
608    }
609
610    @Override
611    public BiMap<K, V> inverse() {
612      return forward();
613    }
614
615    @Override
616    public Set<V> keySet() {
617      return new InverseKeySet();
618    }
619
620    @WeakOuter
621    private final class InverseKeySet extends Maps.KeySet<V, K> {
622      InverseKeySet() {
623        super(Inverse.this);
624      }
625
626      @Override
627      public boolean remove(@Nullable Object o) {
628        BiEntry<K, V> entry = seekByValue(o, smearedHash(o));
629        if (entry == null) {
630          return false;
631        } else {
632          delete(entry);
633          return true;
634        }
635      }
636
637      @Override
638      public Iterator<V> iterator() {
639        return new Itr<V>() {
640          @Override
641          V output(BiEntry<K, V> entry) {
642            return entry.value;
643          }
644        };
645      }
646    }
647
648    @Override
649    public Set<K> values() {
650      return forward().keySet();
651    }
652
653    @Override
654    Iterator<Entry<V, K>> entryIterator() {
655      return new Itr<Entry<V, K>>() {
656        @Override
657        Entry<V, K> output(BiEntry<K, V> entry) {
658          return new InverseEntry(entry);
659        }
660
661        class InverseEntry extends AbstractMapEntry<V, K> {
662          BiEntry<K, V> delegate;
663
664          InverseEntry(BiEntry<K, V> entry) {
665            this.delegate = entry;
666          }
667
668          @Override
669          public V getKey() {
670            return delegate.value;
671          }
672
673          @Override
674          public K getValue() {
675            return delegate.key;
676          }
677
678          @Override
679          public K setValue(K key) {
680            K oldKey = delegate.key;
681            int keyHash = smearedHash(key);
682            if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) {
683              return key;
684            }
685            checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key);
686            delete(delegate);
687            BiEntry<K, V> newEntry =
688                new BiEntry<>(key, keyHash, delegate.value, delegate.valueHash);
689            delegate = newEntry;
690            insert(newEntry, null);
691            expectedModCount = modCount;
692            // This is safe because entries can only get bumped up to earlier in the iteration,
693            // so they can't get revisited.
694            return oldKey;
695          }
696        }
697      };
698    }
699
700    @Override
701    public void forEach(BiConsumer<? super V, ? super K> action) {
702      checkNotNull(action);
703      HashBiMap.this.forEach((k, v) -> action.accept(v, k));
704    }
705
706    @Override
707    public void replaceAll(BiFunction<? super V, ? super K, ? extends K> function) {
708      checkNotNull(function);
709      BiEntry<K, V> oldFirst = firstInKeyInsertionOrder;
710      clear();
711      for (BiEntry<K, V> entry = oldFirst; entry != null; entry = entry.nextInKeyInsertionOrder) {
712        put(entry.value, function.apply(entry.value, entry.key));
713      }
714    }
715
716    Object writeReplace() {
717      return new InverseSerializedForm<>(HashBiMap.this);
718    }
719  }
720
721  private static final class InverseSerializedForm<K, V> implements Serializable {
722    private final HashBiMap<K, V> bimap;
723
724    InverseSerializedForm(HashBiMap<K, V> bimap) {
725      this.bimap = bimap;
726    }
727
728    Object readResolve() {
729      return bimap.inverse();
730    }
731  }
732
733  /**
734   * @serialData the number of entries, first key, first value, second key, second value, and so on.
735   */
736  @GwtIncompatible // java.io.ObjectOutputStream
737  private void writeObject(ObjectOutputStream stream) throws IOException {
738    stream.defaultWriteObject();
739    Serialization.writeMap(this, stream);
740  }
741
742  @GwtIncompatible // java.io.ObjectInputStream
743  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
744    stream.defaultReadObject();
745    init(16);
746    int size = Serialization.readCount(stream);
747    Serialization.populateMap(this, stream, size);
748  }
749
750  @GwtIncompatible // Not needed in emulated source
751  private static final long serialVersionUID = 0;
752}