View Javadoc

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