diff src/com/tmate/hgkit/ll/Nodeid.java @ 24:d4fdd1845b3f

Nodeid with array of exactly 20 bytes
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Thu, 06 Jan 2011 04:42:15 +0100
parents 603806cd2dc6
children b2251b7a9823
line wrap: on
line diff
--- a/src/com/tmate/hgkit/ll/Nodeid.java	Thu Jan 06 03:30:43 2011 +0100
+++ b/src/com/tmate/hgkit/ll/Nodeid.java	Thu Jan 06 04:42:15 2011 +0100
@@ -3,6 +3,8 @@
  */
 package com.tmate.hgkit.ll;
 
+import java.util.Arrays;
+
 
 
 /**
@@ -13,40 +15,41 @@
  * @author artem
  *
  */
-public final class Nodeid implements Comparable<Nodeid> {
+public final class Nodeid {
 	
 	public static int NULLREV = -1;
 	private final byte[] binaryData; 
 
+	/**
+	 * @param binaryRepresentation - byte[20], kept by reference. Use {@link #clone()} if original array may get changed. 
+	 */
 	public Nodeid(byte[] binaryRepresentation) {
 		// 5 int fields => 32 bytes
 		// byte[20] => 48 bytes
+		if (binaryRepresentation == null || binaryRepresentation.length != 20) {
+			throw new IllegalArgumentException();
+		}
 		this.binaryData = binaryRepresentation;
 	}
 
-	// instead of hashCode/equals
-	public int compareTo(Nodeid o) {
-		return equals(this.binaryData, o.binaryData) ? 0 : -1;
+	@Override
+	public int hashCode() {
+		// TODO consider own impl, especially if byte[] get replaced with 5 ints
+		return Arrays.hashCode(binaryData);
+	}
+	
+	@Override
+	public boolean equals(Object o) {
+		if (o instanceof Nodeid) {
+			return Arrays.equals(this.binaryData, ((Nodeid) o).binaryData);
+		}
+		return false;
 	}
 
 	public boolean equalsTo(byte[] buf) {
-		return equals(this.binaryData, buf);
+		return Arrays.equals(this.binaryData, buf);
 	}
 	
-	private static boolean equals(byte[] a1, byte[] a2) {
-		if (a1 == null || a1.length < 20 || a2 == null || a2.length < 20) {
-			throw new IllegalArgumentException();
-		}
-		// assume significant bits are at the end of the array
-		final int s1 = a1.length - 20, s2 = a2.length - 20;
-		for (int i = 0; i < 20; i++) {
-			if (a1[s1+i] != a2[s2+i]) {
-				return false;
-			}
-		}
-		return true;
-	}
-
 	@Override
 	public String toString() {
 		return new DigestHelper().toHexString(binaryData, 0, binaryData.length);
@@ -54,8 +57,10 @@
 	
 	// binascii.unhexlify()
 	public static Nodeid fromAscii(byte[] asciiRepresentation, int offset, int length) {
-		assert length % 2 == 0; // Python's binascii.hexlify convert each byte into 2 digits
-		byte[] data = new byte[length >>> 1]; // XXX use known size instead? nodeid is always 20 bytes
+		if (length != 40) {
+			throw new IllegalArgumentException();
+		}
+		byte[] data = new byte[20];
 		for (int i = 0, j = offset; i < data.length; i++) {
 			int hiNibble = Character.digit(asciiRepresentation[j++], 16);
 			int lowNibble = Character.digit(asciiRepresentation[j++], 16);