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