Skip to content

Commit bdf721a

Browse files
author
Jon Hoffman
committed
Fix for BasicBSONObject equals method
very large Long values were being converted to doubles for comparison and incorrectly considered equals
1 parent da03eef commit bdf721a

2 files changed

Lines changed: 36 additions & 4 deletions

File tree

src/main/org/bson/BasicBSONObject.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,9 +333,16 @@ public boolean equals( Object o ){
333333
return false;
334334
}
335335
else if ( a instanceof Number && b instanceof Number ){
336-
if ( ((Number)a).doubleValue() !=
337-
((Number)b).doubleValue() )
336+
Number aNumber = (Number) a;
337+
Number bNumber = (Number) b;
338+
if (aNumber instanceof Double || bNumber instanceof Double
339+
|| aNumber instanceof Float || bNumber instanceof Float) {
340+
if (aNumber.doubleValue() != bNumber.doubleValue()) {
341+
return false;
342+
}
343+
} else if (aNumber.longValue() != bNumber.longValue()) {
338344
return false;
345+
}
339346
}
340347
else if ( a instanceof Pattern && b instanceof Pattern ){
341348
Pattern p1 = (Pattern) a;

src/test/org/bson/BSONTest.java

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,14 @@
1818

1919
package org.bson;
2020

21+
import static org.testng.Assert.assertNotEquals;
22+
2123
import java.io.ByteArrayInputStream;
2224
import java.io.IOException;
23-
import java.util.*;
24-
25+
import java.util.ArrayList;
26+
import java.util.Date;
27+
import java.util.List;
28+
import java.util.Vector;
2529
import org.bson.io.BasicOutputBuffer;
2630
import org.bson.io.OutputBuffer;
2731
import org.bson.types.CodeWScope;
@@ -251,6 +255,27 @@ public void testCustomDecoders()
251255
assertFalse( BSON.getDecodingHooks( Date.class ).contains( tf ) );
252256

253257
}
258+
259+
@Test
260+
public void testEquals() {
261+
assertNotEquals(new BasicBSONObject("a", 1111111111111111111L), new BasicBSONObject("a", 1111111111111111112L),
262+
"longs should not be equal");
263+
264+
assertNotEquals(new BasicBSONObject("a", 100.1D), new BasicBSONObject("a", 100.2D),
265+
"doubles should not be equal");
266+
267+
assertNotEquals(new BasicBSONObject("a", 100.1F), new BasicBSONObject("a", 100.2F),
268+
"floats should not be equal");
269+
270+
assertEquals(new BasicBSONObject("a", 100.1D), new BasicBSONObject("a", 100.1D),
271+
"doubles should be equal");
272+
273+
assertEquals(new BasicBSONObject("a", 100.1F), new BasicBSONObject("a", 100.1F),
274+
"floats should be equal");
275+
276+
assertEquals(new BasicBSONObject("a", 100), new BasicBSONObject("a", 100L),
277+
"int and long should be equal");
278+
}
254279

255280
private class TestDate {
256281
final int year;

0 commit comments

Comments
 (0)