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