Add TraceState.asMap (#2190)

* Add TraceState.asMap

* Javadoc

* Spot
This commit is contained in:
Anuraag Agrawal 2020-12-04 12:40:11 +09:00 committed by GitHub
parent efe5fbf0aa
commit 643b697106
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 27 additions and 2 deletions

View File

@ -30,10 +30,12 @@ import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/** A read-only view of an array of key-value pairs. */
@SuppressWarnings("unchecked")
final class ReadOnlyArrayMap<K, V> implements Map<K, V> {
public final class ReadOnlyArrayMap<K, V> implements Map<K, V> {
static <K, V> Map<K, V> wrap(List<Object> array) {
/** Returns a read-only view of the given {@code array}. */
public static <K, V> Map<K, V> wrap(List<Object> array) {
if (array.isEmpty()) {
return Collections.emptyMap();
}

View File

@ -6,8 +6,10 @@
package io.opentelemetry.api.trace;
import com.google.auto.value.AutoValue;
import io.opentelemetry.api.internal.ReadOnlyArrayMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
@ -46,6 +48,12 @@ abstract class ArrayBasedTraceState implements TraceState {
}
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Map<String, String> asMap() {
return ReadOnlyArrayMap.wrap((List) getEntries());
}
abstract List<String> getEntries();
@Override

View File

@ -5,6 +5,7 @@
package io.opentelemetry.api.trace;
import java.util.Map;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
@ -69,6 +70,9 @@ public interface TraceState {
/** Iterates over all the key-value entries contained in this {@link TraceState}. */
void forEach(BiConsumer<String, String> consumer);
/** Returns a read-only view of this {@link TraceState} as a {@link Map}. */
Map<String, String> asMap();
/**
* Returns a {@code Builder} based on this {@code TraceState}.
*

View File

@ -64,6 +64,17 @@ class TraceStateTest {
.containsExactly(entry(SECOND_KEY, SECOND_VALUE), entry(FIRST_KEY, FIRST_VALUE));
}
@Test
void asMap() {
assertThat(firstTraceState.asMap()).containsExactly(entry(FIRST_KEY, FIRST_VALUE));
assertThat(secondTraceState.asMap()).containsExactly(entry(SECOND_KEY, SECOND_VALUE));
// Reverse order of input.
assertThat(multiValueTraceState.asMap())
.containsExactly(entry(SECOND_KEY, SECOND_VALUE), entry(FIRST_KEY, FIRST_VALUE));
}
@Test
void disallowsNullKey() {
assertThat(EMPTY.toBuilder().set(null, FIRST_VALUE).build()).isEqualTo(EMPTY);