aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyMap.java
blob: 8b980d9980aa8b08979d0ab784d7b70475646e1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.collect;

import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableSet;

import java.util.AbstractCollection;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;

/**
 * A immutable map implementation for maps with comparable keys. It uses a sorted array
 * and binary search to return the correct values. Its only purpose is to save memory - for n
 * entries, it consumes 8n + 64 bytes, much less than a normal HashMap (43n + 128) or an
 * ImmutableMap (35n + 81).
 *
 * <p>Only a few methods are efficiently implemented: {@link #isEmpty} is O(1), {@link #get} and
 * {@link #containsKey} are O(log(n)), using binary search; {@link #keySet} and {@link #values}
 * refer to the parent instance. All other methods can take O(n) or even make a copy of the
 * contents.
 *
 * <p>This implementation supports neither {@code null} keys nor {@code null} values.
 *
 * @param <K> the type of keys maintained by this map; keys must be comparable
 * @param <V> the type of mapped values
 */
public final class ImmutableSortedKeyMap<K extends Comparable<K>, V> implements Map<K, V> {

  @SuppressWarnings({"rawtypes", "unchecked"})
  private static final ImmutableSortedKeyMap EMPTY_MAP =
      new ImmutableSortedKeyMap(new Comparable<?>[0], new Object[0]);

  /** Returns the empty multimap. */
  @SuppressWarnings("unchecked")
  public static <K extends Comparable<K>, V> ImmutableSortedKeyMap<K, V> of() {
    // Safe because the multimap will never hold any elements.
    return EMPTY_MAP;
  }

  public static <K extends Comparable<K>, V> ImmutableSortedKeyMap<K, V> of(K key0, V value0) {
    return ImmutableSortedKeyMap.<K, V>builder()
        .put(key0, value0)
        .build();
  }

  public static <K extends Comparable<K>, V> ImmutableSortedKeyMap<K, V> of(
      K key0, V value0, K key1, V value1) {
    return ImmutableSortedKeyMap.<K, V>builder()
        .put(key0, value0)
        .put(key1, value1)
        .build();
  }

  @SuppressWarnings("unchecked")
  public static <K extends Comparable<K>, V> ImmutableSortedKeyMap<K, V> copyOf(Map<K, V> data) {
    if (data.isEmpty()) {
      return EMPTY_MAP;
    }
    if (data instanceof ImmutableSortedKeyMap) {
      return (ImmutableSortedKeyMap<K, V>) data;
    }
    Set<K> keySet = data.keySet();
    int size = keySet.size();
    K[] sortedKeys = (K[]) new Comparable<?>[size];
    int index = 0;
    for (K key : keySet) {
      sortedKeys[index] = Preconditions.checkNotNull(key);
      index++;
    }
    Arrays.sort(sortedKeys);
    V[] values = (V[]) new Object[size];
    for (int i = 0; i < size; i++) {
      values[i] = data.get(sortedKeys[i]);
    }
    return new ImmutableSortedKeyMap<>(sortedKeys, values);
  }

  public static <K extends Comparable<K>, V> Builder<K, V> builder() {
    return new Builder<>();
  }

  /**
   * A builder class for ImmutableSortedKeyListMultimap<K, V> instances.
   */
  public static final class Builder<K extends Comparable<K>, V> {
    private final Map<K, V> builderMap = new HashMap<>();

    Builder() {
      // Not public so you must call builder() instead.
    }

    public ImmutableSortedKeyMap<K, V> build() {
      return ImmutableSortedKeyMap.copyOf(builderMap);
    }

    public Builder<K, V> put(K key, V value) {
      builderMap.put(Preconditions.checkNotNull(key), Preconditions.checkNotNull(value));
      return this;
    }

    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
      for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
        put(entry.getKey(), entry.getValue());
      }
      return this;
    }
  }

  private class ValuesCollection extends AbstractCollection<V> {

    ValuesCollection() {
    }

    @Override
    public int size() {
      return ImmutableSortedKeyMap.this.size();
    }

    @Override
    public boolean isEmpty() {
      return sortedKeys.length == 0;
    }

    @Override
    public boolean contains(Object o) {
      return ImmutableSortedKeyMap.this.containsValue(o);
    }

    @Override
    public Iterator<V> iterator() {
      if (isEmpty()) {
        return Collections.emptyIterator();
      }
      return new AbstractIterator<V>() {
        private int currentIndex = 0;

        @Override
        protected V computeNext() {
          if (currentIndex >= values.length) {
            return endOfData();
          }
          return values[currentIndex++];
        }
      };
    }

    @Override
    public boolean remove(Object o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
      throw new UnsupportedOperationException();
    }
  }

  private final K[] sortedKeys;
  private final V[] values;

  private ImmutableSortedKeyMap(K[] sortedKeys, V[] values) {
    this.sortedKeys = sortedKeys;
    this.values = values;
  }

  @Override
  public int size() {
    return sortedKeys.length;
  }

  @Override
  public boolean isEmpty() {
    return sortedKeys.length == 0;
  }

  @Override
  public boolean containsKey(@Nullable Object key) {
    if (key == null) {
      return false;
    }
    int index = Arrays.binarySearch(sortedKeys, key);
    return index >= 0;
  }

  @Override
  public boolean containsValue(@Nullable Object value) {
    if (value == null) {
      return false;
    }
    for (V v : values) {
      if (v.equals(value)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public V put(K key, V value) {
    throw new UnsupportedOperationException();
  }

  @Override
  public V remove(Object key) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void putAll(Map<? extends K, ? extends V> map) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void clear() {
    throw new UnsupportedOperationException();
  }

  @Override
  public V get(@Nullable Object key) {
    if (key == null) {
      return null;
    }
    int index = Arrays.binarySearch(sortedKeys, key);
    return index >= 0 ? values[index] : null;
  }

  @Override
  public Set<K> keySet() {
    return ImmutableSet.copyOf(sortedKeys);
  }

  @Override
  public Collection<V> values() {
    return new ValuesCollection();
  }

  @Override
  public Set<Entry<K, V>> entrySet() {
    ImmutableSet.Builder<Entry<K, V>> builder = ImmutableSet.builder();
    for (int i = 0; i < sortedKeys.length; i++) {
      builder.add(new SimpleImmutableEntry<K, V>(sortedKeys[i], values[i]));
    }
    return builder.build();
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder();
    result.append('{');
    for (int i = 0; i < sortedKeys.length; i++) {
      if (i != 0) {
        result.append(", ");
      }
      result.append(sortedKeys[i]).append('=').append(values[i]);
    }
    result.append('}');
    return result.toString();
  }

  @Override
  public int hashCode() {
    int h = 0;
    for (Entry<K, V> entry : entrySet()) {
      h += entry.hashCode();
    }
    return h;
  }

  @Override
  public boolean equals(@Nullable Object object) {
    if (this == object) {
      return true;
    }
    if (object instanceof Map) {
      throw new UnsupportedOperationException();
    }
    return false;
  }
}