Minor work on ByteArray and associated tests

This commit is contained in:
catbref
2020-12-08 15:19:12 +00:00
parent 8c9cf4a02d
commit e8fc91fd34
2 changed files with 93 additions and 23 deletions

View File

@@ -1,6 +1,7 @@
package org.qortal.utils;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Objects;
public class ByteArray implements Comparable<ByteArray> {
@@ -8,7 +9,11 @@ public class ByteArray implements Comparable<ByteArray> {
public final byte[] value;
public ByteArray(byte[] value) {
this.value = value;
this.value = Objects.requireNonNull(value);
}
public static ByteArray of(byte[] value) {
return new ByteArray(value);
}
@Override
@@ -16,36 +21,39 @@ public class ByteArray implements Comparable<ByteArray> {
if (this == other)
return true;
if (other instanceof ByteArray)
return this.compareTo((ByteArray) other) == 0;
if (other instanceof byte[])
return this.compareTo((byte[]) other) == 0;
return Arrays.equals(this.value, (byte[]) other);
if (other instanceof ByteArray)
return Arrays.equals(this.value, ((ByteArray) other).value);
return false;
}
@Override
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
byte[] val = value;
int h = this.hash;
byte[] val = this.value;
if (h == 0 && val.length > 0) {
h = 1;
for (int i = 0; i < val.length; ++i)
h = 31 * h + val[i];
hash = h;
this.hash = h;
}
return h;
}
@Override
public int compareTo(ByteArray other) {
return this.compareTo(other.value);
Objects.requireNonNull(other);
return this.compareToPrimitive(other.value);
}
public int compareTo(byte[] otherValue) {
byte[] val = value;
public int compareToPrimitive(byte[] otherValue) {
byte[] val = this.value;
if (val.length < otherValue.length)
return -1;
@@ -66,6 +74,16 @@ public class ByteArray implements Comparable<ByteArray> {
}
public String toString() {
return String.format("%x", new BigInteger(1, this.value));
StringBuilder sb = new StringBuilder(3 + this.value.length * 6);
sb.append("[");
if (this.value.length > 0)
sb.append(this.value[0]);
for (int i = 1; i < this.value.length; ++i)
sb.append(", ").append(this.value[i]);
return sb.append("]").toString();
}
}