Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ public class Exemplars implements Iterable<Exemplar> {
private final List<Exemplar> exemplars;

private Exemplars(Collection<Exemplar> exemplars) {
if (exemplars.isEmpty()) {
this.exemplars = Collections.emptyList();
return;
}
List<Exemplar> copy = new ArrayList<>(exemplars.size());
for (Exemplar exemplar : exemplars) {
if (exemplar == null) {
Expand All @@ -41,7 +45,7 @@ private Exemplars(Collection<Exemplar> exemplars) {
* @param exemplars a copy of the exemplars collection will be created.
*/
public static Exemplars of(Collection<Exemplar> exemplars) {
return new Exemplars(exemplars);
return exemplars.isEmpty() ? EMPTY : new Exemplars(exemplars);
}

/**
Expand All @@ -51,7 +55,7 @@ public static Exemplars of(Collection<Exemplar> exemplars) {
* @param exemplars a copy of the exemplars array will be created.
*/
public static Exemplars of(Exemplar... exemplars) {
return new Exemplars(Arrays.asList(exemplars));
return exemplars.length == 0 ? EMPTY : new Exemplars(Arrays.asList(exemplars));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import java.util.Collections;
import java.util.Iterator;
import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -53,4 +54,22 @@ void testGet() {

assertThat(exemplars.getLatest()).isSameAs(newest);
}

@Test
void testEmptyReturnsSingleton() {
// Empty inputs short-circuit to the EMPTY singleton, avoiding allocations.
assertThat(Exemplars.of()).isSameAs(Exemplars.EMPTY);
assertThat(Exemplars.of(Collections.emptyList())).isSameAs(Exemplars.EMPTY);
assertThat(Exemplars.builder().build()).isSameAs(Exemplars.EMPTY);
}

@Test
void testEmptyIteratorIsSingleton() {
// Collections.emptyList().iterator() returns the JDK singleton empty iterator, so reading an
// empty Exemplars allocates no iterator.
assertThat(Exemplars.EMPTY.size()).isZero();
assertThat(Exemplars.EMPTY.iterator()).isSameAs(Collections.emptyIterator());
assertThat(Exemplars.EMPTY.get(0.0, Double.POSITIVE_INFINITY)).isNull();
assertThat(Exemplars.EMPTY.getLatest()).isNull();
}
}