Skip to content

Commit

Permalink
Improve performance of ObjectId#parseHexString (mongodb#1034)
Browse files Browse the repository at this point in the history
JAVA-4816

Co-authored-by: Jeff Yemin <jeff.yemin@mongodb.com>
  • Loading branch information
eonwhite and jyemin authored Dec 13, 2022
1 parent dee0358 commit cbb8d04
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
21 changes: 17 additions & 4 deletions bson/src/main/org/bson/types/ObjectId.java
Original file line number Diff line number Diff line change
Expand Up @@ -415,17 +415,30 @@ private Object readResolve() {
}

private static byte[] parseHexString(final String s) {
if (!isValid(s)) {
throw new IllegalArgumentException("invalid hexadecimal representation of an ObjectId: [" + s + "]");
}
notNull("hexString", s);
isTrueArgument("hexString has 24 characters", s.length() == 24);

byte[] b = new byte[OBJECT_ID_LENGTH];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
int pos = i << 1;
char c1 = s.charAt(pos);
char c2 = s.charAt(pos + 1);
b[i] = (byte) ((hexCharToInt(c1) << 4) + hexCharToInt(c2));
}
return b;
}

private static int hexCharToInt(final char c) {
if (c >= '0' && c <= '9') {
return c - 48;
} else if (c >= 'a' && c <= 'f') {
return c - 87;
} else if (c >= 'A' && c <= 'F') {
return c - 55;
}
throw new IllegalArgumentException("invalid hexadecimal character: [" + c + "]");
}

private static int dateToTimestampSeconds(final Date time) {
return (int) (time.getTime() / 1000);
}
Expand Down
6 changes: 6 additions & 0 deletions bson/src/test/unit/org/bson/types/ObjectIdTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

Expand Down Expand Up @@ -142,6 +144,10 @@ public void testDateCons() {
public void testHexStringConstructor() {
ObjectId id = new ObjectId();
assertEquals(id, new ObjectId(id.toHexString()));
assertEquals(id, new ObjectId(id.toHexString().toUpperCase(Locale.US)));
assertThrows(IllegalArgumentException.class, () -> new ObjectId((String) null));
assertThrows(IllegalArgumentException.class, () -> new ObjectId(id.toHexString().substring(0, 23)));
assertThrows(IllegalArgumentException.class, () -> new ObjectId(id.toHexString().substring(0, 23) + '%'));
}

@Test
Expand Down

0 comments on commit cbb8d04

Please sign in to comment.