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.checkNotNull;
020
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.primitives.Primitives;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import java.io.InvalidObjectException;
025import java.io.ObjectInputStream;
026import java.io.Serializable;
027import java.util.HashMap;
028import java.util.Iterator;
029import java.util.LinkedHashMap;
030import java.util.Map;
031import java.util.Set;
032import java.util.Spliterator;
033import javax.annotation.CheckForNull;
034import org.checkerframework.checker.nullness.qual.Nullable;
035
036/**
037 * A mutable class-to-instance map backed by an arbitrary user-provided map. See also {@link
038 * ImmutableClassToInstanceMap}.
039 *
040 * <p>See the Guava User Guide article on <a href=
041 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
042 * ClassToInstanceMap}</a>.
043 *
044 * <p>This implementation <i>does</i> support null values, despite how it is annotated; see
045 * discussion at {@link ClassToInstanceMap}.
046 *
047 * @author Kevin Bourrillion
048 * @since 2.0
049 */
050@GwtIncompatible
051@SuppressWarnings("serial") // using writeReplace instead of standard serialization
052@ElementTypesAreNonnullByDefault
053public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B>
054    implements ClassToInstanceMap<B>, Serializable {
055
056  /**
057   * Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link HashMap} using the
058   * default initial capacity and load factor.
059   */
060  public static <B> MutableClassToInstanceMap<B> create() {
061    return new MutableClassToInstanceMap<B>(new HashMap<Class<? extends B>, B>());
062  }
063
064  /**
065   * Returns a new {@code MutableClassToInstanceMap} instance backed by a given empty {@code
066   * backingMap}. The caller surrenders control of the backing map, and thus should not allow any
067   * direct references to it to remain accessible.
068   */
069  public static <B> MutableClassToInstanceMap<B> create(Map<Class<? extends B>, B> backingMap) {
070    return new MutableClassToInstanceMap<B>(backingMap);
071  }
072
073  private final Map<Class<? extends B>, B> delegate;
074
075  private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) {
076    this.delegate = checkNotNull(delegate);
077  }
078
079  @Override
080  protected Map<Class<? extends B>, B> delegate() {
081    return delegate;
082  }
083
084  /**
085   * Wraps the {@code setValue} implementation of an {@code Entry} to enforce the class constraint.
086   */
087  private static <B> Entry<Class<? extends B>, B> checkedEntry(
088      final Entry<Class<? extends B>, B> entry) {
089    return new ForwardingMapEntry<Class<? extends B>, B>() {
090      @Override
091      protected Entry<Class<? extends B>, B> delegate() {
092        return entry;
093      }
094
095      @Override
096      public B setValue(B value) {
097        return super.setValue(cast(getKey(), value));
098      }
099    };
100  }
101
102  @Override
103  public Set<Entry<Class<? extends B>, B>> entrySet() {
104    return new ForwardingSet<Entry<Class<? extends B>, B>>() {
105
106      @Override
107      protected Set<Entry<Class<? extends B>, B>> delegate() {
108        return MutableClassToInstanceMap.this.delegate().entrySet();
109      }
110
111      @Override
112      public Spliterator<Entry<Class<? extends B>, B>> spliterator() {
113        return CollectSpliterators.map(
114            delegate().spliterator(), MutableClassToInstanceMap::checkedEntry);
115      }
116
117      @Override
118      public Iterator<Entry<Class<? extends B>, B>> iterator() {
119        return new TransformedIterator<Entry<Class<? extends B>, B>, Entry<Class<? extends B>, B>>(
120            delegate().iterator()) {
121          @Override
122          Entry<Class<? extends B>, B> transform(Entry<Class<? extends B>, B> from) {
123            return checkedEntry(from);
124          }
125        };
126      }
127
128      @Override
129      public Object[] toArray() {
130        /*
131         * standardToArray returns `@Nullable Object[]` rather than `Object[]` but only because it
132         * can be used with collections that may contain null. This collection is a collection of
133         * non-null Entry objects (Entry objects that might contain null values but are not
134         * themselves null), so we can treat it as a plain `Object[]`.
135         */
136        @SuppressWarnings("nullness")
137        Object[] result = standardToArray();
138        return result;
139      }
140
141      @Override
142      @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
143      public <T extends @Nullable Object> T[] toArray(T[] array) {
144        return standardToArray(array);
145      }
146    };
147  }
148
149  @Override
150  @CanIgnoreReturnValue
151  @CheckForNull
152  public B put(Class<? extends B> key, B value) {
153    return super.put(key, cast(key, value));
154  }
155
156  @Override
157  public void putAll(Map<? extends Class<? extends B>, ? extends B> map) {
158    Map<Class<? extends B>, B> copy = new LinkedHashMap<>(map);
159    for (Entry<? extends Class<? extends B>, B> entry : copy.entrySet()) {
160      cast(entry.getKey(), entry.getValue());
161    }
162    super.putAll(copy);
163  }
164
165  @CanIgnoreReturnValue
166  @Override
167  @CheckForNull
168  public <T extends B> T putInstance(Class<T> type, T value) {
169    return cast(type, put(type, value));
170  }
171
172  @Override
173  @CheckForNull
174  public <T extends B> T getInstance(Class<T> type) {
175    return cast(type, get(type));
176  }
177
178  @CanIgnoreReturnValue
179  @CheckForNull
180  private static <B, T extends B> T cast(Class<T> type, @CheckForNull B value) {
181    return Primitives.wrap(type).cast(value);
182  }
183
184  private Object writeReplace() {
185    return new SerializedForm(delegate());
186  }
187
188  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
189    throw new InvalidObjectException("Use SerializedForm");
190  }
191
192  /** Serialized form of the map, to avoid serializing the constraint. */
193  private static final class SerializedForm<B> implements Serializable {
194    private final Map<Class<? extends B>, B> backingMap;
195
196    SerializedForm(Map<Class<? extends B>, B> backingMap) {
197      this.backingMap = backingMap;
198    }
199
200    Object readResolve() {
201      return create(backingMap);
202    }
203
204    private static final long serialVersionUID = 0;
205  }
206}