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