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