001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.Platform.getDeclaringClassOrObjectForJ2cl;
022import static java.util.Objects.requireNonNull;
023
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.annotations.GwtIncompatible;
026import com.google.common.annotations.J2ktIncompatible;
027import java.io.IOException;
028import java.io.ObjectInputStream;
029import java.io.ObjectOutputStream;
030import java.util.EnumMap;
031import java.util.Map;
032
033/**
034 * A {@code BiMap} backed by two {@code EnumMap} instances. Null keys and values are not permitted.
035 * An {@code EnumBiMap} and its inverse are both serializable.
036 *
037 * <p>See the Guava User Guide article on <a href=
038 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">{@code BiMap}</a>.
039 *
040 * @author Mike Bostock
041 * @since 2.0
042 */
043@GwtCompatible(emulated = true)
044@J2ktIncompatible
045@ElementTypesAreNonnullByDefault
046public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends AbstractBiMap<K, V> {
047  /*
048   * J2CL's EnumMap does not need the Class instance, so we can use Object.class instead. (Or we
049   * could use null, but that messes with our nullness checking, including under J2KT. We could
050   * probably work around it by changing how we annotate the J2CL EnumMap, but that's probably more
051   * trouble than just using Object.class.)
052   *
053   * Then we declare the getters for these fields as @GwtIncompatible so that no one can try to use
054   * them under J2CL—or, as an unfortunate side effect, under GWT. We do still give the fields
055   * themselves their proper values under GWT, since GWT's EnumMap does need the Class instance.
056   *
057   * Note that sometimes these fields *do* have correct values under J2CL: They will if the caller
058   * calls `create(Foo.class)`, rather than `create(map)`. That's fine; we just shouldn't rely on
059   * it.
060   */
061  transient Class<K> keyTypeOrObjectUnderJ2cl;
062  transient Class<V> valueTypeOrObjectUnderJ2cl;
063
064  /**
065   * Returns a new, empty {@code EnumBiMap} using the specified key and value types.
066   *
067   * @param keyType the key type
068   * @param valueType the value type
069   */
070  public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(
071      Class<K> keyType, Class<V> valueType) {
072    return new EnumBiMap<>(keyType, valueType);
073  }
074
075  /**
076   * Returns a new bimap with the same mappings as the specified map. If the specified map is an
077   * {@code EnumBiMap}, the new bimap has the same types as the provided map. Otherwise, the
078   * specified map must contain at least one mapping, in order to determine the key and value types.
079   *
080   * @param map the map whose mappings are to be placed in this map
081   * @throws IllegalArgumentException if map is not an {@code EnumBiMap} instance and contains no
082   *     mappings
083   */
084  public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Map<K, V> map) {
085    EnumBiMap<K, V> bimap =
086        create(inferKeyTypeOrObjectUnderJ2cl(map), inferValueTypeOrObjectUnderJ2cl(map));
087    bimap.putAll(map);
088    return bimap;
089  }
090
091  private EnumBiMap(Class<K> keyTypeOrObjectUnderJ2cl, Class<V> valueTypeOrObjectUnderJ2cl) {
092    super(
093        new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
094    this.keyTypeOrObjectUnderJ2cl = keyTypeOrObjectUnderJ2cl;
095    this.valueTypeOrObjectUnderJ2cl = valueTypeOrObjectUnderJ2cl;
096  }
097
098  static <K extends Enum<K>> Class<K> inferKeyTypeOrObjectUnderJ2cl(Map<K, ?> map) {
099    if (map instanceof EnumBiMap) {
100      return ((EnumBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
101    }
102    if (map instanceof EnumHashBiMap) {
103      return ((EnumHashBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
104    }
105    checkArgument(!map.isEmpty());
106    return getDeclaringClassOrObjectForJ2cl(map.keySet().iterator().next());
107  }
108
109  private static <V extends Enum<V>> Class<V> inferValueTypeOrObjectUnderJ2cl(Map<?, V> map) {
110    if (map instanceof EnumBiMap) {
111      return ((EnumBiMap<?, V>) map).valueTypeOrObjectUnderJ2cl;
112    }
113    checkArgument(!map.isEmpty());
114    return getDeclaringClassOrObjectForJ2cl(map.values().iterator().next());
115  }
116
117  /** Returns the associated key type. */
118  @GwtIncompatible
119  public Class<K> keyType() {
120    return keyTypeOrObjectUnderJ2cl;
121  }
122
123  /** Returns the associated value type. */
124  @GwtIncompatible
125  public Class<V> valueType() {
126    return valueTypeOrObjectUnderJ2cl;
127  }
128
129  @Override
130  K checkKey(K key) {
131    return checkNotNull(key);
132  }
133
134  @Override
135  V checkValue(V value) {
136    return checkNotNull(value);
137  }
138
139  /**
140   * @serialData the key class, value class, number of entries, first key, first value, second key,
141   *     second value, and so on.
142   */
143  @GwtIncompatible // java.io.ObjectOutputStream
144  private void writeObject(ObjectOutputStream stream) throws IOException {
145    stream.defaultWriteObject();
146    stream.writeObject(keyTypeOrObjectUnderJ2cl);
147    stream.writeObject(valueTypeOrObjectUnderJ2cl);
148    Serialization.writeMap(this, stream);
149  }
150
151  @SuppressWarnings("unchecked") // reading fields populated by writeObject
152  @GwtIncompatible // java.io.ObjectInputStream
153  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
154    stream.defaultReadObject();
155    keyTypeOrObjectUnderJ2cl = (Class<K>) requireNonNull(stream.readObject());
156    valueTypeOrObjectUnderJ2cl = (Class<V>) requireNonNull(stream.readObject());
157    setDelegates(
158        new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
159    Serialization.populateMap(this, stream);
160  }
161
162  @GwtIncompatible // not needed in emulated source.
163  private static final long serialVersionUID = 0;
164}