File tree 2 files changed +23
-4
lines changed
2 files changed +23
-4
lines changed Original file line number Diff line number Diff line change @@ -415,17 +415,30 @@ private Object readResolve() {
415
415
}
416
416
417
417
private static byte [] parseHexString (final String s ) {
418
- if (!isValid (s )) {
419
- throw new IllegalArgumentException ("invalid hexadecimal representation of an ObjectId: [" + s + "]" );
420
- }
418
+ notNull ("hexString" , s );
419
+ isTrueArgument ("hexString has 24 characters" , s .length () == 24 );
421
420
422
421
byte [] b = new byte [OBJECT_ID_LENGTH ];
423
422
for (int i = 0 ; i < b .length ; i ++) {
424
- b [i ] = (byte ) Integer .parseInt (s .substring (i * 2 , i * 2 + 2 ), 16 );
423
+ int pos = i << 1 ;
424
+ char c1 = s .charAt (pos );
425
+ char c2 = s .charAt (pos + 1 );
426
+ b [i ] = (byte ) ((hexCharToInt (c1 ) << 4 ) + hexCharToInt (c2 ));
425
427
}
426
428
return b ;
427
429
}
428
430
431
+ private static int hexCharToInt (final char c ) {
432
+ if (c >= '0' && c <= '9' ) {
433
+ return c - 48 ;
434
+ } else if (c >= 'a' && c <= 'f' ) {
435
+ return c - 87 ;
436
+ } else if (c >= 'A' && c <= 'F' ) {
437
+ return c - 55 ;
438
+ }
439
+ throw new IllegalArgumentException ("invalid hexadecimal character: [" + c + "]" );
440
+ }
441
+
429
442
private static int dateToTimestampSeconds (final Date time ) {
430
443
return (int ) (time .getTime () / 1000 );
431
444
}
Original file line number Diff line number Diff line change 27
27
import java .text .ParseException ;
28
28
import java .text .SimpleDateFormat ;
29
29
import java .util .Date ;
30
+ import java .util .Locale ;
30
31
import java .util .Random ;
31
32
32
33
import static org .junit .Assert .assertArrayEquals ;
33
34
import static org .junit .Assert .assertEquals ;
35
+ import static org .junit .Assert .assertThrows ;
34
36
import static org .junit .Assert .assertTrue ;
35
37
import static org .junit .Assert .fail ;
36
38
@@ -142,6 +144,10 @@ public void testDateCons() {
142
144
public void testHexStringConstructor () {
143
145
ObjectId id = new ObjectId ();
144
146
assertEquals (id , new ObjectId (id .toHexString ()));
147
+ assertEquals (id , new ObjectId (id .toHexString ().toUpperCase (Locale .US )));
148
+ assertThrows (IllegalArgumentException .class , () -> new ObjectId ((String ) null ));
149
+ assertThrows (IllegalArgumentException .class , () -> new ObjectId (id .toHexString ().substring (0 , 23 )));
150
+ assertThrows (IllegalArgumentException .class , () -> new ObjectId (id .toHexString ().substring (0 , 23 ) + '%' ));
145
151
}
146
152
147
153
@ Test
You can’t perform that action at this time.
0 commit comments