Googler | 231e24e | 2017-06-19 19:46:47 -0400 | [diff] [blame] | 1 | // Copyright 2017 The Bazel Authors. All rights reserved. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package com.google.devtools.build.lib.collect; |
| 16 | |
| 17 | import java.util.Iterator; |
| 18 | |
| 19 | /** |
| 20 | * A minimal map interface that avoids methods whose implementation tends to force GC churn, or |
| 21 | * otherwise overly constrain implementation freedom. |
| 22 | * |
| 23 | * <p>TODO: Convert to interface once we move to Java 8. |
| 24 | */ |
| 25 | public abstract class CompactImmutableMap<K, V> implements Iterable<K> { |
| 26 | |
| 27 | public boolean containsKey(K key) { |
| 28 | return get(key) != null; |
| 29 | } |
| 30 | |
| 31 | public abstract V get(K key); |
| 32 | |
| 33 | public abstract int size(); |
| 34 | |
| 35 | public abstract K keyAt(int index); |
| 36 | |
| 37 | public abstract V valueAt(int index); |
| 38 | |
| 39 | @Override |
| 40 | public Iterator<K> iterator() { |
| 41 | return new ImmutableMapSharedKeysIterator(); |
| 42 | } |
| 43 | |
| 44 | private class ImmutableMapSharedKeysIterator implements Iterator<K> { |
| 45 | int index = 0; |
| 46 | |
| 47 | @Override |
| 48 | public boolean hasNext() { |
| 49 | return index < size(); |
| 50 | } |
| 51 | |
| 52 | @Override |
| 53 | public K next() { |
| 54 | K key = keyAt(index); |
| 55 | ++index; |
| 56 | return key; |
| 57 | } |
| 58 | } |
| 59 | } |