mirror of https://github.com/grpc/grpc-java.git
core: add discard method for Attributes
This commit is contained in:
parent
4dcbe56354
commit
cdeafcf6e0
|
|
@ -232,6 +232,26 @@ public final class Attributes {
|
|||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the key and associated value from the attribtues.
|
||||
*
|
||||
* @since 1.22.0
|
||||
* @param key The key to remove
|
||||
* @return this
|
||||
*/
|
||||
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/5777")
|
||||
public <T> Builder discard(Key<T> key) {
|
||||
if (base.data.containsKey(key)) {
|
||||
Map<Key<?>, Object> newBaseData = new IdentityHashMap<>(base.data);
|
||||
newBaseData.remove(key);
|
||||
base = new Attributes(newBaseData);
|
||||
}
|
||||
if (newdata != null) {
|
||||
newdata.remove(key);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public <T> Builder setAll(Attributes other) {
|
||||
data(other.data.size()).putAll(other.data);
|
||||
return this;
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ package io.grpc;
|
|||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
||||
import org.junit.Test;
|
||||
|
|
@ -91,4 +92,40 @@ public class AttributesTest {
|
|||
assertEquals(attr1, attr2);
|
||||
assertEquals(attr1.hashCode(), attr2.hashCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discard_baseAttributes() {
|
||||
Attributes attrs = Attributes.newBuilder().set(YOLO_KEY, "value").build();
|
||||
|
||||
Attributes newAttrs = attrs.toBuilder().discard(YOLO_KEY).build();
|
||||
assertNull(newAttrs.get(YOLO_KEY));
|
||||
assertThat(newAttrs.keysForTest()).doesNotContain(YOLO_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discard_noBase() {
|
||||
Attributes.Builder attrs = Attributes.newBuilder().set(YOLO_KEY, "value");
|
||||
|
||||
Attributes newAttrs = attrs.discard(YOLO_KEY).build();
|
||||
assertNull(newAttrs.get(YOLO_KEY));
|
||||
assertThat(newAttrs.keysForTest()).doesNotContain(YOLO_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discard_baseAttributesAndBuilder() {
|
||||
Attributes attrs = Attributes.newBuilder().set(YOLO_KEY, "value").build();
|
||||
|
||||
Attributes.Builder attrsBuilder = attrs.toBuilder().set(YOLO_KEY, "other value");
|
||||
Attributes newAttrs = attrsBuilder.discard(YOLO_KEY).build();
|
||||
assertNull(newAttrs.get(YOLO_KEY));
|
||||
assertThat(newAttrs.keysForTest()).doesNotContain(YOLO_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discard_empty() {
|
||||
Attributes newAttrs = Attributes.EMPTY.toBuilder().discard(YOLO_KEY).build();
|
||||
|
||||
assertNull(newAttrs.get(YOLO_KEY));
|
||||
assertThat(newAttrs.keysForTest()).doesNotContain(YOLO_KEY);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue