1/*
2 * Copyright (C) 2007 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.collect;
18
19import com.google.common.collect.MapConstraints.ConstrainedMap;
20import com.google.common.primitives.Primitives;
21
22import java.util.HashMap;
23import java.util.Map;
24
25/**
26 * A mutable class-to-instance map backed by an arbitrary user-provided map.
27 * See also {@link ImmutableClassToInstanceMap}.
28 *
29 * @author Kevin Bourrillion
30 * @since 2.0 (imported from Google Collections Library)
31 */
32public final class MutableClassToInstanceMap<B>
33    extends ConstrainedMap<Class<? extends B>, B>
34    implements ClassToInstanceMap<B> {
35
36  /**
37   * Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link
38   * HashMap} using the default initial capacity and load factor.
39   */
40  public static <B> MutableClassToInstanceMap<B> create() {
41    return new MutableClassToInstanceMap<B>(
42        new HashMap<Class<? extends B>, B>());
43  }
44
45  /**
46   * Returns a new {@code MutableClassToInstanceMap} instance backed by a given
47   * empty {@code backingMap}. The caller surrenders control of the backing map,
48   * and thus should not allow any direct references to it to remain accessible.
49   */
50  public static <B> MutableClassToInstanceMap<B> create(
51      Map<Class<? extends B>, B> backingMap) {
52    return new MutableClassToInstanceMap<B>(backingMap);
53  }
54
55  private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) {
56    super(delegate, VALUE_CAN_BE_CAST_TO_KEY);
57  }
58
59  private static final MapConstraint<Class<?>, Object> VALUE_CAN_BE_CAST_TO_KEY
60      = new MapConstraint<Class<?>, Object>() {
61    @Override
62    public void checkKeyValue(Class<?> key, Object value) {
63      cast(key, value);
64    }
65  };
66
67  @Override
68  public <T extends B> T putInstance(Class<T> type, T value) {
69    return cast(type, put(type, value));
70  }
71
72  @Override
73  public <T extends B> T getInstance(Class<T> type) {
74    return cast(type, get(type));
75  }
76
77  private static <B, T extends B> T cast(Class<T> type, B value) {
78    return Primitives.wrap(type).cast(value);
79  }
80
81  private static final long serialVersionUID = 0;
82}
83