Mercurial > hg4j
comparison src/org/tmatesoft/hg/core/Nodeid.java @ 261:436bb5f65ce1
Avoid redundant calls to library when converting a char to hex digit
| author | Artem Tikhomirov <tikhomirov.artem@gmail.com> |
|---|---|
| date | Wed, 17 Aug 2011 20:30:06 +0200 |
| parents | 4b661efb9374 |
| children | 3dcd3dd90c77 |
comparison
equal
deleted
inserted
replaced
| 260:61cb6724ff36 | 261:436bb5f65ce1 |
|---|---|
| 163 throw new IllegalArgumentException(); | 163 throw new IllegalArgumentException(); |
| 164 } | 164 } |
| 165 // XXX is better impl for String possible? | 165 // XXX is better impl for String possible? |
| 166 return fromAscii(asciiRepresentation.getBytes(), 0, 40); | 166 return fromAscii(asciiRepresentation.getBytes(), 0, 40); |
| 167 } | 167 } |
| 168 | 168 |
| 169 /** | 169 /** |
| 170 * Parse encoded representation. Similar to {@link #fromAscii(String)}. | 170 * Parse encoded representation. Similar to {@link #fromAscii(String)}. |
| 171 */ | 171 */ |
| 172 public static Nodeid fromAscii(byte[] asciiRepresentation, int offset, int length) { | 172 public static Nodeid fromAscii(byte[] asciiRepresentation, int offset, int length) { |
| 173 if (length != 40) { | 173 if (length != 40) { |
| 174 throw new IllegalArgumentException(); | 174 throw new IllegalArgumentException(); |
| 175 } | 175 } |
| 176 byte[] data = new byte[20]; | 176 byte[] data = new byte[20]; |
| 177 boolean zeroBytes = true; | 177 boolean zeroBytes = true; |
| 178 for (int i = 0, j = offset; i < data.length; i++) { | 178 for (int i = 0, j = offset; i < data.length; i++) { |
| 179 int hiNibble = Character.digit(asciiRepresentation[j++], 16); | 179 int b = asciiRepresentation[j++] & 0xCF; // -0x30 to get decimal digit out from their char, and to uppercase if a letter |
| 180 int lowNibble = Character.digit(asciiRepresentation[j++], 16); | 180 int hiNibble = b > 64 ? b - 55 : b; |
| 181 byte b = (byte) (((hiNibble << 4) | lowNibble) & 0xFF); | 181 b = asciiRepresentation[j++] & 0xCF; |
| 182 data[i] = b; | 182 int lowNibble = b > 64 ? b - 55 : b; |
| 183 if (hiNibble >= 16 || lowNibble >= 16) { | |
| 184 throw new IllegalArgumentException(String.format("Characters '%c%c' (%1$d and %2$d) at index %d are not valid hex digits", asciiRepresentation[j-2], asciiRepresentation[j-1], j-2)); | |
| 185 } | |
| 186 data[i] = (byte) (((hiNibble << 4) | lowNibble) & 0xFF); | |
| 183 zeroBytes = zeroBytes && b == 0; | 187 zeroBytes = zeroBytes && b == 0; |
| 184 } | 188 } |
| 185 if (zeroBytes) { | 189 if (zeroBytes) { |
| 186 return NULL; | 190 return NULL; |
| 187 } | 191 } |
