001/*
002 * Copyright (C) 2012 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.reflect;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.base.Function;
021import com.google.common.collect.ForwardingMap;
022import com.google.common.collect.ForwardingMapEntry;
023import com.google.common.collect.ForwardingSet;
024import com.google.common.collect.Iterators;
025import com.google.common.collect.Maps;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import com.google.errorprone.annotations.DoNotCall;
028import java.util.Iterator;
029import java.util.Map;
030import java.util.Set;
031import org.checkerframework.checker.nullness.compatqual.NullableDecl;
032
033/**
034 * A mutable type-to-instance map. See also {@link ImmutableTypeToInstanceMap}.
035 *
036 * @author Ben Yu
037 * @since 13.0
038 */
039@Beta
040public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B>
041    implements TypeToInstanceMap<B> {
042
043  private final Map<TypeToken<? extends B>, B> backingMap = Maps.newHashMap();
044
045  @Override
046  @NullableDecl
047  public <T extends B> T getInstance(Class<T> type) {
048    return trustedGet(TypeToken.of(type));
049  }
050
051  @Override
052  @NullableDecl
053  public <T extends B> T getInstance(TypeToken<T> type) {
054    return trustedGet(type.rejectTypeVariables());
055  }
056
057  @Override
058  @CanIgnoreReturnValue
059  @NullableDecl
060  public <T extends B> T putInstance(Class<T> type, @NullableDecl T value) {
061    return trustedPut(TypeToken.of(type), value);
062  }
063
064  @Override
065  @CanIgnoreReturnValue
066  @NullableDecl
067  public <T extends B> T putInstance(TypeToken<T> type, @NullableDecl T value) {
068    return trustedPut(type.rejectTypeVariables(), value);
069  }
070
071  /**
072   * Not supported. Use {@link #putInstance} instead.
073   *
074   * @deprecated unsupported operation
075   * @throws UnsupportedOperationException always
076   */
077  @CanIgnoreReturnValue
078  @Deprecated
079  @Override
080  @DoNotCall("Always throws UnsupportedOperationException")
081  public B put(TypeToken<? extends B> key, B value) {
082    throw new UnsupportedOperationException("Please use putInstance() instead.");
083  }
084
085  /**
086   * Not supported. Use {@link #putInstance} instead.
087   *
088   * @deprecated unsupported operation
089   * @throws UnsupportedOperationException always
090   */
091  @Deprecated
092  @Override
093  @DoNotCall("Always throws UnsupportedOperationException")
094  public void putAll(Map<? extends TypeToken<? extends B>, ? extends B> map) {
095    throw new UnsupportedOperationException("Please use putInstance() instead.");
096  }
097
098  @Override
099  public Set<Entry<TypeToken<? extends B>, B>> entrySet() {
100    return UnmodifiableEntry.transformEntries(super.entrySet());
101  }
102
103  @Override
104  protected Map<TypeToken<? extends B>, B> delegate() {
105    return backingMap;
106  }
107
108  @SuppressWarnings("unchecked") // value could not get in if not a T
109  @NullableDecl
110  private <T extends B> T trustedPut(TypeToken<T> type, @NullableDecl T value) {
111    return (T) backingMap.put(type, value);
112  }
113
114  @SuppressWarnings("unchecked") // value could not get in if not a T
115  @NullableDecl
116  private <T extends B> T trustedGet(TypeToken<T> type) {
117    return (T) backingMap.get(type);
118  }
119
120  private static final class UnmodifiableEntry<K, V> extends ForwardingMapEntry<K, V> {
121
122    private final Entry<K, V> delegate;
123
124    static <K, V> Set<Entry<K, V>> transformEntries(final Set<Entry<K, V>> entries) {
125      return new ForwardingSet<Map.Entry<K, V>>() {
126        @Override
127        protected Set<Entry<K, V>> delegate() {
128          return entries;
129        }
130
131        @Override
132        public Iterator<Entry<K, V>> iterator() {
133          return UnmodifiableEntry.transformEntries(super.iterator());
134        }
135
136        @Override
137        public Object[] toArray() {
138          return standardToArray();
139        }
140
141        @Override
142        public <T> T[] toArray(T[] array) {
143          return standardToArray(array);
144        }
145      };
146    }
147
148    private static <K, V> Iterator<Entry<K, V>> transformEntries(Iterator<Entry<K, V>> entries) {
149      return Iterators.transform(
150          entries,
151          new Function<Entry<K, V>, Entry<K, V>>() {
152            @Override
153            public Entry<K, V> apply(Entry<K, V> entry) {
154              return new UnmodifiableEntry<>(entry);
155            }
156          });
157    }
158
159    private UnmodifiableEntry(java.util.Map.Entry<K, V> delegate) {
160      this.delegate = checkNotNull(delegate);
161    }
162
163    @Override
164    protected Entry<K, V> delegate() {
165      return delegate;
166    }
167
168    @Override
169    public V setValue(V value) {
170      throw new UnsupportedOperationException();
171    }
172  }
173}