001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.util; 019 020import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkArgument; 021import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkNotNull; 022import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkPositionIndex; 023 024import java.io.DataInput; 025import java.io.DataOutput; 026import java.io.IOException; 027import java.io.UnsupportedEncodingException; 028import java.math.BigDecimal; 029import java.math.BigInteger; 030import java.nio.ByteBuffer; 031import java.nio.charset.StandardCharsets; 032import java.security.SecureRandom; 033import java.util.ArrayList; 034import java.util.Arrays; 035import java.util.Collection; 036import java.util.Collections; 037import java.util.Comparator; 038import java.util.Iterator; 039import java.util.List; 040import java.util.Random; 041import org.apache.hadoop.hbase.Cell; 042import org.apache.hadoop.hbase.CellComparator; 043import org.apache.hadoop.hbase.unsafe.HBasePlatformDependent; 044import org.apache.hadoop.io.RawComparator; 045import org.apache.hadoop.io.WritableComparator; 046import org.apache.hadoop.io.WritableUtils; 047import org.apache.yetus.audience.InterfaceAudience; 048import org.slf4j.Logger; 049import org.slf4j.LoggerFactory; 050 051import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils; 052 053/** 054 * Utility class that handles byte arrays, conversions to/from other types, comparisons, hash code 055 * generation, manufacturing keys for HashMaps or HashSets, and can be used as key in maps or trees. 056 */ 057@InterfaceAudience.Public 058@edu.umd.cs.findbugs.annotations.SuppressWarnings( 059 value = "EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", 060 justification = "It has been like this forever") 061@SuppressWarnings("MixedMutabilityReturnType") 062public class Bytes implements Comparable<Bytes> { 063 064 // Using the charset canonical name for String/byte[] conversions is much 065 // more efficient due to use of cached encoders/decoders. 066 private static final String UTF8_CSN = StandardCharsets.UTF_8.name(); 067 068 // HConstants.EMPTY_BYTE_ARRAY should be updated if this changed 069 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; 070 071 private static final Logger LOG = LoggerFactory.getLogger(Bytes.class); 072 073 /** 074 * Size of boolean in bytes 075 */ 076 public static final int SIZEOF_BOOLEAN = Byte.SIZE / Byte.SIZE; 077 078 /** 079 * Size of byte in bytes 080 */ 081 public static final int SIZEOF_BYTE = SIZEOF_BOOLEAN; 082 083 /** 084 * Size of char in bytes 085 */ 086 public static final int SIZEOF_CHAR = Character.SIZE / Byte.SIZE; 087 088 /** 089 * Size of double in bytes 090 */ 091 public static final int SIZEOF_DOUBLE = Double.SIZE / Byte.SIZE; 092 093 /** 094 * Size of float in bytes 095 */ 096 public static final int SIZEOF_FLOAT = Float.SIZE / Byte.SIZE; 097 098 /** 099 * Size of int in bytes 100 */ 101 public static final int SIZEOF_INT = Integer.SIZE / Byte.SIZE; 102 103 /** 104 * Size of long in bytes 105 */ 106 public static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE; 107 108 /** 109 * Size of short in bytes 110 */ 111 public static final int SIZEOF_SHORT = Short.SIZE / Byte.SIZE; 112 113 /** 114 * Mask to apply to a long to reveal the lower int only. Use like this: int i = 115 * (int)(0xFFFFFFFF00000000L ^ some_long_value); 116 */ 117 public static final long MASK_FOR_LOWER_INT_IN_LONG = 0xFFFFFFFF00000000L; 118 119 /** 120 * Estimate of size cost to pay beyond payload in jvm for instance of byte []. Estimate based on 121 * study of jhat and jprofiler numbers. 122 */ 123 // JHat says BU is 56 bytes. 124 // SizeOf which uses java.lang.instrument says 24 bytes. (3 longs?) 125 public static final int ESTIMATED_HEAP_TAX = 16; 126 127 static final boolean UNSAFE_UNALIGNED = HBasePlatformDependent.unaligned(); 128 129 /** 130 * Returns length of the byte array, returning 0 if the array is null. Useful for calculating 131 * sizes. 132 * @param b byte array, which can be null 133 * @return 0 if b is null, otherwise returns length 134 */ 135 final public static int len(byte[] b) { 136 return b == null ? 0 : b.length; 137 } 138 139 private byte[] bytes; 140 private int offset; 141 private int length; 142 143 /** 144 * Create a zero-size sequence. 145 */ 146 public Bytes() { 147 super(); 148 } 149 150 /** 151 * Create a Bytes using the byte array as the initial value. 152 * @param bytes This array becomes the backing storage for the object. 153 */ 154 public Bytes(byte[] bytes) { 155 this(bytes, 0, bytes.length); 156 } 157 158 /** 159 * Set the new Bytes to the contents of the passed <code>ibw</code>. 160 * @param ibw the value to set this Bytes to. 161 */ 162 public Bytes(final Bytes ibw) { 163 this(ibw.get(), ibw.getOffset(), ibw.getLength()); 164 } 165 166 /** 167 * Set the value to a given byte range 168 * @param bytes the new byte range to set to 169 * @param offset the offset in newData to start at 170 * @param length the number of bytes in the range 171 */ 172 public Bytes(final byte[] bytes, final int offset, final int length) { 173 this.bytes = bytes; 174 this.offset = offset; 175 this.length = length; 176 } 177 178 /** 179 * Get the data from the Bytes. 180 * @return The data is only valid between offset and offset+length. 181 */ 182 public byte[] get() { 183 if (this.bytes == null) { 184 throw new IllegalStateException( 185 "Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); 186 } 187 return this.bytes; 188 } 189 190 /** Use passed bytes as backing array for this instance. */ 191 public void set(final byte[] b) { 192 set(b, 0, b.length); 193 } 194 195 /** Use passed bytes as backing array for this instance. */ 196 public void set(final byte[] b, final int offset, final int length) { 197 this.bytes = b; 198 this.offset = offset; 199 this.length = length; 200 } 201 202 /** Returns the number of valid bytes in the buffer */ 203 public int getLength() { 204 if (this.bytes == null) { 205 throw new IllegalStateException( 206 "Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); 207 } 208 return this.length; 209 } 210 211 /** Return the offset into the buffer. */ 212 public int getOffset() { 213 return this.offset; 214 } 215 216 @Override 217 public int hashCode() { 218 return Bytes.hashCode(bytes, offset, length); 219 } 220 221 /** 222 * Define the sort order of the Bytes. 223 * @param that The other bytes writable 224 * @return Positive if left is bigger than right, 0 if they are equal, and negative if left is 225 * smaller than right. 226 */ 227 @Override 228 public int compareTo(Bytes that) { 229 return BYTES_RAWCOMPARATOR.compare(this.bytes, this.offset, this.length, that.bytes, 230 that.offset, that.length); 231 } 232 233 /** 234 * Compares the bytes in this object to the specified byte array 235 * @return Positive if left is bigger than right, 0 if they are equal, and negative if left is 236 * smaller than right. 237 */ 238 public int compareTo(final byte[] that) { 239 return BYTES_RAWCOMPARATOR.compare(this.bytes, this.offset, this.length, that, 0, that.length); 240 } 241 242 @Override 243 public boolean equals(Object right_obj) { 244 if (right_obj instanceof byte[]) { 245 return compareTo((byte[]) right_obj) == 0; 246 } 247 if (right_obj instanceof Bytes) { 248 return compareTo((Bytes) right_obj) == 0; 249 } 250 return false; 251 } 252 253 @Override 254 public String toString() { 255 return Bytes.toString(bytes, offset, length); 256 } 257 258 /** 259 * Convert a list of byte[] to an array 260 * @param array List of byte []. 261 * @return Array of byte []. 262 */ 263 public static byte[][] toArray(final List<byte[]> array) { 264 // List#toArray doesn't work on lists of byte []. 265 byte[][] results = new byte[array.size()][]; 266 for (int i = 0; i < array.size(); i++) { 267 results[i] = array.get(i); 268 } 269 return results; 270 } 271 272 /** Returns a copy of the bytes referred to by this writable */ 273 public byte[] copyBytes() { 274 return Arrays.copyOfRange(bytes, offset, offset + length); 275 } 276 277 /** Byte array comparator class. */ 278 @InterfaceAudience.Public 279 public static class ByteArrayComparator implements RawComparator<byte[]> { 280 281 public ByteArrayComparator() { 282 super(); 283 } 284 285 @Override 286 public int compare(byte[] left, byte[] right) { 287 return compareTo(left, right); 288 } 289 290 @Override 291 public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { 292 return LexicographicalComparerHolder.BEST_COMPARER.compareTo(b1, s1, l1, b2, s2, l2); 293 } 294 } 295 296 /** 297 * A {@link ByteArrayComparator} that treats the empty array as the largest value. This is useful 298 * for comparing row end keys for regions. 299 */ 300 // TODO: unfortunately, HBase uses byte[0] as both start and end keys for region 301 // boundaries. Thus semantically, we should treat empty byte array as the smallest value 302 // while comparing row keys, start keys etc; but as the largest value for comparing 303 // region boundaries for endKeys. 304 @InterfaceAudience.Public 305 public static class RowEndKeyComparator extends ByteArrayComparator { 306 @Override 307 public int compare(byte[] left, byte[] right) { 308 return compare(left, 0, left.length, right, 0, right.length); 309 } 310 311 @Override 312 public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { 313 if (b1 == b2 && s1 == s2 && l1 == l2) { 314 return 0; 315 } 316 if (l1 == 0) { 317 return l2; // 0 or positive 318 } 319 if (l2 == 0) { 320 return -1; 321 } 322 return super.compare(b1, s1, l1, b2, s2, l2); 323 } 324 } 325 326 /** Pass this to TreeMaps where byte [] are keys. */ 327 public final static Comparator<byte[]> BYTES_COMPARATOR = new ByteArrayComparator(); 328 329 /** Use comparing byte arrays, byte-by-byte */ 330 public final static RawComparator<byte[]> BYTES_RAWCOMPARATOR = new ByteArrayComparator(); 331 332 /** 333 * Read byte-array written with a WritableableUtils.vint prefix. 334 * @param in Input to read from. 335 * @return byte array read off <code>in</code> 336 * @throws IOException e 337 */ 338 public static byte[] readByteArray(final DataInput in) throws IOException { 339 int len = WritableUtils.readVInt(in); 340 if (len < 0) { 341 throw new NegativeArraySizeException(Integer.toString(len)); 342 } 343 byte[] result = new byte[len]; 344 in.readFully(result, 0, len); 345 return result; 346 } 347 348 /** 349 * Read byte-array written with a WritableableUtils.vint prefix. IOException is converted to a 350 * RuntimeException. 351 * @param in Input to read from. 352 * @return byte array read off <code>in</code> 353 */ 354 public static byte[] readByteArrayThrowsRuntime(final DataInput in) { 355 try { 356 return readByteArray(in); 357 } catch (Exception e) { 358 throw new RuntimeException(e); 359 } 360 } 361 362 /** 363 * Write byte-array with a WritableableUtils.vint prefix. 364 * @param out output stream to be written to 365 * @param b array to write 366 * @throws IOException e 367 */ 368 public static void writeByteArray(final DataOutput out, final byte[] b) throws IOException { 369 if (b == null) { 370 WritableUtils.writeVInt(out, 0); 371 } else { 372 writeByteArray(out, b, 0, b.length); 373 } 374 } 375 376 /** 377 * Write byte-array to out with a vint length prefix. 378 * @param out output stream 379 * @param b array 380 * @param offset offset into array 381 * @param length length past offset 382 * @throws IOException e 383 */ 384 public static void writeByteArray(final DataOutput out, final byte[] b, final int offset, 385 final int length) throws IOException { 386 WritableUtils.writeVInt(out, length); 387 out.write(b, offset, length); 388 } 389 390 /** 391 * Write byte-array from src to tgt with a vint length prefix. 392 * @param tgt target array 393 * @param tgtOffset offset into target array 394 * @param src source array 395 * @param srcOffset source offset 396 * @param srcLength source length 397 * @return New offset in src array. 398 */ 399 public static int writeByteArray(final byte[] tgt, final int tgtOffset, final byte[] src, 400 final int srcOffset, final int srcLength) { 401 byte[] vint = vintToBytes(srcLength); 402 System.arraycopy(vint, 0, tgt, tgtOffset, vint.length); 403 int offset = tgtOffset + vint.length; 404 System.arraycopy(src, srcOffset, tgt, offset, srcLength); 405 return offset + srcLength; 406 } 407 408 /** 409 * Put bytes at the specified byte array position. 410 * @param tgtBytes the byte array 411 * @param tgtOffset position in the array 412 * @param srcBytes array to write out 413 * @param srcOffset source offset 414 * @param srcLength source length 415 * @return incremented offset 416 */ 417 public static int putBytes(byte[] tgtBytes, int tgtOffset, byte[] srcBytes, int srcOffset, 418 int srcLength) { 419 System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength); 420 return tgtOffset + srcLength; 421 } 422 423 /** 424 * Write a single byte out to the specified byte array position. 425 * @param bytes the byte array 426 * @param offset position in the array 427 * @param b byte to write out 428 * @return incremented offset 429 */ 430 public static int putByte(byte[] bytes, int offset, byte b) { 431 bytes[offset] = b; 432 return offset + 1; 433 } 434 435 /** 436 * Add the whole content of the ByteBuffer to the bytes arrays. The ByteBuffer is modified. 437 * @param bytes the byte array 438 * @param offset position in the array 439 * @param buf ByteBuffer to write out 440 * @return incremented offset 441 */ 442 public static int putByteBuffer(byte[] bytes, int offset, ByteBuffer buf) { 443 int len = buf.remaining(); 444 buf.get(bytes, offset, len); 445 return offset + len; 446 } 447 448 /** 449 * Returns a new byte array, copied from the given {@code buf}, from the index 0 (inclusive) to 450 * the limit (exclusive), regardless of the current position. The position and the other index 451 * parameters are not changed. 452 * @param buf a byte buffer 453 * @return the byte array 454 * @see #getBytes(ByteBuffer) 455 */ 456 public static byte[] toBytes(ByteBuffer buf) { 457 ByteBuffer dup = buf.duplicate(); 458 dup.position(0); 459 return readBytes(dup); 460 } 461 462 private static byte[] readBytes(ByteBuffer buf) { 463 byte[] result = new byte[buf.remaining()]; 464 buf.get(result); 465 return result; 466 } 467 468 /** 469 * Convert a byte[] into a string. Charset is assumed to be UTF-8. 470 * @param b Presumed UTF-8 encoded byte array. 471 * @return String made from <code>b</code> 472 */ 473 public static String toString(final byte[] b) { 474 if (b == null) { 475 return null; 476 } 477 return toString(b, 0, b.length); 478 } 479 480 /** 481 * Joins two byte arrays together using a separator. 482 * @param b1 The first byte array. 483 * @param sep The separator to use. 484 * @param b2 The second byte array. 485 */ 486 public static String toString(final byte[] b1, String sep, final byte[] b2) { 487 return toString(b1, 0, b1.length) + sep + toString(b2, 0, b2.length); 488 } 489 490 /** 491 * This method will convert utf8 encoded bytes into a string. If the given byte array is null, 492 * this method will return null. 493 * @param b Presumed UTF-8 encoded byte array. 494 * @param off offset into array 495 * @return String made from <code>b</code> or null 496 */ 497 public static String toString(final byte[] b, int off) { 498 if (b == null) { 499 return null; 500 } 501 int len = b.length - off; 502 if (len <= 0) { 503 return ""; 504 } 505 try { 506 return new String(b, off, len, UTF8_CSN); 507 } catch (UnsupportedEncodingException e) { 508 // should never happen! 509 throw new IllegalArgumentException("UTF8 encoding is not supported", e); 510 } 511 } 512 513 /** 514 * This method will convert utf8 encoded bytes into a string. If the given byte array is null, 515 * this method will return null. 516 * @param b Presumed UTF-8 encoded byte array. 517 * @param off offset into array 518 * @param len length of utf-8 sequence 519 * @return String made from <code>b</code> or null 520 */ 521 public static String toString(final byte[] b, int off, int len) { 522 if (b == null) { 523 return null; 524 } 525 if (len == 0) { 526 return ""; 527 } 528 try { 529 return new String(b, off, len, UTF8_CSN); 530 } catch (UnsupportedEncodingException e) { 531 // should never happen! 532 throw new IllegalArgumentException("UTF8 encoding is not supported", e); 533 } 534 } 535 536 /** 537 * Write a printable representation of a byte array. 538 * @param b byte array 539 * @see #toStringBinary(byte[], int, int) 540 */ 541 public static String toStringBinary(final byte[] b) { 542 if (b == null) return "null"; 543 return toStringBinary(b, 0, b.length); 544 } 545 546 /** 547 * Converts the given byte buffer to a printable representation, from the index 0 (inclusive) to 548 * the limit (exclusive), regardless of the current position. The position and the other index 549 * parameters are not changed. 550 * @param buf a byte buffer 551 * @return a string representation of the buffer's binary contents 552 * @see #toBytes(ByteBuffer) 553 * @see #getBytes(ByteBuffer) 554 */ 555 public static String toStringBinary(ByteBuffer buf) { 556 if (buf == null) return "null"; 557 if (buf.hasArray()) { 558 return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit()); 559 } 560 return toStringBinary(toBytes(buf)); 561 } 562 563 private static final char[] HEX_CHARS_UPPER = 564 { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 565 566 /** 567 * Write a printable representation of a byte array. Non-printable characters are hex escaped in 568 * the format \\x%02X, eg: \x00 \x05 etc 569 * @param b array to write out 570 * @param off offset to start at 571 * @param len length to write 572 * @return string output 573 */ 574 public static String toStringBinary(final byte[] b, int off, int len) { 575 StringBuilder result = new StringBuilder(); 576 // Just in case we are passed a 'len' that is > buffer length... 577 if (off >= b.length) return result.toString(); 578 if (off + len > b.length) len = b.length - off; 579 for (int i = off; i < off + len; ++i) { 580 int ch = b[i] & 0xFF; 581 if (ch >= ' ' && ch <= '~' && ch != '\\') { 582 result.append((char) ch); 583 } else { 584 result.append("\\x"); 585 result.append(HEX_CHARS_UPPER[ch / 0x10]); 586 result.append(HEX_CHARS_UPPER[ch % 0x10]); 587 } 588 } 589 return result.toString(); 590 } 591 592 private static boolean isHexDigit(char c) { 593 return (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9'); 594 } 595 596 /** 597 * Takes a ASCII digit in the range A-F0-9 and returns the corresponding integer/ordinal value. 598 * @param ch The hex digit. 599 * @return The converted hex value as a byte. 600 */ 601 public static byte toBinaryFromHex(byte ch) { 602 if (ch >= 'A' && ch <= 'F') return (byte) ((byte) 10 + (byte) (ch - 'A')); 603 // else 604 return (byte) (ch - '0'); 605 } 606 607 public static byte[] toBytesBinary(String in) { 608 // this may be bigger than we need, but let's be safe. 609 byte[] b = new byte[in.length()]; 610 int size = 0; 611 for (int i = 0; i < in.length(); ++i) { 612 char ch = in.charAt(i); 613 if (ch == '\\' && in.length() > i + 1 && in.charAt(i + 1) == 'x') { 614 // ok, take next 2 hex digits. 615 char hd1 = in.charAt(i + 2); 616 char hd2 = in.charAt(i + 3); 617 618 // they need to be A-F0-9: 619 if (!isHexDigit(hd1) || !isHexDigit(hd2)) { 620 // bogus escape code, ignore: 621 continue; 622 } 623 // turn hex ASCII digit -> number 624 byte d = (byte) ((toBinaryFromHex((byte) hd1) << 4) + toBinaryFromHex((byte) hd2)); 625 626 b[size++] = d; 627 i += 3; // skip 3 628 } else { 629 b[size++] = (byte) ch; 630 } 631 } 632 // resize: 633 byte[] b2 = new byte[size]; 634 System.arraycopy(b, 0, b2, 0, size); 635 return b2; 636 } 637 638 /** 639 * Converts a string to a UTF-8 byte array. 640 * @param s string 641 * @return the byte array 642 */ 643 public static byte[] toBytes(String s) { 644 try { 645 return s.getBytes(UTF8_CSN); 646 } catch (UnsupportedEncodingException e) { 647 // should never happen! 648 throw new IllegalArgumentException("UTF8 decoding is not supported", e); 649 } 650 } 651 652 /** 653 * Convert a boolean to a byte array. True becomes -1 and false becomes 0. 654 * @param b value 655 * @return <code>b</code> encoded in a byte array. 656 */ 657 public static byte[] toBytes(final boolean b) { 658 return new byte[] { b ? (byte) -1 : (byte) 0 }; 659 } 660 661 /** 662 * Reverses {@link #toBytes(boolean)} 663 * @param b array 664 * @return True or false. 665 */ 666 public static boolean toBoolean(final byte[] b) { 667 if (b.length != 1) { 668 throw new IllegalArgumentException("Array has wrong size: " + b.length); 669 } 670 return b[0] != (byte) 0; 671 } 672 673 /** 674 * Convert a long value to a byte array using big-endian. 675 * @param val value to convert 676 * @return the byte array 677 */ 678 public static byte[] toBytes(long val) { 679 byte[] b = new byte[8]; 680 for (int i = 7; i > 0; i--) { 681 b[i] = (byte) val; 682 val >>>= 8; 683 } 684 b[0] = (byte) val; 685 return b; 686 } 687 688 /** 689 * Converts a byte array to a long value. Reverses {@link #toBytes(long)} 690 * @param bytes array 691 * @return the long value 692 */ 693 public static long toLong(byte[] bytes) { 694 return toLong(bytes, 0, SIZEOF_LONG); 695 } 696 697 /** 698 * Converts a byte array to a long value. Assumes there will be {@link #SIZEOF_LONG} bytes 699 * available. 700 * @param bytes bytes 701 * @param offset offset 702 * @return the long value 703 */ 704 public static long toLong(byte[] bytes, int offset) { 705 return toLong(bytes, offset, SIZEOF_LONG); 706 } 707 708 /** 709 * Converts a byte array to a long value. 710 * @param bytes array of bytes 711 * @param offset offset into array 712 * @param length length of data (must be {@link #SIZEOF_LONG}) 713 * @return the long value 714 * @throws IllegalArgumentException if length is not {@link #SIZEOF_LONG} or if there's not enough 715 * room in the array at the offset indicated. 716 */ 717 public static long toLong(byte[] bytes, int offset, final int length) { 718 if (length != SIZEOF_LONG || offset + length > bytes.length) { 719 throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG); 720 } 721 return ConverterHolder.BEST_CONVERTER.toLong(bytes, offset, length); 722 } 723 724 private static IllegalArgumentException explainWrongLengthOrOffset(final byte[] bytes, 725 final int offset, final int length, final int expectedLength) { 726 String reason; 727 if (length != expectedLength) { 728 reason = "Wrong length: " + length + ", expected " + expectedLength; 729 } else { 730 reason = "offset (" + offset + ") + length (" + length + ") exceed the" 731 + " capacity of the array: " + bytes.length; 732 } 733 return new IllegalArgumentException(reason); 734 } 735 736 /** 737 * Put a long value out to the specified byte array position. 738 * @param bytes the byte array 739 * @param offset position in the array 740 * @param val long to write out 741 * @return incremented offset 742 * @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset 743 * specified. 744 */ 745 public static int putLong(byte[] bytes, int offset, long val) { 746 if (bytes.length - offset < SIZEOF_LONG) { 747 throw new IllegalArgumentException("Not enough room to put a long at" + " offset " + offset 748 + " in a " + bytes.length + " byte array"); 749 } 750 return ConverterHolder.BEST_CONVERTER.putLong(bytes, offset, val); 751 } 752 753 /** 754 * Put a float value out to the specified byte array position. Presumes float encoded as IEEE 754 755 * floating-point "single format" 756 * @param bytes byte array 757 * @return Float made from passed byte array. 758 */ 759 public static float toFloat(byte[] bytes) { 760 return toFloat(bytes, 0); 761 } 762 763 /** 764 * Put a float value out to the specified byte array position. Presumes float encoded as IEEE 754 765 * floating-point "single format" 766 * @param bytes array to convert 767 * @param offset offset into array 768 * @return Float made from passed byte array. 769 */ 770 public static float toFloat(byte[] bytes, int offset) { 771 return Float.intBitsToFloat(toInt(bytes, offset, SIZEOF_INT)); 772 } 773 774 /** 775 * Put a float value out to the specified byte array position. 776 * @param bytes byte array 777 * @param offset offset to write to 778 * @param f float value 779 * @return New offset in <code>bytes</code> 780 */ 781 public static int putFloat(byte[] bytes, int offset, float f) { 782 return putInt(bytes, offset, Float.floatToRawIntBits(f)); 783 } 784 785 /** Return the float represented as byte[] */ 786 public static byte[] toBytes(final float f) { 787 // Encode it as int 788 return Bytes.toBytes(Float.floatToRawIntBits(f)); 789 } 790 791 /** Return double made from passed bytes. */ 792 public static double toDouble(final byte[] bytes) { 793 return toDouble(bytes, 0); 794 } 795 796 /** Return double made from passed bytes. */ 797 public static double toDouble(final byte[] bytes, final int offset) { 798 return Double.longBitsToDouble(toLong(bytes, offset, SIZEOF_LONG)); 799 } 800 801 /** 802 * Put a double value out to the specified byte array position as the IEEE 754 double format. 803 * @param bytes byte array 804 * @param offset offset to write to 805 * @param d value 806 * @return New offset into array <code>bytes</code> 807 */ 808 public static int putDouble(byte[] bytes, int offset, double d) { 809 return putLong(bytes, offset, Double.doubleToLongBits(d)); 810 } 811 812 /** 813 * Serialize a double as the IEEE 754 double format output. The resultant array will be 8 bytes 814 * long. 815 * @param d value 816 * @return the double represented as byte [] 817 */ 818 public static byte[] toBytes(final double d) { 819 // Encode it as a long 820 return Bytes.toBytes(Double.doubleToRawLongBits(d)); 821 } 822 823 /** 824 * Convert an int value to a byte array. Big-endian. Same as what DataOutputStream.writeInt does. 825 * @param val value 826 * @return the byte array 827 */ 828 public static byte[] toBytes(int val) { 829 byte[] b = new byte[4]; 830 for (int i = 3; i > 0; i--) { 831 b[i] = (byte) val; 832 val >>>= 8; 833 } 834 b[0] = (byte) val; 835 return b; 836 } 837 838 /** 839 * Converts a byte array to an int value 840 * @param bytes byte array 841 * @return the int value 842 */ 843 public static int toInt(byte[] bytes) { 844 return toInt(bytes, 0, SIZEOF_INT); 845 } 846 847 /** 848 * Converts a byte array to an int value 849 * @param bytes byte array 850 * @param offset offset into array 851 * @return the int value 852 */ 853 public static int toInt(byte[] bytes, int offset) { 854 return toInt(bytes, offset, SIZEOF_INT); 855 } 856 857 /** 858 * Converts a byte array to an int value 859 * @param bytes byte array 860 * @param offset offset into array 861 * @param length length of int (has to be {@link #SIZEOF_INT}) 862 * @return the int value 863 * @throws IllegalArgumentException if length is not {@link #SIZEOF_INT} or if there's not enough 864 * room in the array at the offset indicated. 865 */ 866 public static int toInt(byte[] bytes, int offset, final int length) { 867 if (length != SIZEOF_INT || offset + length > bytes.length) { 868 throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_INT); 869 } 870 return ConverterHolder.BEST_CONVERTER.toInt(bytes, offset, length); 871 } 872 873 /** 874 * Converts a byte array to an int value 875 * @param bytes byte array 876 * @param offset offset into array 877 * @param length how many bytes should be considered for creating int 878 * @return the int value 879 * @throws IllegalArgumentException if there's not enough room in the array at the offset 880 * indicated. 881 */ 882 public static int readAsInt(byte[] bytes, int offset, final int length) { 883 if (offset + length > bytes.length) { 884 throw new IllegalArgumentException("offset (" + offset + ") + length (" + length 885 + ") exceed the" + " capacity of the array: " + bytes.length); 886 } 887 int n = 0; 888 for (int i = offset; i < (offset + length); i++) { 889 n <<= 8; 890 n ^= bytes[i] & 0xFF; 891 } 892 return n; 893 } 894 895 /** 896 * Put an int value out to the specified byte array position. 897 * @param bytes the byte array 898 * @param offset position in the array 899 * @param val int to write out 900 * @return incremented offset 901 * @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset 902 * specified. 903 */ 904 public static int putInt(byte[] bytes, int offset, int val) { 905 if (bytes.length - offset < SIZEOF_INT) { 906 throw new IllegalArgumentException("Not enough room to put an int at" + " offset " + offset 907 + " in a " + bytes.length + " byte array"); 908 } 909 return ConverterHolder.BEST_CONVERTER.putInt(bytes, offset, val); 910 } 911 912 /** 913 * Convert a short value to a byte array of {@link #SIZEOF_SHORT} bytes long. 914 * @param val value 915 * @return the byte array 916 */ 917 public static byte[] toBytes(short val) { 918 byte[] b = new byte[SIZEOF_SHORT]; 919 b[1] = (byte) val; 920 val >>= 8; 921 b[0] = (byte) val; 922 return b; 923 } 924 925 /** 926 * Converts a byte array to a short value 927 * @param bytes byte array 928 * @return the short value 929 */ 930 public static short toShort(byte[] bytes) { 931 return toShort(bytes, 0, SIZEOF_SHORT); 932 } 933 934 /** 935 * Converts a byte array to a short value 936 * @param bytes byte array 937 * @param offset offset into array 938 * @return the short value 939 */ 940 public static short toShort(byte[] bytes, int offset) { 941 return toShort(bytes, offset, SIZEOF_SHORT); 942 } 943 944 /** 945 * Converts a byte array to a short value 946 * @param bytes byte array 947 * @param offset offset into array 948 * @param length length, has to be {@link #SIZEOF_SHORT} 949 * @return the short value 950 * @throws IllegalArgumentException if length is not {@link #SIZEOF_SHORT} or if there's not 951 * enough room in the array at the offset indicated. 952 */ 953 public static short toShort(byte[] bytes, int offset, final int length) { 954 if (length != SIZEOF_SHORT || offset + length > bytes.length) { 955 throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_SHORT); 956 } 957 return ConverterHolder.BEST_CONVERTER.toShort(bytes, offset, length); 958 } 959 960 /** 961 * Returns a new byte array, copied from the given {@code buf}, from the position (inclusive) to 962 * the limit (exclusive). The position and the other index parameters are not changed. 963 * @param buf a byte buffer 964 * @return the byte array 965 * @see #toBytes(ByteBuffer) 966 */ 967 public static byte[] getBytes(ByteBuffer buf) { 968 return readBytes(buf.duplicate()); 969 } 970 971 /** 972 * Put a short value out to the specified byte array position. 973 * @param bytes the byte array 974 * @param offset position in the array 975 * @param val short to write out 976 * @return incremented offset 977 * @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset 978 * specified. 979 */ 980 public static int putShort(byte[] bytes, int offset, short val) { 981 if (bytes.length - offset < SIZEOF_SHORT) { 982 throw new IllegalArgumentException("Not enough room to put a short at" + " offset " + offset 983 + " in a " + bytes.length + " byte array"); 984 } 985 return ConverterHolder.BEST_CONVERTER.putShort(bytes, offset, val); 986 } 987 988 /** 989 * Put an int value as short out to the specified byte array position. Only the lower 2 bytes of 990 * the short will be put into the array. The caller of the API need to make sure they will not 991 * loose the value by doing so. This is useful to store an unsigned short which is represented as 992 * int in other parts. 993 * @param bytes the byte array 994 * @param offset position in the array 995 * @param val value to write out 996 * @return incremented offset 997 * @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset 998 * specified. 999 */ 1000 public static int putAsShort(byte[] bytes, int offset, int val) { 1001 if (bytes.length - offset < SIZEOF_SHORT) { 1002 throw new IllegalArgumentException("Not enough room to put a short at" + " offset " + offset 1003 + " in a " + bytes.length + " byte array"); 1004 } 1005 bytes[offset + 1] = (byte) val; 1006 val >>= 8; 1007 bytes[offset] = (byte) val; 1008 return offset + SIZEOF_SHORT; 1009 } 1010 1011 /** Convert a BigDecimal value to a byte array */ 1012 public static byte[] toBytes(BigDecimal val) { 1013 byte[] valueBytes = val.unscaledValue().toByteArray(); 1014 byte[] result = new byte[valueBytes.length + SIZEOF_INT]; 1015 int offset = putInt(result, 0, val.scale()); 1016 putBytes(result, offset, valueBytes, 0, valueBytes.length); 1017 return result; 1018 } 1019 1020 /** Converts a byte array to a BigDecimal */ 1021 public static BigDecimal toBigDecimal(byte[] bytes) { 1022 return toBigDecimal(bytes, 0, bytes.length); 1023 } 1024 1025 /** Converts a byte array to a BigDecimal value */ 1026 public static BigDecimal toBigDecimal(byte[] bytes, int offset, final int length) { 1027 if (bytes == null || length < SIZEOF_INT + 1 || (offset + length > bytes.length)) { 1028 return null; 1029 } 1030 1031 int scale = toInt(bytes, offset); 1032 byte[] tcBytes = new byte[length - SIZEOF_INT]; 1033 System.arraycopy(bytes, offset + SIZEOF_INT, tcBytes, 0, length - SIZEOF_INT); 1034 return new BigDecimal(new BigInteger(tcBytes), scale); 1035 } 1036 1037 /** 1038 * Put a BigDecimal value out to the specified byte array position. 1039 * @param bytes the byte array 1040 * @param offset position in the array 1041 * @param val BigDecimal to write out 1042 * @return incremented offset 1043 */ 1044 public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) { 1045 if (bytes == null) { 1046 return offset; 1047 } 1048 1049 byte[] valueBytes = val.unscaledValue().toByteArray(); 1050 byte[] result = new byte[valueBytes.length + SIZEOF_INT]; 1051 offset = putInt(result, offset, val.scale()); 1052 return putBytes(result, offset, valueBytes, 0, valueBytes.length); 1053 } 1054 1055 /** 1056 * Encode a long value as a variable length integer. 1057 * @param vint Integer to make a vint of. 1058 * @return Vint as bytes array. 1059 */ 1060 public static byte[] vintToBytes(final long vint) { 1061 long i = vint; 1062 int size = WritableUtils.getVIntSize(i); 1063 byte[] result = new byte[size]; 1064 int offset = 0; 1065 if (i >= -112 && i <= 127) { 1066 result[offset] = (byte) i; 1067 return result; 1068 } 1069 1070 int len = -112; 1071 if (i < 0) { 1072 i ^= -1L; // take one's complement' 1073 len = -120; 1074 } 1075 1076 long tmp = i; 1077 while (tmp != 0) { 1078 tmp = tmp >> 8; 1079 len--; 1080 } 1081 1082 result[offset++] = (byte) len; 1083 1084 len = (len < -120) ? -(len + 120) : -(len + 112); 1085 1086 for (int idx = len; idx != 0; idx--) { 1087 int shiftbits = (idx - 1) * 8; 1088 long mask = 0xFFL << shiftbits; 1089 result[offset++] = (byte) ((i & mask) >> shiftbits); 1090 } 1091 return result; 1092 } 1093 1094 /** 1095 * Reads a zero-compressed encoded long from input buffer and returns it. 1096 * @param buffer buffer to convert 1097 * @return vint bytes as an integer. 1098 */ 1099 public static long bytesToVint(final byte[] buffer) { 1100 int offset = 0; 1101 byte firstByte = buffer[offset++]; 1102 int len = WritableUtils.decodeVIntSize(firstByte); 1103 if (len == 1) { 1104 return firstByte; 1105 } 1106 long i = 0; 1107 for (int idx = 0; idx < len - 1; idx++) { 1108 byte b = buffer[offset++]; 1109 i = i << 8; 1110 i = i | (b & 0xFF); 1111 } 1112 return (WritableUtils.isNegativeVInt(firstByte) ? ~i : i); 1113 } 1114 1115 /** 1116 * Reads a zero-compressed encoded long from input buffer and returns it. 1117 * @param buffer Binary array 1118 * @param offset Offset into array at which vint begins. 1119 * @return deserialized long from buffer. 1120 */ 1121 public static long readAsVLong(final byte[] buffer, final int offset) { 1122 byte firstByte = buffer[offset]; 1123 int len = WritableUtils.decodeVIntSize(firstByte); 1124 if (len == 1) { 1125 return firstByte; 1126 } 1127 long i = 0; 1128 for (int idx = 0; idx < len - 1; idx++) { 1129 byte b = buffer[offset + 1 + idx]; 1130 i = i << 8; 1131 i = i | (b & 0xFF); 1132 } 1133 return (WritableUtils.isNegativeVInt(firstByte) ? ~i : i); 1134 } 1135 1136 /** 1137 * Lexicographically compare two arrays. 1138 * @param left left operand 1139 * @param right right operand 1140 * @return 0 if equal, < 0 if left is less than right, etc. 1141 */ 1142 public static int compareTo(final byte[] left, final byte[] right) { 1143 return LexicographicalComparerHolder.BEST_COMPARER.compareTo(left, 0, 1144 left == null ? 0 : left.length, right, 0, right == null ? 0 : right.length); 1145 } 1146 1147 /** 1148 * Lexicographically compare two arrays. 1149 * @param buffer1 left operand 1150 * @param buffer2 right operand 1151 * @param offset1 Where to start comparing in the left buffer 1152 * @param offset2 Where to start comparing in the right buffer 1153 * @param length1 How much to compare from the left buffer 1154 * @param length2 How much to compare from the right buffer 1155 * @return 0 if equal, < 0 if left is less than right, etc. 1156 */ 1157 public static int compareTo(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, 1158 int length2) { 1159 return LexicographicalComparerHolder.BEST_COMPARER.compareTo(buffer1, offset1, length1, buffer2, 1160 offset2, length2); 1161 } 1162 1163 interface Comparer<T> { 1164 int compareTo(T buffer1, int offset1, int length1, T buffer2, int offset2, int length2); 1165 } 1166 1167 static abstract class Converter { 1168 abstract long toLong(byte[] bytes, int offset, int length); 1169 1170 abstract int putLong(byte[] bytes, int offset, long val); 1171 1172 abstract int toInt(byte[] bytes, int offset, final int length); 1173 1174 abstract int putInt(byte[] bytes, int offset, int val); 1175 1176 abstract short toShort(byte[] bytes, int offset, final int length); 1177 1178 abstract int putShort(byte[] bytes, int offset, short val); 1179 1180 } 1181 1182 static Comparer<byte[]> lexicographicalComparerJavaImpl() { 1183 return LexicographicalComparerHolder.PureJavaComparer.INSTANCE; 1184 } 1185 1186 static class ConverterHolder { 1187 static final String UNSAFE_CONVERTER_NAME = 1188 ConverterHolder.class.getName() + "$UnsafeConverter"; 1189 1190 static final Converter BEST_CONVERTER = getBestConverter(); 1191 1192 /** 1193 * Returns the Unsafe-using Converter, or falls back to the pure-Java implementation if unable 1194 * to do so. 1195 */ 1196 static Converter getBestConverter() { 1197 try { 1198 Class<?> theClass = Class.forName(UNSAFE_CONVERTER_NAME); 1199 1200 // yes, UnsafeComparer does implement Comparer<byte[]> 1201 @SuppressWarnings("unchecked") 1202 Converter converter = (Converter) theClass.getConstructor().newInstance(); 1203 return converter; 1204 } catch (Throwable t) { // ensure we really catch *everything* 1205 return PureJavaConverter.INSTANCE; 1206 } 1207 } 1208 1209 protected static final class PureJavaConverter extends Converter { 1210 static final PureJavaConverter INSTANCE = new PureJavaConverter(); 1211 1212 private PureJavaConverter() { 1213 } 1214 1215 @Override 1216 long toLong(byte[] bytes, int offset, int length) { 1217 long l = 0; 1218 for (int i = offset; i < offset + length; i++) { 1219 l <<= 8; 1220 l ^= bytes[i] & 0xFF; 1221 } 1222 return l; 1223 } 1224 1225 @Override 1226 int putLong(byte[] bytes, int offset, long val) { 1227 for (int i = offset + 7; i > offset; i--) { 1228 bytes[i] = (byte) val; 1229 val >>>= 8; 1230 } 1231 bytes[offset] = (byte) val; 1232 return offset + SIZEOF_LONG; 1233 } 1234 1235 @Override 1236 int toInt(byte[] bytes, int offset, int length) { 1237 int n = 0; 1238 for (int i = offset; i < (offset + length); i++) { 1239 n <<= 8; 1240 n ^= bytes[i] & 0xFF; 1241 } 1242 return n; 1243 } 1244 1245 @Override 1246 int putInt(byte[] bytes, int offset, int val) { 1247 for (int i = offset + 3; i > offset; i--) { 1248 bytes[i] = (byte) val; 1249 val >>>= 8; 1250 } 1251 bytes[offset] = (byte) val; 1252 return offset + SIZEOF_INT; 1253 } 1254 1255 @Override 1256 short toShort(byte[] bytes, int offset, int length) { 1257 short n = 0; 1258 n = (short) ((n ^ bytes[offset]) & 0xFF); 1259 n = (short) (n << 8); 1260 n ^= (short) (bytes[offset + 1] & 0xFF); 1261 return n; 1262 } 1263 1264 @Override 1265 int putShort(byte[] bytes, int offset, short val) { 1266 bytes[offset + 1] = (byte) val; 1267 val >>= 8; 1268 bytes[offset] = (byte) val; 1269 return offset + SIZEOF_SHORT; 1270 } 1271 } 1272 1273 protected static final class UnsafeConverter extends Converter { 1274 1275 public UnsafeConverter() { 1276 } 1277 1278 static { 1279 if (!UNSAFE_UNALIGNED) { 1280 // It doesn't matter what we throw; 1281 // it's swallowed in getBestComparer(). 1282 throw new Error(); 1283 } 1284 1285 // sanity check - this should never fail 1286 if (HBasePlatformDependent.arrayIndexScale(byte[].class) != 1) { 1287 throw new AssertionError(); 1288 } 1289 } 1290 1291 @Override 1292 long toLong(byte[] bytes, int offset, int length) { 1293 return UnsafeAccess.toLong(bytes, offset); 1294 } 1295 1296 @Override 1297 int putLong(byte[] bytes, int offset, long val) { 1298 return UnsafeAccess.putLong(bytes, offset, val); 1299 } 1300 1301 @Override 1302 int toInt(byte[] bytes, int offset, int length) { 1303 return UnsafeAccess.toInt(bytes, offset); 1304 } 1305 1306 @Override 1307 int putInt(byte[] bytes, int offset, int val) { 1308 return UnsafeAccess.putInt(bytes, offset, val); 1309 } 1310 1311 @Override 1312 short toShort(byte[] bytes, int offset, int length) { 1313 return UnsafeAccess.toShort(bytes, offset); 1314 } 1315 1316 @Override 1317 int putShort(byte[] bytes, int offset, short val) { 1318 return UnsafeAccess.putShort(bytes, offset, val); 1319 } 1320 } 1321 } 1322 1323 /** 1324 * Provides a lexicographical comparer implementation; either a Java implementation or a faster 1325 * implementation based on {@code Unsafe}. 1326 * <p> 1327 * Uses reflection to gracefully fall back to the Java implementation if {@code Unsafe} isn't 1328 * available. 1329 */ 1330 static class LexicographicalComparerHolder { 1331 static final String UNSAFE_COMPARER_NAME = 1332 LexicographicalComparerHolder.class.getName() + "$UnsafeComparer"; 1333 1334 static final Comparer<byte[]> BEST_COMPARER = getBestComparer(); 1335 1336 /** 1337 * Returns the Unsafe-using Comparer, or falls back to the pure-Java implementation if unable to 1338 * do so. 1339 */ 1340 static Comparer<byte[]> getBestComparer() { 1341 try { 1342 Class<?> theClass = Class.forName(UNSAFE_COMPARER_NAME); 1343 1344 // yes, UnsafeComparer does implement Comparer<byte[]> 1345 @SuppressWarnings("unchecked") 1346 Comparer<byte[]> comparer = (Comparer<byte[]>) theClass.getEnumConstants()[0]; 1347 return comparer; 1348 } catch (Throwable t) { // ensure we really catch *everything* 1349 return lexicographicalComparerJavaImpl(); 1350 } 1351 } 1352 1353 enum PureJavaComparer implements Comparer<byte[]> { 1354 INSTANCE; 1355 1356 @Override 1357 public int compareTo(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, 1358 int length2) { 1359 // Short circuit equal case 1360 if (buffer1 == buffer2 && offset1 == offset2 && length1 == length2) { 1361 return 0; 1362 } 1363 // Bring WritableComparator code local 1364 int end1 = offset1 + length1; 1365 int end2 = offset2 + length2; 1366 for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) { 1367 int a = (buffer1[i] & 0xff); 1368 int b = (buffer2[j] & 0xff); 1369 if (a != b) { 1370 return a - b; 1371 } 1372 } 1373 return length1 - length2; 1374 } 1375 } 1376 1377 enum UnsafeComparer implements Comparer<byte[]> { 1378 INSTANCE; 1379 1380 static { 1381 if (!UNSAFE_UNALIGNED) { 1382 // It doesn't matter what we throw; 1383 // it's swallowed in getBestComparer(). 1384 throw new Error(); 1385 } 1386 1387 // sanity check - this should never fail 1388 if (HBasePlatformDependent.arrayIndexScale(byte[].class) != 1) { 1389 throw new AssertionError(); 1390 } 1391 } 1392 1393 /** 1394 * Lexicographically compare two arrays. 1395 * @param buffer1 left operand 1396 * @param buffer2 right operand 1397 * @param offset1 Where to start comparing in the left buffer 1398 * @param offset2 Where to start comparing in the right buffer 1399 * @param length1 How much to compare from the left buffer 1400 * @param length2 How much to compare from the right buffer 1401 * @return 0 if equal, < 0 if left is less than right, etc. 1402 */ 1403 @Override 1404 public int compareTo(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, 1405 int length2) { 1406 1407 // Short circuit equal case 1408 if (buffer1 == buffer2 && offset1 == offset2 && length1 == length2) { 1409 return 0; 1410 } 1411 final int stride = 8; 1412 final int minLength = Math.min(length1, length2); 1413 int strideLimit = minLength & ~(stride - 1); 1414 final long offset1Adj = offset1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; 1415 final long offset2Adj = offset2 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; 1416 int i; 1417 1418 /* 1419 * Compare 8 bytes at a time. Benchmarking on x86 shows a stride of 8 bytes is no slower 1420 * than 4 bytes even on 32-bit. On the other hand, it is substantially faster on 64-bit. 1421 */ 1422 for (i = 0; i < strideLimit; i += stride) { 1423 long lw = HBasePlatformDependent.getLong(buffer1, offset1Adj + i); 1424 long rw = HBasePlatformDependent.getLong(buffer2, offset2Adj + i); 1425 if (lw != rw) { 1426 if (!UnsafeAccess.LITTLE_ENDIAN) { 1427 return ((lw + Long.MIN_VALUE) < (rw + Long.MIN_VALUE)) ? -1 : 1; 1428 } 1429 1430 /* 1431 * We want to compare only the first index where left[index] != right[index]. This 1432 * corresponds to the least significant nonzero byte in lw ^ rw, since lw and rw are 1433 * little-endian. Long.numberOfTrailingZeros(diff) tells us the least significant 1434 * nonzero bit, and zeroing out the first three bits of L.nTZ gives us the shift to get 1435 * that least significant nonzero byte. This comparison logic is based on UnsignedBytes 1436 * comparator from guava v21 1437 */ 1438 int n = Long.numberOfTrailingZeros(lw ^ rw) & ~0x7; 1439 return ((int) ((lw >>> n) & 0xFF)) - ((int) ((rw >>> n) & 0xFF)); 1440 } 1441 } 1442 1443 // The epilogue to cover the last (minLength % stride) elements. 1444 for (; i < minLength; i++) { 1445 int a = (buffer1[offset1 + i] & 0xFF); 1446 int b = (buffer2[offset2 + i] & 0xFF); 1447 if (a != b) { 1448 return a - b; 1449 } 1450 } 1451 return length1 - length2; 1452 } 1453 } 1454 } 1455 1456 /** 1457 * Lexicographically determine the equality of two arrays. 1458 * @param left left operand 1459 * @param right right operand 1460 * @return True if equal 1461 */ 1462 public static boolean equals(final byte[] left, final byte[] right) { 1463 // Could use Arrays.equals? 1464 // noinspection SimplifiableConditionalExpression 1465 if (left == right) return true; 1466 if (left == null || right == null) return false; 1467 if (left.length != right.length) return false; 1468 if (left.length == 0) return true; 1469 1470 // Since we're often comparing adjacent sorted data, 1471 // it's usual to have equal arrays except for the very last byte 1472 // so check that first 1473 if (left[left.length - 1] != right[right.length - 1]) return false; 1474 1475 return compareTo(left, right) == 0; 1476 } 1477 1478 /** 1479 * Lexicographically determine the equality of two arrays. 1480 * @param left left operand 1481 * @param leftOffset offset into left operand 1482 * @param leftLen length of left operand 1483 * @param right right operand 1484 * @param rightOffset offset into right operand 1485 * @param rightLen length of right operand 1486 * @return True if equal 1487 */ 1488 public static boolean equals(final byte[] left, int leftOffset, int leftLen, final byte[] right, 1489 int rightOffset, int rightLen) { 1490 // short circuit case 1491 if (left == right && leftOffset == rightOffset && leftLen == rightLen) { 1492 return true; 1493 } 1494 // different lengths fast check 1495 if (leftLen != rightLen) { 1496 return false; 1497 } 1498 if (leftLen == 0) { 1499 return true; 1500 } 1501 1502 // Since we're often comparing adjacent sorted data, 1503 // it's usual to have equal arrays except for the very last byte 1504 // so check that first 1505 if (left[leftOffset + leftLen - 1] != right[rightOffset + rightLen - 1]) return false; 1506 1507 return LexicographicalComparerHolder.BEST_COMPARER.compareTo(left, leftOffset, leftLen, right, 1508 rightOffset, rightLen) == 0; 1509 } 1510 1511 /** 1512 * Lexicographically determine the equality of two byte[], one as ByteBuffer. 1513 * @param a left operand 1514 * @param buf right operand 1515 * @return True if equal 1516 */ 1517 public static boolean equals(byte[] a, ByteBuffer buf) { 1518 if (a == null) return buf == null; 1519 if (buf == null) return false; 1520 if (a.length != buf.remaining()) return false; 1521 1522 // Thou shalt not modify the original byte buffer in what should be read only operations. 1523 ByteBuffer b = buf.duplicate(); 1524 for (byte anA : a) { 1525 if (anA != b.get()) { 1526 return false; 1527 } 1528 } 1529 return true; 1530 } 1531 1532 /** 1533 * Return true if the byte array on the right is a prefix of the byte array on the left. 1534 */ 1535 public static boolean startsWith(byte[] bytes, byte[] prefix) { 1536 return bytes != null && prefix != null && bytes.length >= prefix.length 1537 && LexicographicalComparerHolder.BEST_COMPARER.compareTo(bytes, 0, prefix.length, prefix, 0, 1538 prefix.length) == 0; 1539 } 1540 1541 /** 1542 * Calculate a hash code from a given byte array. 1543 * @param b bytes to hash 1544 * @return Runs {@link WritableComparator#hashBytes(byte[], int)} on the passed in array. This 1545 * method is what {@link org.apache.hadoop.io.Text} use calculating hash code. 1546 */ 1547 public static int hashCode(final byte[] b) { 1548 return hashCode(b, b.length); 1549 } 1550 1551 /** 1552 * Calculate a hash code from a given byte array. 1553 * @param b value 1554 * @param length length of the value 1555 * @return Runs {@link WritableComparator#hashBytes(byte[], int)} on the passed in array. This 1556 * method is what {@link org.apache.hadoop.io.Text} use calculating hash code. 1557 */ 1558 public static int hashCode(final byte[] b, final int length) { 1559 return WritableComparator.hashBytes(b, length); 1560 } 1561 1562 /** 1563 * Calculate a hash code from a given byte array suitable for use as a key in maps. 1564 * @param b bytes to hash 1565 * @return A hash of <code>b</code> as an Integer that can be used as key in Maps. 1566 */ 1567 public static Integer mapKey(final byte[] b) { 1568 return hashCode(b); 1569 } 1570 1571 /** 1572 * Calculate a hash code from a given byte array suitable for use as a key in maps. 1573 * @param b bytes to hash 1574 * @param length length to hash 1575 * @return A hash of <code>b</code> as an Integer that can be used as key in Maps. 1576 */ 1577 public static Integer mapKey(final byte[] b, final int length) { 1578 return hashCode(b, length); 1579 } 1580 1581 /** 1582 * Concatenate byte arrays. 1583 * @param a lower half 1584 * @param b upper half 1585 * @return New array that has a in lower half and b in upper half. 1586 */ 1587 public static byte[] add(final byte[] a, final byte[] b) { 1588 return add(a, b, EMPTY_BYTE_ARRAY); 1589 } 1590 1591 /** 1592 * Concatenate byte arrays. 1593 * @param a first third 1594 * @param b second third 1595 * @param c third third 1596 * @return New array made from a, b and c 1597 */ 1598 public static byte[] add(final byte[] a, final byte[] b, final byte[] c) { 1599 byte[] result = new byte[a.length + b.length + c.length]; 1600 System.arraycopy(a, 0, result, 0, a.length); 1601 System.arraycopy(b, 0, result, a.length, b.length); 1602 System.arraycopy(c, 0, result, a.length + b.length, c.length); 1603 return result; 1604 } 1605 1606 /** 1607 * Concatenate byte arrays. 1608 * @param arrays all the arrays to concatenate together. 1609 * @return New array made from the concatenation of the given arrays. 1610 */ 1611 public static byte[] add(final byte[][] arrays) { 1612 int length = 0; 1613 for (int i = 0; i < arrays.length; i++) { 1614 length += arrays[i].length; 1615 } 1616 byte[] result = new byte[length]; 1617 int index = 0; 1618 for (int i = 0; i < arrays.length; i++) { 1619 System.arraycopy(arrays[i], 0, result, index, arrays[i].length); 1620 index += arrays[i].length; 1621 } 1622 return result; 1623 } 1624 1625 /** 1626 * Make a new byte array from a subset of bytes at the head of another. 1627 * @param a array 1628 * @param length amount of bytes to grab 1629 * @return First <code>length</code> bytes from <code>a</code> 1630 */ 1631 public static byte[] head(final byte[] a, final int length) { 1632 if (a.length < length) { 1633 return null; 1634 } 1635 byte[] result = new byte[length]; 1636 System.arraycopy(a, 0, result, 0, length); 1637 return result; 1638 } 1639 1640 /** 1641 * Make a new byte array from a subset of bytes at the tail of another. 1642 * @param a array 1643 * @param length amount of bytes to snarf 1644 * @return Last <code>length</code> bytes from <code>a</code> 1645 */ 1646 public static byte[] tail(final byte[] a, final int length) { 1647 if (a.length < length) { 1648 return null; 1649 } 1650 byte[] result = new byte[length]; 1651 System.arraycopy(a, a.length - length, result, 0, length); 1652 return result; 1653 } 1654 1655 /** 1656 * Make a new byte array from a subset of bytes at the head of another, zero padded as desired. 1657 * @param a array 1658 * @param length new array size 1659 * @return Value in <code>a</code> plus <code>length</code> prepended 0 bytes 1660 */ 1661 public static byte[] padHead(final byte[] a, final int length) { 1662 byte[] padding = new byte[length]; 1663 for (int i = 0; i < length; i++) { 1664 padding[i] = 0; 1665 } 1666 return add(padding, a); 1667 } 1668 1669 /** 1670 * Make a new byte array from a subset of bytes at the tail of another, zero padded as desired. 1671 * @param a array 1672 * @param length new array size 1673 * @return Value in <code>a</code> plus <code>length</code> appended 0 bytes 1674 */ 1675 public static byte[] padTail(final byte[] a, final int length) { 1676 byte[] padding = new byte[length]; 1677 for (int i = 0; i < length; i++) { 1678 padding[i] = 0; 1679 } 1680 return add(a, padding); 1681 } 1682 1683 /** 1684 * Split passed range. Expensive operation relatively. Uses BigInteger math. Useful splitting 1685 * ranges for MapReduce jobs. 1686 * @param a Beginning of range 1687 * @param b End of range 1688 * @param num Number of times to split range. Pass 1 if you want to split the range in two; i.e. 1689 * one split. 1690 * @return Array of dividing values 1691 */ 1692 public static byte[][] split(final byte[] a, final byte[] b, final int num) { 1693 return split(a, b, false, num); 1694 } 1695 1696 /** 1697 * Split passed range. Expensive operation relatively. Uses BigInteger math. Useful splitting 1698 * ranges for MapReduce jobs. 1699 * @param a Beginning of range 1700 * @param b End of range 1701 * @param inclusive Whether the end of range is prefix-inclusive or is considered an exclusive 1702 * boundary. Automatic splits are generally exclusive and manual splits with an 1703 * explicit range utilize an inclusive end of range. 1704 * @param num Number of times to split range. Pass 1 if you want to split the range in two; 1705 * i.e. one split. 1706 * @return Array of dividing values 1707 */ 1708 public static byte[][] split(final byte[] a, final byte[] b, boolean inclusive, final int num) { 1709 byte[][] ret = new byte[num + 2][]; 1710 int i = 0; 1711 Iterable<byte[]> iter = iterateOnSplits(a, b, inclusive, num); 1712 if (iter == null) return null; 1713 for (byte[] elem : iter) { 1714 ret[i++] = elem; 1715 } 1716 return ret; 1717 } 1718 1719 /** 1720 * Iterate over keys within the passed range, splitting at an [a,b) boundary. 1721 */ 1722 public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) { 1723 return iterateOnSplits(a, b, false, num); 1724 } 1725 1726 /** 1727 * Iterate over keys within the passed range. 1728 */ 1729 public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, 1730 final int num) { 1731 byte[] aPadded; 1732 byte[] bPadded; 1733 if (a.length < b.length) { 1734 aPadded = padTail(a, b.length - a.length); 1735 bPadded = b; 1736 } else if (b.length < a.length) { 1737 aPadded = a; 1738 bPadded = padTail(b, a.length - b.length); 1739 } else { 1740 aPadded = a; 1741 bPadded = b; 1742 } 1743 if (compareTo(aPadded, bPadded) >= 0) { 1744 throw new IllegalArgumentException("b <= a"); 1745 } 1746 if (num <= 0) { 1747 throw new IllegalArgumentException("num cannot be <= 0"); 1748 } 1749 byte[] prependHeader = { 1, 0 }; 1750 final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); 1751 final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); 1752 BigInteger diffBI = stopBI.subtract(startBI); 1753 if (inclusive) { 1754 diffBI = diffBI.add(BigInteger.ONE); 1755 } 1756 final BigInteger splitsBI = BigInteger.valueOf(num + 1); 1757 // when diffBI < splitBI, use an additional byte to increase diffBI 1758 if (diffBI.compareTo(splitsBI) < 0) { 1759 byte[] aPaddedAdditional = new byte[aPadded.length + 1]; 1760 byte[] bPaddedAdditional = new byte[bPadded.length + 1]; 1761 for (int i = 0; i < aPadded.length; i++) { 1762 aPaddedAdditional[i] = aPadded[i]; 1763 } 1764 for (int j = 0; j < bPadded.length; j++) { 1765 bPaddedAdditional[j] = bPadded[j]; 1766 } 1767 aPaddedAdditional[aPadded.length] = 0; 1768 bPaddedAdditional[bPadded.length] = 0; 1769 return iterateOnSplits(aPaddedAdditional, bPaddedAdditional, inclusive, num); 1770 } 1771 final BigInteger intervalBI; 1772 try { 1773 intervalBI = diffBI.divide(splitsBI); 1774 } catch (Exception e) { 1775 LOG.error("Exception caught during division", e); 1776 return null; 1777 } 1778 1779 final Iterator<byte[]> iterator = new Iterator<byte[]>() { 1780 private int i = -1; 1781 1782 @Override 1783 public boolean hasNext() { 1784 return i < num + 1; 1785 } 1786 1787 @Override 1788 public byte[] next() { 1789 i++; 1790 if (i == 0) return a; 1791 if (i == num + 1) return b; 1792 1793 BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); 1794 byte[] padded = curBI.toByteArray(); 1795 if (padded[1] == 0) padded = tail(padded, padded.length - 2); 1796 else padded = tail(padded, padded.length - 1); 1797 return padded; 1798 } 1799 1800 @Override 1801 public void remove() { 1802 throw new UnsupportedOperationException(); 1803 } 1804 1805 }; 1806 1807 return new Iterable<byte[]>() { 1808 @Override 1809 public Iterator<byte[]> iterator() { 1810 return iterator; 1811 } 1812 }; 1813 } 1814 1815 /** 1816 * Calculate the hash code for a given range of bytes. 1817 * @param bytes array to hash 1818 * @param offset offset to start from 1819 * @param length length to hash 1820 */ 1821 public static int hashCode(byte[] bytes, int offset, int length) { 1822 int hash = 1; 1823 for (int i = offset; i < offset + length; i++) 1824 hash = (31 * hash) + bytes[i]; 1825 return hash; 1826 } 1827 1828 /** 1829 * Create an array of byte[] given an array of String. 1830 * @param t operands 1831 * @return Array of byte arrays made from passed array of Text 1832 */ 1833 public static byte[][] toByteArrays(final String[] t) { 1834 byte[][] result = new byte[t.length][]; 1835 for (int i = 0; i < t.length; i++) { 1836 result[i] = Bytes.toBytes(t[i]); 1837 } 1838 return result; 1839 } 1840 1841 /** 1842 * Create an array of byte[] given an array of String. 1843 * @param t operands 1844 * @return Array of binary byte arrays made from passed array of binary strings 1845 */ 1846 public static byte[][] toBinaryByteArrays(final String[] t) { 1847 byte[][] result = new byte[t.length][]; 1848 for (int i = 0; i < t.length; i++) { 1849 result[i] = Bytes.toBytesBinary(t[i]); 1850 } 1851 return result; 1852 } 1853 1854 /** 1855 * Create a byte[][] where first and only entry is <code>column</code> 1856 * @param column operand 1857 * @return A byte array of a byte array where first and only entry is <code>column</code> 1858 */ 1859 public static byte[][] toByteArrays(final String column) { 1860 return toByteArrays(toBytes(column)); 1861 } 1862 1863 /** 1864 * Create a byte[][] where first and only entry is <code>column</code> 1865 * @param column operand 1866 * @return A byte array of a byte array where first and only entry is <code>column</code> 1867 */ 1868 public static byte[][] toByteArrays(final byte[] column) { 1869 byte[][] result = new byte[1][]; 1870 result[0] = column; 1871 return result; 1872 } 1873 1874 /** 1875 * Binary search for keys in indexes using Bytes.BYTES_RAWCOMPARATOR. 1876 * @param arr array of byte arrays to search for 1877 * @param key the key you want to find 1878 * @param offset the offset in the key you want to find 1879 * @param length the length of the key 1880 * @return zero-based index of the key, if the key is present in the array. Otherwise, a value -(i 1881 * + 1) such that the key is between arr[i - 1] and arr[i] non-inclusively, where i is in 1882 * [0, i], if we define arr[-1] = -Inf and arr[N] = Inf for an N-element array. The above 1883 * means that this function can return 2N + 1 different values ranging from -(N + 1) to N 1884 * - 1. 1885 */ 1886 public static int binarySearch(byte[][] arr, byte[] key, int offset, int length) { 1887 int low = 0; 1888 int high = arr.length - 1; 1889 1890 while (low <= high) { 1891 int mid = low + ((high - low) >> 1); 1892 // we have to compare in this order, because the comparator order 1893 // has special logic when the 'left side' is a special key. 1894 int cmp = 1895 Bytes.BYTES_RAWCOMPARATOR.compare(key, offset, length, arr[mid], 0, arr[mid].length); 1896 // key lives above the midpoint 1897 if (cmp > 0) low = mid + 1; 1898 // key lives below the midpoint 1899 else if (cmp < 0) high = mid - 1; 1900 // BAM. how often does this really happen? 1901 else return mid; 1902 } 1903 return -(low + 1); 1904 } 1905 1906 /** 1907 * Binary search for keys in indexes. 1908 * @param arr array of byte arrays to search for 1909 * @param key the key you want to find 1910 * @param comparator a comparator to compare. 1911 * @return zero-based index of the key, if the key is present in the array. Otherwise, a value -(i 1912 * + 1) such that the key is between arr[i - 1] and arr[i] non-inclusively, where i is in 1913 * [0, i], if we define arr[-1] = -Inf and arr[N] = Inf for an N-element array. The above 1914 * means that this function can return 2N + 1 different values ranging from -(N + 1) to N 1915 * - 1. 1916 * @return the index of the block 1917 */ 1918 public static int binarySearch(Cell[] arr, Cell key, CellComparator comparator) { 1919 int low = 0; 1920 int high = arr.length - 1; 1921 while (low <= high) { 1922 int mid = low + ((high - low) >> 1); 1923 // we have to compare in this order, because the comparator order 1924 // has special logic when the 'left side' is a special key. 1925 int cmp = comparator.compare(key, arr[mid]); 1926 // key lives above the midpoint 1927 if (cmp > 0) low = mid + 1; 1928 // key lives below the midpoint 1929 else if (cmp < 0) high = mid - 1; 1930 // BAM. how often does this really happen? 1931 else return mid; 1932 } 1933 return -(low + 1); 1934 } 1935 1936 /** 1937 * Bytewise binary increment/deincrement of long contained in byte array on given amount. 1938 * @param value - array of bytes containing long (length <= SIZEOF_LONG) 1939 * @param amount value will be incremented on (deincremented if negative) 1940 * @return array of bytes containing incremented long (length == SIZEOF_LONG) 1941 */ 1942 public static byte[] incrementBytes(byte[] value, long amount) { 1943 byte[] val = value; 1944 if (val.length < SIZEOF_LONG) { 1945 // Hopefully this doesn't happen too often. 1946 byte[] newvalue; 1947 if (val[0] < 0) { 1948 newvalue = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1 }; 1949 } else { 1950 newvalue = new byte[SIZEOF_LONG]; 1951 } 1952 System.arraycopy(val, 0, newvalue, newvalue.length - val.length, val.length); 1953 val = newvalue; 1954 } else if (val.length > SIZEOF_LONG) { 1955 throw new IllegalArgumentException("Increment Bytes - value too big: " + val.length); 1956 } 1957 if (amount == 0) return val; 1958 if (val[0] < 0) { 1959 return binaryIncrementNeg(val, amount); 1960 } 1961 return binaryIncrementPos(val, amount); 1962 } 1963 1964 /* increment/deincrement for positive value */ 1965 private static byte[] binaryIncrementPos(byte[] value, long amount) { 1966 long amo = amount; 1967 int sign = 1; 1968 if (amount < 0) { 1969 amo = -amount; 1970 sign = -1; 1971 } 1972 for (int i = 0; i < value.length; i++) { 1973 int cur = ((int) amo % 256) * sign; 1974 amo = (amo >> 8); 1975 int val = value[value.length - i - 1] & 0x0ff; 1976 int total = val + cur; 1977 if (total > 255) { 1978 amo += sign; 1979 total %= 256; 1980 } else if (total < 0) { 1981 amo -= sign; 1982 } 1983 value[value.length - i - 1] = (byte) total; 1984 if (amo == 0) return value; 1985 } 1986 return value; 1987 } 1988 1989 /* increment/deincrement for negative value */ 1990 private static byte[] binaryIncrementNeg(byte[] value, long amount) { 1991 long amo = amount; 1992 int sign = 1; 1993 if (amount < 0) { 1994 amo = -amount; 1995 sign = -1; 1996 } 1997 for (int i = 0; i < value.length; i++) { 1998 int cur = ((int) amo % 256) * sign; 1999 amo = (amo >> 8); 2000 int val = (~value[value.length - i - 1] & 0x0ff) + 1; 2001 int total = cur - val; 2002 if (total >= 0) { 2003 amo += sign; 2004 } else if (total < -256) { 2005 amo -= sign; 2006 total %= 256; 2007 } 2008 value[value.length - i - 1] = (byte) total; 2009 if (amo == 0) return value; 2010 } 2011 return value; 2012 } 2013 2014 /** 2015 * Writes a string as a fixed-size field, padded with zeros. 2016 */ 2017 public static void writeStringFixedSize(final DataOutput out, String s, int size) 2018 throws IOException { 2019 byte[] b = toBytes(s); 2020 if (b.length > size) { 2021 throw new IOException("Trying to write " + b.length + " bytes (" + toStringBinary(b) 2022 + ") into a field of length " + size); 2023 } 2024 2025 out.writeBytes(s); 2026 for (int i = 0; i < size - s.length(); ++i) 2027 out.writeByte(0); 2028 } 2029 2030 /** 2031 * Reads a fixed-size field and interprets it as a string padded with zeros. 2032 */ 2033 public static String readStringFixedSize(final DataInput in, int size) throws IOException { 2034 byte[] b = new byte[size]; 2035 in.readFully(b); 2036 int n = b.length; 2037 while (n > 0 && b[n - 1] == 0) 2038 --n; 2039 2040 return toString(b, 0, n); 2041 } 2042 2043 /** 2044 * Copy the byte array given in parameter and return an instance of a new byte array with the same 2045 * length and the same content. 2046 * @param bytes the byte array to duplicate 2047 * @return a copy of the given byte array 2048 */ 2049 public static byte[] copy(byte[] bytes) { 2050 if (bytes == null) return null; 2051 byte[] result = new byte[bytes.length]; 2052 System.arraycopy(bytes, 0, result, 0, bytes.length); 2053 return result; 2054 } 2055 2056 /** 2057 * Copy the byte array given in parameter and return an instance of a new byte array with the same 2058 * length and the same content. 2059 * @param bytes the byte array to copy from 2060 * @return a copy of the given designated byte array 2061 */ 2062 public static byte[] copy(byte[] bytes, final int offset, final int length) { 2063 if (bytes == null) return null; 2064 byte[] result = new byte[length]; 2065 System.arraycopy(bytes, offset, result, 0, length); 2066 return result; 2067 } 2068 2069 /** 2070 * Search sorted array "a" for byte "key". I can't remember if I wrote this or copied it from 2071 * somewhere. (mcorgan) 2072 * @param a Array to search. Entries must be sorted and unique. 2073 * @param fromIndex First index inclusive of "a" to include in the search. 2074 * @param toIndex Last index exclusive of "a" to include in the search. 2075 * @param key The byte to search for. 2076 * @return The index of key if found. If not found, return -(index + 1), where negative indicates 2077 * "not found" and the "index + 1" handles the "-0" case. 2078 */ 2079 public static int unsignedBinarySearch(byte[] a, int fromIndex, int toIndex, byte key) { 2080 int unsignedKey = key & 0xff; 2081 int low = fromIndex; 2082 int high = toIndex - 1; 2083 2084 while (low <= high) { 2085 int mid = low + ((high - low) >> 1); 2086 int midVal = a[mid] & 0xff; 2087 2088 if (midVal < unsignedKey) { 2089 low = mid + 1; 2090 } else if (midVal > unsignedKey) { 2091 high = mid - 1; 2092 } else { 2093 return mid; // key found 2094 } 2095 } 2096 return -(low + 1); // key not found. 2097 } 2098 2099 /** 2100 * Treat the byte[] as an unsigned series of bytes, most significant bits first. Start by adding 1 2101 * to the rightmost bit/byte and carry over all overflows to the more significant bits/bytes. 2102 * @param input The byte[] to increment. 2103 * @return The incremented copy of "in". May be same length or 1 byte longer. 2104 */ 2105 public static byte[] unsignedCopyAndIncrement(final byte[] input) { 2106 byte[] copy = copy(input); 2107 if (copy == null) { 2108 throw new IllegalArgumentException("cannot increment null array"); 2109 } 2110 for (int i = copy.length - 1; i >= 0; --i) { 2111 if (copy[i] == -1) {// -1 is all 1-bits, which is the unsigned maximum 2112 copy[i] = 0; 2113 } else { 2114 ++copy[i]; 2115 return copy; 2116 } 2117 } 2118 // we maxed out the array 2119 byte[] out = new byte[copy.length + 1]; 2120 out[0] = 1; 2121 System.arraycopy(copy, 0, out, 1, copy.length); 2122 return out; 2123 } 2124 2125 public static boolean equals(List<byte[]> a, List<byte[]> b) { 2126 if (a == null) { 2127 if (b == null) { 2128 return true; 2129 } 2130 return false; 2131 } 2132 if (b == null) { 2133 return false; 2134 } 2135 if (a.size() != b.size()) { 2136 return false; 2137 } 2138 for (int i = 0; i < a.size(); ++i) { 2139 if (!Bytes.equals(a.get(i), b.get(i))) { 2140 return false; 2141 } 2142 } 2143 return true; 2144 } 2145 2146 public static boolean isSorted(Collection<byte[]> arrays) { 2147 if (!CollectionUtils.isEmpty(arrays)) { 2148 byte[] previous = new byte[0]; 2149 for (byte[] array : arrays) { 2150 if (Bytes.compareTo(previous, array) > 0) { 2151 return false; 2152 } 2153 previous = array; 2154 } 2155 } 2156 return true; 2157 } 2158 2159 public static List<byte[]> getUtf8ByteArrays(List<String> strings) { 2160 if (CollectionUtils.isEmpty(strings)) { 2161 return Collections.emptyList(); 2162 } 2163 List<byte[]> byteArrays = new ArrayList<>(strings.size()); 2164 strings.forEach(s -> byteArrays.add(Bytes.toBytes(s))); 2165 return byteArrays; 2166 } 2167 2168 /** 2169 * Returns the index of the first appearance of the value {@code target} in {@code array}. 2170 * @param array an array of {@code byte} values, possibly empty 2171 * @param target a primitive {@code byte} value 2172 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 2173 * such index exists. 2174 */ 2175 public static int indexOf(byte[] array, byte target) { 2176 for (int i = 0; i < array.length; i++) { 2177 if (array[i] == target) { 2178 return i; 2179 } 2180 } 2181 return -1; 2182 } 2183 2184 /** 2185 * Returns the start position of the first occurrence of the specified {@code 2186 * target} within {@code array}, or {@code -1} if there is no such occurrence. 2187 * <p> 2188 * More formally, returns the lowest index {@code i} such that {@code 2189 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly the same elements 2190 * as {@code target}. 2191 * @param array the array to search for the sequence {@code target} 2192 * @param target the array to search for as a sub-sequence of {@code array} 2193 */ 2194 public static int indexOf(byte[] array, byte[] target) { 2195 checkNotNull(array, "array"); 2196 checkNotNull(target, "target"); 2197 if (target.length == 0) { 2198 return 0; 2199 } 2200 2201 outer: for (int i = 0; i < array.length - target.length + 1; i++) { 2202 for (int j = 0; j < target.length; j++) { 2203 if (array[i + j] != target[j]) { 2204 continue outer; 2205 } 2206 } 2207 return i; 2208 } 2209 return -1; 2210 } 2211 2212 /** 2213 * Return true if target is present as an element anywhere in the given array. 2214 * @param array an array of {@code byte} values, possibly empty 2215 * @param target a primitive {@code byte} value 2216 * @return {@code true} if {@code target} is present as an element anywhere in {@code array}. 2217 */ 2218 public static boolean contains(byte[] array, byte target) { 2219 return indexOf(array, target) > -1; 2220 } 2221 2222 /** 2223 * Return true if target is present as an element anywhere in the given array. 2224 * @param array an array of {@code byte} values, possibly empty 2225 * @param target an array of {@code byte} 2226 * @return {@code true} if {@code target} is present anywhere in {@code array} 2227 */ 2228 public static boolean contains(byte[] array, byte[] target) { 2229 return indexOf(array, target) > -1; 2230 } 2231 2232 /** 2233 * Fill given array with zeros. 2234 * @param b array which needs to be filled with zeros 2235 */ 2236 public static void zero(byte[] b) { 2237 zero(b, 0, b.length); 2238 } 2239 2240 /** 2241 * Fill given array with zeros at the specified position. 2242 */ 2243 public static void zero(byte[] b, int offset, int length) { 2244 checkPositionIndex(offset, b.length, "offset"); 2245 checkArgument(length > 0, "length must be greater than 0"); 2246 checkPositionIndex(offset + length, b.length, "offset + length"); 2247 Arrays.fill(b, offset, offset + length, (byte) 0); 2248 } 2249 2250 // Pseudorandom random number generator, do not use SecureRandom here 2251 private static final Random RNG = new Random(); 2252 2253 /** 2254 * Fill given array with random bytes. 2255 * @param b array which needs to be filled with random bytes 2256 * <p> 2257 * If you want random bytes generated by a strong source of randomness use 2258 * {@link Bytes#secureRandom(byte[])}. 2259 * @param b array which needs to be filled with random bytes 2260 */ 2261 public static void random(byte[] b) { 2262 RNG.nextBytes(b); 2263 } 2264 2265 /** 2266 * Fill given array with random bytes at the specified position. 2267 * <p> 2268 * If you want random bytes generated by a strong source of randomness use 2269 * {@link Bytes#secureRandom(byte[], int, int)}. 2270 * @param b array which needs to be filled with random bytes 2271 * @param offset staring offset in array 2272 * @param length number of bytes to fill 2273 */ 2274 public static void random(byte[] b, int offset, int length) { 2275 checkPositionIndex(offset, b.length, "offset"); 2276 checkArgument(length > 0, "length must be greater than 0"); 2277 checkPositionIndex(offset + length, b.length, "offset + length"); 2278 byte[] buf = new byte[length]; 2279 RNG.nextBytes(buf); 2280 System.arraycopy(buf, 0, b, offset, length); 2281 } 2282 2283 // Bytes.secureRandom may be used to create key material. 2284 private static final SecureRandom SECURE_RNG = new SecureRandom(); 2285 2286 /** 2287 * Fill given array with random bytes using a strong random number generator. 2288 * @param b array which needs to be filled with random bytes 2289 */ 2290 public static void secureRandom(byte[] b) { 2291 SECURE_RNG.nextBytes(b); 2292 } 2293 2294 /** 2295 * Fill given array with random bytes at the specified position using a strong random number 2296 * generator. 2297 * @param b array which needs to be filled with random bytes 2298 * @param offset staring offset in array 2299 * @param length number of bytes to fill 2300 */ 2301 public static void secureRandom(byte[] b, int offset, int length) { 2302 checkPositionIndex(offset, b.length, "offset"); 2303 checkArgument(length > 0, "length must be greater than 0"); 2304 checkPositionIndex(offset + length, b.length, "offset + length"); 2305 byte[] buf = new byte[length]; 2306 SECURE_RNG.nextBytes(buf); 2307 System.arraycopy(buf, 0, b, offset, length); 2308 } 2309 2310 /** 2311 * Create a max byte array with the specified max byte count 2312 * @param maxByteCount the length of returned byte array 2313 * @return the created max byte array 2314 */ 2315 public static byte[] createMaxByteArray(int maxByteCount) { 2316 byte[] maxByteArray = new byte[maxByteCount]; 2317 for (int i = 0; i < maxByteArray.length; i++) { 2318 maxByteArray[i] = (byte) 0xff; 2319 } 2320 return maxByteArray; 2321 } 2322 2323 /** 2324 * Create a byte array which is multiple given bytes 2325 * @return byte array 2326 */ 2327 public static byte[] multiple(byte[] srcBytes, int multiNum) { 2328 if (multiNum <= 0) { 2329 return new byte[0]; 2330 } 2331 byte[] result = new byte[srcBytes.length * multiNum]; 2332 for (int i = 0; i < multiNum; i++) { 2333 System.arraycopy(srcBytes, 0, result, i * srcBytes.length, srcBytes.length); 2334 } 2335 return result; 2336 } 2337 2338 private static final char[] HEX_CHARS = 2339 { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 2340 2341 /** 2342 * Convert a byte range into a hex string 2343 */ 2344 public static String toHex(byte[] b, int offset, int length) { 2345 checkArgument(length <= Integer.MAX_VALUE / 2); 2346 int numChars = length * 2; 2347 char[] ch = new char[numChars]; 2348 for (int i = 0; i < numChars; i += 2) { 2349 byte d = b[offset + i / 2]; 2350 ch[i] = HEX_CHARS[(d >> 4) & 0x0F]; 2351 ch[i + 1] = HEX_CHARS[d & 0x0F]; 2352 } 2353 return new String(ch); 2354 } 2355 2356 /** 2357 * Convert a byte array into a hex string 2358 */ 2359 public static String toHex(byte[] b) { 2360 return toHex(b, 0, b.length); 2361 } 2362 2363 private static int hexCharToNibble(char ch) { 2364 if (ch <= '9' && ch >= '0') { 2365 return ch - '0'; 2366 } else if (ch >= 'a' && ch <= 'f') { 2367 return ch - 'a' + 10; 2368 } else if (ch >= 'A' && ch <= 'F') { 2369 return ch - 'A' + 10; 2370 } 2371 throw new IllegalArgumentException("Invalid hex char: " + ch); 2372 } 2373 2374 private static byte hexCharsToByte(char c1, char c2) { 2375 return (byte) ((hexCharToNibble(c1) << 4) | hexCharToNibble(c2)); 2376 } 2377 2378 /** 2379 * Create a byte array from a string of hash digits. The length of the string must be a multiple 2380 * of 2 2381 */ 2382 public static byte[] fromHex(String hex) { 2383 checkArgument(hex.length() % 2 == 0, "length must be a multiple of 2"); 2384 int len = hex.length(); 2385 byte[] b = new byte[len / 2]; 2386 for (int i = 0; i < len; i += 2) { 2387 b[i / 2] = hexCharsToByte(hex.charAt(i), hex.charAt(i + 1)); 2388 } 2389 return b; 2390 } 2391 2392 /** 2393 * Find index of passed delimiter. 2394 * @return Index of delimiter having started from start of <code>b</code> moving rightward. 2395 */ 2396 public static int searchDelimiterIndex(final byte[] b, int offset, final int length, 2397 final int delimiter) { 2398 if (b == null) { 2399 throw new IllegalArgumentException("Passed buffer is null"); 2400 } 2401 int result = -1; 2402 for (int i = offset; i < length + offset; i++) { 2403 if (b[i] == delimiter) { 2404 result = i; 2405 break; 2406 } 2407 } 2408 return result; 2409 } 2410 2411 /** 2412 * Find index of passed delimiter walking from end of buffer backwards. 2413 * @return Index of delimiter 2414 */ 2415 public static int searchDelimiterIndexInReverse(final byte[] b, final int offset, 2416 final int length, final int delimiter) { 2417 if (b == null) { 2418 throw new IllegalArgumentException("Passed buffer is null"); 2419 } 2420 int result = -1; 2421 for (int i = (offset + length) - 1; i >= offset; i--) { 2422 if (b[i] == delimiter) { 2423 result = i; 2424 break; 2425 } 2426 } 2427 return result; 2428 } 2429 2430 public static int findCommonPrefix(byte[] left, byte[] right, int leftLength, int rightLength, 2431 int leftOffset, int rightOffset) { 2432 int length = Math.min(leftLength, rightLength); 2433 int result = 0; 2434 2435 while (result < length && left[leftOffset + result] == right[rightOffset + result]) { 2436 result++; 2437 } 2438 return result; 2439 } 2440}