Improve binToNibble performance

This commit is contained in:
nicksavers 2014-08-03 20:51:08 +02:00
parent 59d8dfbed0
commit a5802b9398
1 changed files with 14 additions and 14 deletions

View File

@ -1,13 +1,14 @@
package org.ethereum.util; package org.ethereum.util;
import java.io.ByteArrayOutputStream;
import static java.util.Arrays.copyOfRange;
import static java.util.Arrays.copyOf; import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static org.ethereum.util.ByteUtil.appendByte; import static org.ethereum.util.ByteUtil.appendByte;
import static org.spongycastle.util.Arrays.concatenate; import static org.spongycastle.util.Arrays.concatenate;
import static org.spongycastle.util.encoders.Hex.toHexString; import static org.spongycastle.util.encoders.Hex.encode;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
/** /**
* Compact encoding of hex sequence with optional terminator * Compact encoding of hex sequence with optional terminator
@ -85,11 +86,11 @@ public class CompactEncoder {
*/ */
public static byte[] unpackToNibbles(byte[] str) { public static byte[] unpackToNibbles(byte[] str) {
byte[] base = binToNibbles(str); byte[] base = binToNibbles(str);
base = copyOf(base, base.length-1); base = copyOf(base, base.length - 1);
if (base[0] >= 2) { if (base[0] >= 2) {
base = appendByte(base, TERMINATOR); base = appendByte(base, TERMINATOR);
} }
if (base[0]%2 == 1) { if (base[0] % 2 == 1) {
base = copyOfRange(base, 1, base.length); base = copyOfRange(base, 1, base.length);
} else { } else {
base = copyOfRange(base, 2, base.length); base = copyOfRange(base, 2, base.length);
@ -101,15 +102,14 @@ public class CompactEncoder {
* Transforms a binary array to hexadecimal format + terminator * Transforms a binary array to hexadecimal format + terminator
* *
* @return array with each individual nibble adding a terminator at the end * @return array with each individual nibble adding a terminator at the end
*/ */
public static byte[] binToNibbles(byte[] str) { public static byte[] binToNibbles(byte[] str) {
byte[] hexSlice = new byte[0]; byte[] hexEncoded = encode(str);
String hexEncoded = toHexString(str); ByteBuffer slice = ByteBuffer.allocate(hexEncoded.length + 1);
for (char value : hexEncoded.toCharArray()) { for (byte b : hexEncoded) {
hexSlice = appendByte(hexSlice, (byte) hexBase.indexOf(value)); slice.put((byte)hexBase.indexOf(b));
} }
hexSlice = appendByte(hexSlice, TERMINATOR); slice.put(TERMINATOR);
return slice.array();
return hexSlice;
} }
} }