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