core: add discard method for Attributes
diff --git a/api/src/main/java/io/grpc/Attributes.java b/api/src/main/java/io/grpc/Attributes.java
index 7ae4612..9063e6e 100644
--- a/api/src/main/java/io/grpc/Attributes.java
+++ b/api/src/main/java/io/grpc/Attributes.java
@@ -232,6 +232,26 @@
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;
diff --git a/api/src/test/java/io/grpc/AttributesTest.java b/api/src/test/java/io/grpc/AttributesTest.java
index 33f43f8..3d981e0 100644
--- a/api/src/test/java/io/grpc/AttributesTest.java
+++ b/api/src/test/java/io/grpc/AttributesTest.java
@@ -19,6 +19,7 @@
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 @@
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);
+ }
}