diff src/org/tmatesoft/hg/internal/DigestHelper.java @ 266:0a2f445de774

Improve manifest parsing: reduce number of arrays instantiated for Nodeid
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Fri, 19 Aug 2011 04:59:32 +0200
parents a3a2e5deb320
children 981f9f50bb6c
line wrap: on
line diff
--- a/src/org/tmatesoft/hg/internal/DigestHelper.java	Fri Aug 19 04:02:48 2011 +0200
+++ b/src/org/tmatesoft/hg/internal/DigestHelper.java	Fri Aug 19 04:59:32 2011 +0200
@@ -122,4 +122,24 @@
 		}
 		return new String(result);
 	}
+
+	public static boolean ascii2bin(byte[] ascii, int offset, int len, byte[] binary) {
+		assert len % 2 == 0;
+		assert binary.length >= len >>> 1;
+
+		boolean zeroBytes = true;
+		for (int i = 0, j = offset; i < len >>> 1; i++) {
+			int b = ascii[j++] & 0xCF; // -0x30 to get decimal digit out from their char, and to uppercase if a letter 
+			int hiNibble = b > 64 ? b - 55 : b;
+			b = ascii[j++] & 0xCF;
+			int lowNibble = b > 64 ? b - 55 : b;
+			if (hiNibble >= 16 || lowNibble >= 16) {
+				throw new IllegalArgumentException(String.format("Characters '%c%c' (%1$d and %2$d) at index %d are not valid hex digits", ascii[j-2], ascii[j-1], j-2));
+			}
+			b = (((hiNibble << 4) | lowNibble) & 0xFF);
+			binary[i] = (byte) b;
+			zeroBytes = zeroBytes && b == 0;
+		}
+		return zeroBytes;
+	}
 }