Skip to content

Commit

Permalink
Ensure BasicDBObject equals/hashCode works with UUID values (#688)
Browse files Browse the repository at this point in the history
  • Loading branch information
jyemin committed Mar 19, 2021
1 parent 33d6017 commit c5886fb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
11 changes: 9 additions & 2 deletions driver-core/src/main/com/mongodb/BasicDBObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@
import org.bson.BsonBinaryWriter;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWrapper;
import org.bson.UuidRepresentation;
import org.bson.codecs.Decoder;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.Encoder;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.bson.internal.CodecRegistryHelper;
import org.bson.io.BasicOutputBuffer;
import org.bson.io.OutputBuffer;
import org.bson.json.JsonMode;
Expand Down Expand Up @@ -220,10 +222,15 @@ public int hashCode() {
return Arrays.hashCode(toBson(canonicalizeBSONObject(this)));
}

/**
* Convert the object to its BSON representation, using the {@code STANDARD} representation for UUID. This is safe to do in the context
* of this class because currently this method is only used for equality and hash code, and is not passed to any other parts of the
* library.
*/
private static byte[] toBson(final DBObject dbObject) {
OutputBuffer outputBuffer = new BasicOutputBuffer();
DBObjectCodec.getDefaultRegistry().get(DBObject.class).encode(new BsonBinaryWriter(outputBuffer), dbObject,
EncoderContext.builder().build());
CodecRegistryHelper.createRegistry(DBObjectCodec.getDefaultRegistry(), UuidRepresentation.STANDARD)
.get(DBObject.class).encode(new BsonBinaryWriter(outputBuffer), dbObject, EncoderContext.builder().build());
return outputBuffer.toByteArray();
}

Expand Down
10 changes: 10 additions & 0 deletions driver-core/src/test/unit/com/mongodb/BasicDBObjectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.not;
Expand Down Expand Up @@ -218,6 +219,15 @@ public void testEqualsAndHashCode() {
assertEquality(new BasicDBObject("a", first), new BasicBSONObject("a", third));
}

@Test
public void testUuid() {
UUID uuid = UUID.randomUUID();
BasicDBObject dbo1 = new BasicDBObject("_id", uuid);
BasicDBObject dbo2 = new BasicDBObject("_id", uuid);

assertEquality(dbo1, dbo2);
}

void assertEquality(final BSONObject x, final BSONObject y) {
assertEquals(x, y);
assertEquals(y, x);
Expand Down

0 comments on commit c5886fb

Please sign in to comment.