Add a new ObjectCodec to support ImmutableBiMap instances.

PiperOrigin-RevId: 244868926
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableBiMapCodec.java b/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableBiMapCodec.java
new file mode 100644
index 0000000..26feda2
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableBiMapCodec.java
@@ -0,0 +1,76 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.skyframe.serialization;
+
+import com.google.common.collect.ImmutableBiMap;
+import com.google.common.collect.ImmutableMap;
+import com.google.protobuf.CodedInputStream;
+import com.google.protobuf.CodedOutputStream;
+import java.io.IOException;
+
+/**
+ * Encodes an {@link ImmutableBiMap}. The iteration order of the deserialized map is the same as the
+ * original map's.
+ *
+ * <p>We handle {@link ImmutableBiMap} by treating it as an {@link ImmutableMap} and calling the
+ * proper conversion method ({@link ImmutableBiMap#copyOf}) when deserializing. This is valid
+ * because every {@link ImmutableBiMap} is also an {@link ImmutableMap}.
+ *
+ * <p>Any {@link SerializationException} or {@link IOException} that arises while serializing or
+ * deserializing a map entry's value (not its key) will be wrapped in a new {@link
+ * SerializationException} using {@link SerializationException#propagate}. (Note that this preserves
+ * the type of {@link SerializationException.NoCodecException} exceptions.) The message will include
+ * the {@code toString()} of the entry's key. For errors that occur while serializing, it will also
+ * include the class name of the entry's value. Errors that occur while serializing an entry key are
+ * not affected.
+ */
+class ImmutableBiMapCodec<K, V> implements ObjectCodec<ImmutableBiMap<K, V>> {
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public Class<ImmutableBiMap<K, V>> getEncodedClass() {
+    return (Class<ImmutableBiMap<K, V>>) ((Class<?>) ImmutableBiMap.class);
+  }
+
+  @Override
+  public void serialize(
+      SerializationContext context, ImmutableBiMap<K, V> map, CodedOutputStream codedOut)
+      throws SerializationException, IOException {
+
+    codedOut.writeInt32NoTag(map.size());
+    ImmutableMapCodec.serializeEntries(context, map.entrySet(), codedOut);
+  }
+
+  @Override
+  public ImmutableBiMap<K, V> deserialize(DeserializationContext context, CodedInputStream codedIn)
+      throws SerializationException, IOException {
+
+    int length = codedIn.readInt32();
+    if (length < 0) {
+      throw new SerializationException("Expected non-negative length: " + length);
+    }
+
+    ImmutableBiMap.Builder<K, V> builder =
+        ImmutableMapCodec.deserializeEntries(
+            ImmutableBiMap.builderWithExpectedSize(length), length, context, codedIn);
+
+    try {
+      return builder.build();
+    } catch (IllegalArgumentException e) {
+      throw new SerializationException(
+          "Duplicate keys during ImmutableBiMapCodec deserialization", e);
+    }
+  }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableMapCodec.java b/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableMapCodec.java
index 2c1e11c..07e337f 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableMapCodec.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableMapCodec.java
@@ -66,7 +66,15 @@
           comparator.equals(Ordering.natural()) || comparator.equals(Comparator.naturalOrder());
     }
     codedOut.writeBoolNoTag(serializeAsSortedMap);
-    for (Map.Entry<?, ?> entry : map.entrySet()) {
+    serializeEntries(context, map.entrySet(), codedOut);
+  }
+
+  static <K, V> void serializeEntries(
+      SerializationContext context,
+      Iterable<? extends Map.Entry<K, V>> entrySet,
+      CodedOutputStream codedOut)
+      throws IOException, SerializationException {
+    for (Map.Entry<?, ?> entry : entrySet) {
       context.serialize(entry.getKey(), codedOut);
       try {
         context.serialize(entry.getValue(), codedOut);
@@ -87,18 +95,24 @@
     if (length < 0) {
       throw new SerializationException("Expected non-negative length: " + length);
     }
+    ImmutableMap.Builder<?, V> builder;
     if (codedIn.readBool()) {
-      return buildMap(ImmutableSortedMap.naturalOrder(), length, context, codedIn);
+      builder = deserializeEntries(ImmutableSortedMap.naturalOrder(), length, context, codedIn);
     } else {
-      return buildMap(ImmutableMap.builderWithExpectedSize(length), length, context, codedIn);
+      builder =
+          deserializeEntries(
+              ImmutableMap.builderWithExpectedSize(length), length, context, codedIn);
+    }
+    try {
+      return builder.build();
+    } catch (IllegalArgumentException e) {
+      throw new SerializationException(
+          "Duplicate keys during ImmutableMapCodec deserialization", e);
     }
   }
 
-  private static <K, V> ImmutableMap<K, V> buildMap(
-      ImmutableMap.Builder<K, V> builder,
-      int length,
-      DeserializationContext context,
-      CodedInputStream codedIn)
+  static <K, V, M extends ImmutableMap.Builder<K, V>> M deserializeEntries(
+      M builder, int length, DeserializationContext context, CodedInputStream codedIn)
       throws IOException, SerializationException {
     for (int i = 0; i < length; i++) {
       K key = context.deserialize(codedIn);
@@ -111,11 +125,6 @@
       }
       builder.put(key, value);
     }
-    try {
-      return builder.build();
-    } catch (IllegalArgumentException e) {
-      throw new SerializationException(
-          "Duplicate keys during ImmutableMapCodec deserialization", e);
-    }
+    return builder;
   }
 }
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableBiMapCodecTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableBiMapCodecTest.java
new file mode 100644
index 0000000..099993a
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/serialization/ImmutableBiMapCodecTest.java
@@ -0,0 +1,119 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.skyframe.serialization;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableBiMap;
+import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationTester;
+import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationTester.VerificationFunction;
+import com.google.devtools.build.lib.skyframe.serialization.testutils.TestUtils;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.CodedInputStream;
+import com.google.protobuf.CodedOutputStream;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link ImmutableBiMapCodec}. */
+@RunWith(JUnit4.class)
+public class ImmutableBiMapCodecTest {
+  @Test
+  public void smoke() throws Exception {
+    new SerializationTester(
+            ImmutableBiMap.of(),
+            ImmutableBiMap.of("A", "//foo:A"),
+            ImmutableBiMap.of("B", "//foo:B"))
+        // Check for order.
+        .setVerificationFunction(
+            (VerificationFunction<ImmutableBiMap<?, ?>>)
+                (deserialized, subject) -> {
+                  assertThat(deserialized).isEqualTo(subject);
+                  assertThat(deserialized).containsExactlyEntriesIn(subject).inOrder();
+                })
+        .runTests();
+  }
+
+  @Test
+  public void serializingErrorIncludesKeyStringAndValueClass() {
+    SerializationException expected =
+        assertThrows(
+            SerializationException.class,
+            () ->
+                TestUtils.toBytesMemoized(
+                    ImmutableBiMap.of("a", new Dummy()),
+                    AutoRegistry.get()
+                        .getBuilder()
+                        .add(new DummyThrowingCodec(/*throwsOnSerialization=*/ true))
+                        .build()));
+    assertThat(expected)
+        .hasMessageThat()
+        .containsMatch("Exception while serializing value of type .*\\$Dummy for key 'a'");
+  }
+
+  @Test
+  public void deserializingErrorIncludesKeyString() throws Exception {
+    ObjectCodecRegistry registry =
+        AutoRegistry.get()
+            .getBuilder()
+            .add(new DummyThrowingCodec(/*throwsOnSerialization=*/ false))
+            .build();
+    ByteString data =
+        TestUtils.toBytes(
+            new SerializationContext(registry, ImmutableBiMap.of()),
+            ImmutableBiMap.of("a", new Dummy()));
+    SerializationException expected =
+        assertThrows(
+            SerializationException.class,
+            () ->
+                TestUtils.fromBytes(
+                    new DeserializationContext(registry, ImmutableBiMap.of()), data));
+    assertThat(expected)
+        .hasMessageThat()
+        .contains("Exception while deserializing value for key 'a'");
+  }
+
+  private static class Dummy {}
+
+  private static class DummyThrowingCodec implements ObjectCodec<Dummy> {
+    private final boolean throwsOnSerialization;
+
+    private DummyThrowingCodec(boolean throwsOnSerialization) {
+      this.throwsOnSerialization = throwsOnSerialization;
+    }
+
+    @Override
+    public Class<Dummy> getEncodedClass() {
+      return Dummy.class;
+    }
+
+    @Override
+    public void serialize(SerializationContext context, Dummy value, CodedOutputStream codedOut)
+        throws SerializationException {
+      if (throwsOnSerialization) {
+        throw new SerializationException("Expected failure");
+      }
+    }
+
+    @Override
+    public Dummy deserialize(DeserializationContext context, CodedInputStream codedIn)
+        throws SerializationException {
+      Preconditions.checkState(!throwsOnSerialization);
+      throw new SerializationException("Expected failure");
+    }
+  }
+}