/** * {@link ByteKey} implements {@link Comparable Comparable<ByteKey>} by comparing the * arrays in lexicographic order. The smallest {@link ByteKey} is a zero-length array; the * successor to a key is the same key with an additional 0 byte appended; and keys have unbounded * size. */ @Override public int compareTo(@Nonnull ByteKey other) { checkNotNull(other, "other"); ByteIterator thisIt = value.iterator(); ByteIterator otherIt = other.value.iterator(); while (thisIt.hasNext() && otherIt.hasNext()) { // (byte & 0xff) converts [-128,127] bytes to [0,255] ints. int cmp = (thisIt.nextByte() & 0xff) - (otherIt.nextByte() & 0xff); if (cmp != 0) { return cmp; } } // If we get here, the prefix of both arrays is equal up to the shorter array. The array with // more bytes is larger. return value.size() - other.value.size(); }
@Override public String toString() { char[] encoded = new char[2 * value.size() + 2]; encoded[0] = '['; int cnt = 1; ByteIterator iterator = value.iterator(); while (iterator.hasNext()) { byte b = iterator.nextByte(); encoded[cnt] = HEX[(b & 0xF0) >>> 4]; ++cnt; encoded[cnt] = HEX[b & 0xF]; ++cnt; } encoded[cnt] = ']'; return new String(encoded); }
int compare(ByteString a, ByteString b) { ByteIterator itA = a.iterator(); ByteIterator itB = b.iterator(); while (itA.hasNext()) { if (!itB.hasNext()) { return -1; } int bA = itA.nextByte() & 0xff; int bB = itB.nextByte() & 0xff; int c = Integer.compare(bA, bB); if (c != 0) { return c; } } if (itB.hasNext()) { return 1; } return 0; }
public static String toHex(ByteString key) { StringBuilder sb = new StringBuilder(); ByteIterator iterator = key.iterator(); while (iterator.hasNext()) { int v = iterator.nextByte() & 0xff; sb.append(HEX[v >> 4]); sb.append(HEX[v & 0xf]); } return sb.toString(); }