Skip to content

Commit 3a4b24e

Browse files
committed
Fix regression in ObjectId.compareTo
Now checks the byte array unsigned int values JAVA-1785
1 parent 938ff60 commit 3a4b24e

File tree

2 files changed

+9
-15
lines changed

2 files changed

+9
-15
lines changed

bson/src/main/org/bson/types/ObjectId.java

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -405,22 +405,14 @@ public int compareTo(final ObjectId other) {
405405
throw new NullPointerException();
406406
}
407407

408-
int x = timestamp - other.timestamp;
409-
if (x != 0) {
410-
return x;
411-
}
412-
413-
x = machineIdentifier - other.machineIdentifier;
414-
if (x != 0) {
415-
return x;
416-
}
417-
418-
x = processIdentifier - other.processIdentifier;
419-
if (x != 0) {
420-
return x;
408+
byte[] byteArray = toByteArray();
409+
byte[] otherByteArray = other.toByteArray();
410+
for (int i = 0; i < 12; i++) {
411+
if (byteArray[i] != otherByteArray[i]) {
412+
return Integer.compare(byteArray[i] & 0xff, otherByteArray[i] & 0xff);
413+
}
421414
}
422-
423-
return counter - other.counter;
415+
return 0;
424416
}
425417

426418
@Override

bson/src/test/unit/org/bson/types/ObjectIdTest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,11 +113,13 @@ public void testCompareTo() {
113113
assertEquals(-1, new ObjectId(0, 0, (short) 0, 0).compareTo(new ObjectId(1, 0, (short) 0, 0)));
114114
assertEquals(-1, new ObjectId(0, 0, (short) 0, 0).compareTo(new ObjectId(0, 1, (short) 0, 0)));
115115
assertEquals(-1, new ObjectId(0, 0, (short) 0, 0).compareTo(new ObjectId(0, 0, (short) 1, 0)));
116+
assertEquals(-1, new ObjectId(0, 0, (short) 1, 0).compareTo(new ObjectId(0, 0, (short) -1, 0)));
116117
assertEquals(-1, new ObjectId(0, 0, (short) 0, 0).compareTo(new ObjectId(0, 0, (short) 0, 1)));
117118
assertEquals(0, new ObjectId(0, 0, (short) 0, 0).compareTo(new ObjectId(0, 0, (short) 0, 0)));
118119
assertEquals(1, new ObjectId(1, 0, (short) 0, 0).compareTo(new ObjectId(0, 0, (short) 0, 0)));
119120
assertEquals(1, new ObjectId(0, 1, (short) 0, 0).compareTo(new ObjectId(0, 0, (short) 0, 0)));
120121
assertEquals(1, new ObjectId(0, 0, (short) 1, 0).compareTo(new ObjectId(0, 0, (short) 0, 0)));
122+
assertEquals(1, new ObjectId(0, 0, (short) -1, 0).compareTo(new ObjectId(0, 0, (short) 1, 0)));
121123
assertEquals(1, new ObjectId(0, 0, (short) 0, 1).compareTo(new ObjectId(0, 0, (short) 0, 0)));
122124
}
123125

0 commit comments

Comments
 (0)