Skip to content

Commit

Permalink
Replace SmallSortedMap.EmptySet with equivalent Collections.emptySet()
Browse files Browse the repository at this point in the history
This reduces our code weight by a little (3 classes).

Collections.emptySet also has a singleton empty iterator, so it doesn't allocate.

PiperOrigin-RevId: 633667264
  • Loading branch information
mhansen authored and copybara-github committed May 14, 2024
1 parent 396d661 commit c6e2778
Showing 1 changed file with 2 additions and 42 deletions.
44 changes: 2 additions & 42 deletions java/core/src/main/java/com/google/protobuf/SmallSortedMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
Expand Down Expand Up @@ -169,13 +168,13 @@ public int getNumOverflowEntries() {
/** @return An iterable over the overflow entries. */
public Iterable<Map.Entry<K, V>> getOverflowEntries() {
return overflowEntries.isEmpty()
? EmptySet.<Map.Entry<K, V>>iterable()
? Collections.emptySet()
: overflowEntries.entrySet();
}

Iterable<Map.Entry<K, V>> getOverflowEntriesDescending() {
return overflowEntriesDescending.isEmpty()
? EmptySet.<Map.Entry<K, V>>iterable()
? Collections.emptySet()
: overflowEntriesDescending.entrySet();
}

Expand Down Expand Up @@ -597,45 +596,6 @@ private Iterator<Map.Entry<K, V>> getOverflowIterator() {
}
}

/**
* Helper class that holds immutable instances of an Iterable/Iterator that we return when the
* overflow entries is empty. This eliminates the creation of an Iterator object when there is
* nothing to iterate over.
*/
private static class EmptySet {

private static final Iterator<Object> ITERATOR =
new Iterator<Object>() {
@Override
public boolean hasNext() {
return false;
}

@Override
public Object next() {
throw new NoSuchElementException();
}

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

private static final Iterable<Object> ITERABLE =
new Iterable<Object>() {
@Override
public Iterator<Object> iterator() {
return ITERATOR;
}
};

@SuppressWarnings("unchecked")
static <T> Iterable<T> iterable() {
return (Iterable<T>) ITERABLE;
}
}

@Override
public boolean equals(Object o) {
if (this == o) {
Expand Down

0 comments on commit c6e2778

Please sign in to comment.