1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.Cell;
44 import org.apache.hadoop.hbase.KeyValue;
45 import org.apache.hadoop.io.RawComparator;
46 import org.apache.hadoop.io.WritableComparator;
47 import org.apache.hadoop.io.WritableUtils;
48
49 import sun.misc.Unsafe;
50
51 import com.google.common.annotations.VisibleForTesting;
52 import com.google.common.collect.Lists;
53
54 import org.apache.hadoop.hbase.util.Bytes.LexicographicalComparerHolder.UnsafeComparer;
55
56
57
58
59
60
61 @SuppressWarnings("restriction")
62 @InterfaceAudience.Public
63 @InterfaceStability.Stable
64 public class Bytes implements Comparable<Bytes> {
65
66
67 private static final String UTF8_ENCODING = "UTF-8";
68
69
70
71 private static final Charset UTF8_CHARSET = Charset.forName(UTF8_ENCODING);
72
73
74 private static final byte [] EMPTY_BYTE_ARRAY = new byte [0];
75
76 private static final Log LOG = LogFactory.getLog(Bytes.class);
77
78
79
80
81 public static final int SIZEOF_BOOLEAN = Byte.SIZE / Byte.SIZE;
82
83
84
85
86 public static final int SIZEOF_BYTE = SIZEOF_BOOLEAN;
87
88
89
90
91 public static final int SIZEOF_CHAR = Character.SIZE / Byte.SIZE;
92
93
94
95
96 public static final int SIZEOF_DOUBLE = Double.SIZE / Byte.SIZE;
97
98
99
100
101 public static final int SIZEOF_FLOAT = Float.SIZE / Byte.SIZE;
102
103
104
105
106 public static final int SIZEOF_INT = Integer.SIZE / Byte.SIZE;
107
108
109
110
111 public static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE;
112
113
114
115
116 public static final int SIZEOF_SHORT = Short.SIZE / Byte.SIZE;
117
118
119
120
121
122 public static final long MASK_FOR_LOWER_INT_IN_LONG = 0xFFFFFFFF00000000l;
123
124
125
126
127
128
129
130 public static final int ESTIMATED_HEAP_TAX = 16;
131
132 private static final boolean UNSAFE_UNALIGNED = UnsafeAvailChecker.unaligned();
133
134
135
136
137
138
139
140 final public static int len(byte[] b) {
141 return b == null ? 0 : b.length;
142 }
143
144 private byte[] bytes;
145 private int offset;
146 private int length;
147
148
149
150
151 public Bytes() {
152 super();
153 }
154
155
156
157
158
159 public Bytes(byte[] bytes) {
160 this(bytes, 0, bytes.length);
161 }
162
163
164
165
166
167
168 public Bytes(final Bytes ibw) {
169 this(ibw.get(), ibw.getOffset(), ibw.getLength());
170 }
171
172
173
174
175
176
177
178 public Bytes(final byte[] bytes, final int offset,
179 final int length) {
180 this.bytes = bytes;
181 this.offset = offset;
182 this.length = length;
183 }
184
185
186
187
188
189 public byte[] get() {
190 if (this.bytes == null) {
191 throw new IllegalStateException("Uninitialiized. Null constructor " +
192 "called w/o accompaying readFields invocation");
193 }
194 return this.bytes;
195 }
196
197
198
199
200 public void set(final byte[] b) {
201 set(b, 0, b.length);
202 }
203
204
205
206
207
208
209 public void set(final byte[] b, final int offset, final int length) {
210 this.bytes = b;
211 this.offset = offset;
212 this.length = length;
213 }
214
215
216
217
218 public int getLength() {
219 if (this.bytes == null) {
220 throw new IllegalStateException("Uninitialiized. Null constructor " +
221 "called w/o accompaying readFields invocation");
222 }
223 return this.length;
224 }
225
226
227
228
229 public int getOffset(){
230 return this.offset;
231 }
232 @Override
233 public int hashCode() {
234 return Bytes.hashCode(bytes, offset, length);
235 }
236
237
238
239
240
241
242
243 @Override
244 public int compareTo(Bytes that) {
245 return BYTES_RAWCOMPARATOR.compare(
246 this.bytes, this.offset, this.length,
247 that.bytes, that.offset, that.length);
248 }
249
250
251
252
253
254
255
256 public int compareTo(final byte[] that) {
257 return BYTES_RAWCOMPARATOR.compare(
258 this.bytes, this.offset, this.length,
259 that, 0, that.length);
260 }
261
262
263
264
265 @Override
266 public boolean equals(Object that) {
267 if (that == this) {
268 return true;
269 }
270 if (that instanceof Bytes) {
271 return compareTo((Bytes)that) == 0;
272 }
273 return false;
274 }
275
276
277
278
279 @Override
280 public String toString() {
281 return Bytes.toString(bytes, offset, length);
282 }
283
284
285
286
287 public byte[] copyBytes() {
288 return Arrays.copyOfRange(bytes, offset, offset+length);
289 }
290
291
292
293
294 @InterfaceAudience.Public
295 @InterfaceStability.Stable
296 public static class ByteArrayComparator implements RawComparator<byte []> {
297
298
299
300 public ByteArrayComparator() {
301 super();
302 }
303 @Override
304 public int compare(byte [] left, byte [] right) {
305 return compareTo(left, right);
306 }
307 @Override
308 public int compare(byte [] b1, int s1, int l1, byte [] b2, int s2, int l2) {
309 return LexicographicalComparerHolder.BEST_COMPARER.
310 compareTo(b1, s1, l1, b2, s2, l2);
311 }
312 }
313
314
315
316
317
318
319
320
321
322 @InterfaceAudience.Public
323 @InterfaceStability.Stable
324 public static class RowEndKeyComparator extends ByteArrayComparator {
325 @Override
326 public int compare(byte[] left, byte[] right) {
327 return compare(left, 0, left.length, right, 0, right.length);
328 }
329 @Override
330 public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
331 if (b1 == b2 && s1 == s2 && l1 == l2) {
332 return 0;
333 }
334 if (l1 == 0) {
335 return l2;
336 }
337 if (l2 == 0) {
338 return -1;
339 }
340 return super.compare(b1, s1, l1, b2, s2, l2);
341 }
342 }
343
344
345
346
347 public final static Comparator<byte []> BYTES_COMPARATOR = new ByteArrayComparator();
348
349
350
351
352 public final static RawComparator<byte []> BYTES_RAWCOMPARATOR = new ByteArrayComparator();
353
354
355
356
357
358
359
360 public static byte [] readByteArray(final DataInput in)
361 throws IOException {
362 int len = WritableUtils.readVInt(in);
363 if (len < 0) {
364 throw new NegativeArraySizeException(Integer.toString(len));
365 }
366 byte [] result = new byte[len];
367 in.readFully(result, 0, len);
368 return result;
369 }
370
371
372
373
374
375
376
377 public static byte [] readByteArrayThrowsRuntime(final DataInput in) {
378 try {
379 return readByteArray(in);
380 } catch (Exception e) {
381 throw new RuntimeException(e);
382 }
383 }
384
385
386
387
388
389
390
391 public static void writeByteArray(final DataOutput out, final byte [] b)
392 throws IOException {
393 if(b == null) {
394 WritableUtils.writeVInt(out, 0);
395 } else {
396 writeByteArray(out, b, 0, b.length);
397 }
398 }
399
400
401
402
403
404
405
406
407
408 public static void writeByteArray(final DataOutput out, final byte [] b,
409 final int offset, final int length)
410 throws IOException {
411 WritableUtils.writeVInt(out, length);
412 out.write(b, offset, length);
413 }
414
415
416
417
418
419
420
421
422
423
424 public static int writeByteArray(final byte [] tgt, final int tgtOffset,
425 final byte [] src, final int srcOffset, final int srcLength) {
426 byte [] vint = vintToBytes(srcLength);
427 System.arraycopy(vint, 0, tgt, tgtOffset, vint.length);
428 int offset = tgtOffset + vint.length;
429 System.arraycopy(src, srcOffset, tgt, offset, srcLength);
430 return offset + srcLength;
431 }
432
433
434
435
436
437
438
439
440
441
442 public static int putBytes(byte[] tgtBytes, int tgtOffset, byte[] srcBytes,
443 int srcOffset, int srcLength) {
444 System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength);
445 return tgtOffset + srcLength;
446 }
447
448
449
450
451
452
453
454
455 public static int putByte(byte[] bytes, int offset, byte b) {
456 bytes[offset] = b;
457 return offset + 1;
458 }
459
460
461
462
463
464
465
466
467 public static int putByteBuffer(byte[] bytes, int offset, ByteBuffer buf) {
468 int len = buf.remaining();
469 buf.get(bytes, offset, len);
470 return offset + len;
471 }
472
473
474
475
476
477
478
479
480
481
482
483 public static byte[] toBytes(ByteBuffer buf) {
484 ByteBuffer dup = buf.duplicate();
485 dup.position(0);
486 return readBytes(dup);
487 }
488
489 private static byte[] readBytes(ByteBuffer buf) {
490 byte [] result = new byte[buf.remaining()];
491 buf.get(result);
492 return result;
493 }
494
495
496
497
498
499 public static String toString(final byte [] b) {
500 if (b == null) {
501 return null;
502 }
503 return toString(b, 0, b.length);
504 }
505
506
507
508
509
510
511
512 public static String toString(final byte [] b1,
513 String sep,
514 final byte [] b2) {
515 return toString(b1, 0, b1.length) + sep + toString(b2, 0, b2.length);
516 }
517
518
519
520
521
522
523
524
525 public static String toString(final byte[] b, int off) {
526 if (b == null) {
527 return null;
528 }
529 int len = b.length - off;
530 if (len <= 0) {
531 return "";
532 }
533 return new String(b, off, len, UTF8_CHARSET);
534 }
535
536
537
538
539
540
541
542
543
544
545 public static String toString(final byte [] b, int off, int len) {
546 if (b == null) {
547 return null;
548 }
549 if (len == 0) {
550 return "";
551 }
552 return new String(b, off, len, UTF8_CHARSET);
553 }
554
555
556
557
558
559
560
561
562 public static String toStringBinary(final byte [] b) {
563 if (b == null)
564 return "null";
565 return toStringBinary(b, 0, b.length);
566 }
567
568
569
570
571
572
573
574
575
576
577
578
579 public static String toStringBinary(ByteBuffer buf) {
580 if (buf == null)
581 return "null";
582 if (buf.hasArray()) {
583 return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit());
584 }
585 return toStringBinary(toBytes(buf));
586 }
587
588 private static final char[] HEX_CHARS_UPPER = {
589 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
590 };
591
592
593
594
595
596
597
598
599
600
601
602 public static String toStringBinary(final byte [] b, int off, int len) {
603 StringBuilder result = new StringBuilder();
604
605 if (off >= b.length) return result.toString();
606 if (off + len > b.length) len = b.length - off;
607 for (int i = off; i < off + len ; ++i ) {
608 int ch = b[i] & 0xFF;
609 if (ch >= ' ' && ch <= '~' && ch != '\\') {
610 result.append((char)ch);
611 } else {
612 result.append("\\x");
613 result.append(HEX_CHARS_UPPER[ch / 0x10]);
614 result.append(HEX_CHARS_UPPER[ch % 0x10]);
615 }
616 }
617 return result.toString();
618 }
619
620 private static boolean isHexDigit(char c) {
621 return
622 (c >= 'A' && c <= 'F') ||
623 (c >= '0' && c <= '9');
624 }
625
626
627
628
629
630
631
632 public static byte toBinaryFromHex(byte ch) {
633 if ( ch >= 'A' && ch <= 'F' )
634 return (byte) ((byte)10 + (byte) (ch - 'A'));
635
636 return (byte) (ch - '0');
637 }
638
639 public static byte [] toBytesBinary(String in) {
640
641 byte [] b = new byte[in.length()];
642 int size = 0;
643 for (int i = 0; i < in.length(); ++i) {
644 char ch = in.charAt(i);
645 if (ch == '\\' && in.length() > i+1 && in.charAt(i+1) == 'x') {
646
647 char hd1 = in.charAt(i+2);
648 char hd2 = in.charAt(i+3);
649
650
651 if (!isHexDigit(hd1) ||
652 !isHexDigit(hd2)) {
653
654 continue;
655 }
656
657 byte d = (byte) ((toBinaryFromHex((byte)hd1) << 4) + toBinaryFromHex((byte)hd2));
658
659 b[size++] = d;
660 i += 3;
661 } else {
662 b[size++] = (byte) ch;
663 }
664 }
665
666 byte [] b2 = new byte[size];
667 System.arraycopy(b, 0, b2, 0, size);
668 return b2;
669 }
670
671
672
673
674
675
676 public static byte[] toBytes(String s) {
677 return s.getBytes(UTF8_CHARSET);
678 }
679
680
681
682
683
684
685
686
687 public static byte [] toBytes(final boolean b) {
688 return new byte[] { b ? (byte) -1 : (byte) 0 };
689 }
690
691
692
693
694
695
696 public static boolean toBoolean(final byte [] b) {
697 if (b.length != 1) {
698 throw new IllegalArgumentException("Array has wrong size: " + b.length);
699 }
700 return b[0] != (byte) 0;
701 }
702
703
704
705
706
707
708
709 public static byte[] toBytes(long val) {
710 byte [] b = new byte[8];
711 for (int i = 7; i > 0; i--) {
712 b[i] = (byte) val;
713 val >>>= 8;
714 }
715 b[0] = (byte) val;
716 return b;
717 }
718
719
720
721
722
723
724
725 public static long toLong(byte[] bytes) {
726 return toLong(bytes, 0, SIZEOF_LONG);
727 }
728
729
730
731
732
733
734
735
736
737 public static long toLong(byte[] bytes, int offset) {
738 return toLong(bytes, offset, SIZEOF_LONG);
739 }
740
741
742
743
744
745
746
747
748
749
750
751 public static long toLong(byte[] bytes, int offset, final int length) {
752 if (length != SIZEOF_LONG || offset + length > bytes.length) {
753 throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG);
754 }
755 if (UNSAFE_UNALIGNED) {
756 return toLongUnsafe(bytes, offset);
757 } else {
758 long l = 0;
759 for(int i = offset; i < offset + length; i++) {
760 l <<= 8;
761 l ^= bytes[i] & 0xFF;
762 }
763 return l;
764 }
765 }
766
767 private static IllegalArgumentException
768 explainWrongLengthOrOffset(final byte[] bytes,
769 final int offset,
770 final int length,
771 final int expectedLength) {
772 String reason;
773 if (length != expectedLength) {
774 reason = "Wrong length: " + length + ", expected " + expectedLength;
775 } else {
776 reason = "offset (" + offset + ") + length (" + length + ") exceed the"
777 + " capacity of the array: " + bytes.length;
778 }
779 return new IllegalArgumentException(reason);
780 }
781
782
783
784
785
786
787
788
789
790
791 public static int putLong(byte[] bytes, int offset, long val) {
792 if (bytes.length - offset < SIZEOF_LONG) {
793 throw new IllegalArgumentException("Not enough room to put a long at"
794 + " offset " + offset + " in a " + bytes.length + " byte array");
795 }
796 if (UNSAFE_UNALIGNED) {
797 return putLongUnsafe(bytes, offset, val);
798 } else {
799 for(int i = offset + 7; i > offset; i--) {
800 bytes[i] = (byte) val;
801 val >>>= 8;
802 }
803 bytes[offset] = (byte) val;
804 return offset + SIZEOF_LONG;
805 }
806 }
807
808
809
810
811
812
813
814
815 public static int putLongUnsafe(byte[] bytes, int offset, long val)
816 {
817 if (UnsafeComparer.littleEndian) {
818 val = Long.reverseBytes(val);
819 }
820 UnsafeComparer.theUnsafe.putLong(bytes, (long) offset +
821 UnsafeComparer.BYTE_ARRAY_BASE_OFFSET , val);
822 return offset + SIZEOF_LONG;
823 }
824
825
826
827
828
829
830 public static float toFloat(byte [] bytes) {
831 return toFloat(bytes, 0);
832 }
833
834
835
836
837
838
839
840 public static float toFloat(byte [] bytes, int offset) {
841 return Float.intBitsToFloat(toInt(bytes, offset, SIZEOF_INT));
842 }
843
844
845
846
847
848
849
850 public static int putFloat(byte [] bytes, int offset, float f) {
851 return putInt(bytes, offset, Float.floatToRawIntBits(f));
852 }
853
854
855
856
857
858 public static byte [] toBytes(final float f) {
859
860 return Bytes.toBytes(Float.floatToRawIntBits(f));
861 }
862
863
864
865
866
867 public static double toDouble(final byte [] bytes) {
868 return toDouble(bytes, 0);
869 }
870
871
872
873
874
875
876 public static double toDouble(final byte [] bytes, final int offset) {
877 return Double.longBitsToDouble(toLong(bytes, offset, SIZEOF_LONG));
878 }
879
880
881
882
883
884
885
886 public static int putDouble(byte [] bytes, int offset, double d) {
887 return putLong(bytes, offset, Double.doubleToLongBits(d));
888 }
889
890
891
892
893
894
895
896
897 public static byte [] toBytes(final double d) {
898
899 return Bytes.toBytes(Double.doubleToRawLongBits(d));
900 }
901
902
903
904
905
906
907
908
909 public static byte[] toBytes(int val) {
910 byte [] b = new byte[4];
911 for(int i = 3; i > 0; i--) {
912 b[i] = (byte) val;
913 val >>>= 8;
914 }
915 b[0] = (byte) val;
916 return b;
917 }
918
919
920
921
922
923
924 public static int toInt(byte[] bytes) {
925 return toInt(bytes, 0, SIZEOF_INT);
926 }
927
928
929
930
931
932
933
934 public static int toInt(byte[] bytes, int offset) {
935 return toInt(bytes, offset, SIZEOF_INT);
936 }
937
938
939
940
941
942
943
944
945
946
947 public static int toInt(byte[] bytes, int offset, final int length) {
948 if (length != SIZEOF_INT || offset + length > bytes.length) {
949 throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_INT);
950 }
951 if (UNSAFE_UNALIGNED) {
952 return toIntUnsafe(bytes, offset);
953 } else {
954 int n = 0;
955 for(int i = offset; i < (offset + length); i++) {
956 n <<= 8;
957 n ^= bytes[i] & 0xFF;
958 }
959 return n;
960 }
961 }
962
963
964
965
966
967
968
969 public static int toIntUnsafe(byte[] bytes, int offset) {
970 if (UnsafeComparer.littleEndian) {
971 return Integer.reverseBytes(UnsafeComparer.theUnsafe.getInt(bytes,
972 (long) offset + UnsafeComparer.BYTE_ARRAY_BASE_OFFSET));
973 } else {
974 return UnsafeComparer.theUnsafe.getInt(bytes,
975 (long) offset + UnsafeComparer.BYTE_ARRAY_BASE_OFFSET);
976 }
977 }
978
979
980
981
982
983
984
985 public static short toShortUnsafe(byte[] bytes, int offset) {
986 if (UnsafeComparer.littleEndian) {
987 return Short.reverseBytes(UnsafeComparer.theUnsafe.getShort(bytes,
988 (long) offset + UnsafeComparer.BYTE_ARRAY_BASE_OFFSET));
989 } else {
990 return UnsafeComparer.theUnsafe.getShort(bytes,
991 (long) offset + UnsafeComparer.BYTE_ARRAY_BASE_OFFSET);
992 }
993 }
994
995
996
997
998
999
1000
1001 public static long toLongUnsafe(byte[] bytes, int offset) {
1002 if (UnsafeComparer.littleEndian) {
1003 return Long.reverseBytes(UnsafeComparer.theUnsafe.getLong(bytes,
1004 (long) offset + UnsafeComparer.BYTE_ARRAY_BASE_OFFSET));
1005 } else {
1006 return UnsafeComparer.theUnsafe.getLong(bytes,
1007 (long) offset + UnsafeComparer.BYTE_ARRAY_BASE_OFFSET);
1008 }
1009 }
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020 public static int readAsInt(byte[] bytes, int offset, final int length) {
1021 if (offset + length > bytes.length) {
1022 throw new IllegalArgumentException("offset (" + offset + ") + length (" + length
1023 + ") exceed the" + " capacity of the array: " + bytes.length);
1024 }
1025 int n = 0;
1026 for(int i = offset; i < (offset + length); i++) {
1027 n <<= 8;
1028 n ^= bytes[i] & 0xFF;
1029 }
1030 return n;
1031 }
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042 public static int putInt(byte[] bytes, int offset, int val) {
1043 if (bytes.length - offset < SIZEOF_INT) {
1044 throw new IllegalArgumentException("Not enough room to put an int at"
1045 + " offset " + offset + " in a " + bytes.length + " byte array");
1046 }
1047 if (UNSAFE_UNALIGNED) {
1048 return putIntUnsafe(bytes, offset, val);
1049 } else {
1050 for(int i= offset + 3; i > offset; i--) {
1051 bytes[i] = (byte) val;
1052 val >>>= 8;
1053 }
1054 bytes[offset] = (byte) val;
1055 return offset + SIZEOF_INT;
1056 }
1057 }
1058
1059
1060
1061
1062
1063
1064
1065
1066 public static int putIntUnsafe(byte[] bytes, int offset, int val)
1067 {
1068 if (UnsafeComparer.littleEndian) {
1069 val = Integer.reverseBytes(val);
1070 }
1071 UnsafeComparer.theUnsafe.putInt(bytes, (long) offset +
1072 UnsafeComparer.BYTE_ARRAY_BASE_OFFSET , val);
1073 return offset + SIZEOF_INT;
1074 }
1075
1076
1077
1078
1079
1080
1081 public static byte[] toBytes(short val) {
1082 byte[] b = new byte[SIZEOF_SHORT];
1083 b[1] = (byte) val;
1084 val >>= 8;
1085 b[0] = (byte) val;
1086 return b;
1087 }
1088
1089
1090
1091
1092
1093
1094 public static short toShort(byte[] bytes) {
1095 return toShort(bytes, 0, SIZEOF_SHORT);
1096 }
1097
1098
1099
1100
1101
1102
1103
1104 public static short toShort(byte[] bytes, int offset) {
1105 return toShort(bytes, offset, SIZEOF_SHORT);
1106 }
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117 public static short toShort(byte[] bytes, int offset, final int length) {
1118 if (length != SIZEOF_SHORT || offset + length > bytes.length) {
1119 throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_SHORT);
1120 }
1121 if (UNSAFE_UNALIGNED) {
1122 return toShortUnsafe(bytes, offset);
1123 } else {
1124 short n = 0;
1125 n = (short) ((n ^ bytes[offset]) & 0xFF);
1126 n = (short) (n << 8);
1127 n = (short) ((n ^ bytes[offset+1]) & 0xFF);
1128 return n;
1129 }
1130 }
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141 public static byte[] getBytes(ByteBuffer buf) {
1142 return readBytes(buf.duplicate());
1143 }
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154 public static int putShort(byte[] bytes, int offset, short val) {
1155 if (bytes.length - offset < SIZEOF_SHORT) {
1156 throw new IllegalArgumentException("Not enough room to put a short at"
1157 + " offset " + offset + " in a " + bytes.length + " byte array");
1158 }
1159 if (UNSAFE_UNALIGNED) {
1160 return putShortUnsafe(bytes, offset, val);
1161 } else {
1162 bytes[offset+1] = (byte) val;
1163 val >>= 8;
1164 bytes[offset] = (byte) val;
1165 return offset + SIZEOF_SHORT;
1166 }
1167 }
1168
1169
1170
1171
1172
1173
1174
1175
1176 public static int putShortUnsafe(byte[] bytes, int offset, short val)
1177 {
1178 if (UnsafeComparer.littleEndian) {
1179 val = Short.reverseBytes(val);
1180 }
1181 UnsafeComparer.theUnsafe.putShort(bytes, (long) offset +
1182 UnsafeComparer.BYTE_ARRAY_BASE_OFFSET , val);
1183 return offset + SIZEOF_SHORT;
1184 }
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198 public static int putAsShort(byte[] bytes, int offset, int val) {
1199 if (bytes.length - offset < SIZEOF_SHORT) {
1200 throw new IllegalArgumentException("Not enough room to put a short at"
1201 + " offset " + offset + " in a " + bytes.length + " byte array");
1202 }
1203 bytes[offset+1] = (byte) val;
1204 val >>= 8;
1205 bytes[offset] = (byte) val;
1206 return offset + SIZEOF_SHORT;
1207 }
1208
1209
1210
1211
1212
1213
1214
1215 public static byte[] toBytes(BigDecimal val) {
1216 byte[] valueBytes = val.unscaledValue().toByteArray();
1217 byte[] result = new byte[valueBytes.length + SIZEOF_INT];
1218 int offset = putInt(result, 0, val.scale());
1219 putBytes(result, offset, valueBytes, 0, valueBytes.length);
1220 return result;
1221 }
1222
1223
1224
1225
1226
1227
1228
1229
1230 public static BigDecimal toBigDecimal(byte[] bytes) {
1231 return toBigDecimal(bytes, 0, bytes.length);
1232 }
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242 public static BigDecimal toBigDecimal(byte[] bytes, int offset, final int length) {
1243 if (bytes == null || length < SIZEOF_INT + 1 ||
1244 (offset + length > bytes.length)) {
1245 return null;
1246 }
1247
1248 int scale = toInt(bytes, offset);
1249 byte[] tcBytes = new byte[length - SIZEOF_INT];
1250 System.arraycopy(bytes, offset + SIZEOF_INT, tcBytes, 0, length - SIZEOF_INT);
1251 return new BigDecimal(new BigInteger(tcBytes), scale);
1252 }
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262 public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) {
1263 if (bytes == null) {
1264 return offset;
1265 }
1266
1267 byte[] valueBytes = val.unscaledValue().toByteArray();
1268 byte[] result = new byte[valueBytes.length + SIZEOF_INT];
1269 offset = putInt(result, offset, val.scale());
1270 return putBytes(result, offset, valueBytes, 0, valueBytes.length);
1271 }
1272
1273
1274
1275
1276
1277 public static byte [] vintToBytes(final long vint) {
1278 long i = vint;
1279 int size = WritableUtils.getVIntSize(i);
1280 byte [] result = new byte[size];
1281 int offset = 0;
1282 if (i >= -112 && i <= 127) {
1283 result[offset] = (byte) i;
1284 return result;
1285 }
1286
1287 int len = -112;
1288 if (i < 0) {
1289 i ^= -1L;
1290 len = -120;
1291 }
1292
1293 long tmp = i;
1294 while (tmp != 0) {
1295 tmp = tmp >> 8;
1296 len--;
1297 }
1298
1299 result[offset++] = (byte) len;
1300
1301 len = (len < -120) ? -(len + 120) : -(len + 112);
1302
1303 for (int idx = len; idx != 0; idx--) {
1304 int shiftbits = (idx - 1) * 8;
1305 long mask = 0xFFL << shiftbits;
1306 result[offset++] = (byte)((i & mask) >> shiftbits);
1307 }
1308 return result;
1309 }
1310
1311
1312
1313
1314
1315 public static long bytesToVint(final byte [] buffer) {
1316 int offset = 0;
1317 byte firstByte = buffer[offset++];
1318 int len = WritableUtils.decodeVIntSize(firstByte);
1319 if (len == 1) {
1320 return firstByte;
1321 }
1322 long i = 0;
1323 for (int idx = 0; idx < len-1; idx++) {
1324 byte b = buffer[offset++];
1325 i = i << 8;
1326 i = i | (b & 0xFF);
1327 }
1328 return (WritableUtils.isNegativeVInt(firstByte) ? ~i : i);
1329 }
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341 @Deprecated
1342 public static long readVLong(final byte [] buffer, final int offset)
1343 throws IOException {
1344 return readAsVLong(buffer, offset);
1345 }
1346
1347
1348
1349
1350
1351
1352
1353 public static long readAsVLong(final byte [] buffer, final int offset) {
1354 byte firstByte = buffer[offset];
1355 int len = WritableUtils.decodeVIntSize(firstByte);
1356 if (len == 1) {
1357 return firstByte;
1358 }
1359 long i = 0;
1360 for (int idx = 0; idx < len-1; idx++) {
1361 byte b = buffer[offset + 1 + idx];
1362 i = i << 8;
1363 i = i | (b & 0xFF);
1364 }
1365 return (WritableUtils.isNegativeVInt(firstByte) ? ~i : i);
1366 }
1367
1368
1369
1370
1371
1372
1373 public static int compareTo(final byte [] left, final byte [] right) {
1374 return LexicographicalComparerHolder.BEST_COMPARER.
1375 compareTo(left, 0, left.length, right, 0, right.length);
1376 }
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389 public static int compareTo(byte[] buffer1, int offset1, int length1,
1390 byte[] buffer2, int offset2, int length2) {
1391 return LexicographicalComparerHolder.BEST_COMPARER.
1392 compareTo(buffer1, offset1, length1, buffer2, offset2, length2);
1393 }
1394
1395 interface Comparer<T> {
1396 int compareTo(
1397 T buffer1, int offset1, int length1, T buffer2, int offset2, int length2
1398 );
1399 }
1400
1401 @VisibleForTesting
1402 static Comparer<byte[]> lexicographicalComparerJavaImpl() {
1403 return LexicographicalComparerHolder.PureJavaComparer.INSTANCE;
1404 }
1405
1406
1407
1408
1409
1410
1411
1412
1413 @VisibleForTesting
1414 static class LexicographicalComparerHolder {
1415 static final String UNSAFE_COMPARER_NAME =
1416 LexicographicalComparerHolder.class.getName() + "$UnsafeComparer";
1417
1418 static final Comparer<byte[]> BEST_COMPARER = getBestComparer();
1419
1420
1421
1422
1423 static Comparer<byte[]> getBestComparer() {
1424 try {
1425 Class<?> theClass = Class.forName(UNSAFE_COMPARER_NAME);
1426
1427
1428 @SuppressWarnings("unchecked")
1429 Comparer<byte[]> comparer =
1430 (Comparer<byte[]>) theClass.getEnumConstants()[0];
1431 return comparer;
1432 } catch (Throwable t) {
1433 return lexicographicalComparerJavaImpl();
1434 }
1435 }
1436
1437 enum PureJavaComparer implements Comparer<byte[]> {
1438 INSTANCE;
1439
1440 @Override
1441 public int compareTo(byte[] buffer1, int offset1, int length1,
1442 byte[] buffer2, int offset2, int length2) {
1443
1444 if (buffer1 == buffer2 &&
1445 offset1 == offset2 &&
1446 length1 == length2) {
1447 return 0;
1448 }
1449
1450 int end1 = offset1 + length1;
1451 int end2 = offset2 + length2;
1452 for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {
1453 int a = (buffer1[i] & 0xff);
1454 int b = (buffer2[j] & 0xff);
1455 if (a != b) {
1456 return a - b;
1457 }
1458 }
1459 return length1 - length2;
1460 }
1461 }
1462
1463 @VisibleForTesting
1464 enum UnsafeComparer implements Comparer<byte[]> {
1465 INSTANCE;
1466
1467 static final Unsafe theUnsafe;
1468
1469
1470 static final int BYTE_ARRAY_BASE_OFFSET;
1471
1472 static {
1473 if (UNSAFE_UNALIGNED) {
1474 theUnsafe = UnsafeAccess.theUnsafe;
1475 } else {
1476
1477
1478 throw new Error();
1479 }
1480
1481 BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
1482
1483
1484 if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
1485 throw new AssertionError();
1486 }
1487 }
1488
1489 static final boolean littleEndian =
1490 ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN);
1491
1492
1493
1494
1495
1496
1497
1498
1499 static boolean lessThanUnsignedLong(long x1, long x2) {
1500 if (littleEndian) {
1501 x1 = Long.reverseBytes(x1);
1502 x2 = Long.reverseBytes(x2);
1503 }
1504 return (x1 + Long.MIN_VALUE) < (x2 + Long.MIN_VALUE);
1505 }
1506
1507
1508
1509
1510
1511
1512
1513
1514 static boolean lessThanUnsignedInt(int x1, int x2) {
1515 if (littleEndian) {
1516 x1 = Integer.reverseBytes(x1);
1517 x2 = Integer.reverseBytes(x2);
1518 }
1519 return (x1 & 0xffffffffL) < (x2 & 0xffffffffL);
1520 }
1521
1522
1523
1524
1525
1526
1527
1528
1529 static boolean lessThanUnsignedShort(short x1, short x2) {
1530 if (littleEndian) {
1531 x1 = Short.reverseBytes(x1);
1532 x2 = Short.reverseBytes(x2);
1533 }
1534 return (x1 & 0xffff) < (x2 & 0xffff);
1535 }
1536
1537
1538
1539
1540
1541 public static boolean isAvailable()
1542 {
1543 return theUnsafe != null;
1544 }
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557 @Override
1558 public int compareTo(byte[] buffer1, int offset1, int length1,
1559 byte[] buffer2, int offset2, int length2) {
1560
1561
1562 if (buffer1 == buffer2 &&
1563 offset1 == offset2 &&
1564 length1 == length2) {
1565 return 0;
1566 }
1567 final int stride = 8;
1568 final int minLength = Math.min(length1, length2);
1569 int strideLimit = minLength & ~(stride - 1);
1570 final long offset1Adj = (long) offset1 + BYTE_ARRAY_BASE_OFFSET;
1571 final long offset2Adj = (long) offset2 + BYTE_ARRAY_BASE_OFFSET;
1572 int i;
1573
1574
1575
1576
1577
1578 for (i = 0; i < strideLimit; i += stride) {
1579 long lw = theUnsafe.getLong(buffer1, offset1Adj + (long) i);
1580 long rw = theUnsafe.getLong(buffer2, offset2Adj + (long) i);
1581 if (lw != rw) {
1582 if (!littleEndian) {
1583 return ((lw + Long.MIN_VALUE) < (rw + Long.MIN_VALUE)) ? -1 : 1;
1584 }
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594 int n = Long.numberOfTrailingZeros(lw ^ rw) & ~0x7;
1595 return ((int) ((lw >>> n) & 0xFF)) - ((int) ((rw >>> n) & 0xFF));
1596 }
1597 }
1598
1599
1600 for (; i < minLength; i++) {
1601 int a = (buffer1[offset1 + i] & 0xFF);
1602 int b = (buffer2[offset2 + i] & 0xFF);
1603 if (a != b) {
1604 return a - b;
1605 }
1606 }
1607 return length1 - length2;
1608 }
1609 }
1610 }
1611
1612
1613
1614
1615
1616
1617 public static boolean equals(final byte [] left, final byte [] right) {
1618
1619
1620 if (left == right) return true;
1621 if (left == null || right == null) return false;
1622 if (left.length != right.length) return false;
1623 if (left.length == 0) return true;
1624
1625
1626
1627
1628 if (left[left.length - 1] != right[right.length - 1]) return false;
1629
1630 return compareTo(left, right) == 0;
1631 }
1632
1633 public static boolean equals(final byte[] left, int leftOffset, int leftLen,
1634 final byte[] right, int rightOffset, int rightLen) {
1635
1636 if (left == right &&
1637 leftOffset == rightOffset &&
1638 leftLen == rightLen) {
1639 return true;
1640 }
1641
1642 if (leftLen != rightLen) {
1643 return false;
1644 }
1645 if (leftLen == 0) {
1646 return true;
1647 }
1648
1649
1650
1651
1652 if (left[leftOffset + leftLen - 1] != right[rightOffset + rightLen - 1]) return false;
1653
1654 return LexicographicalComparerHolder.BEST_COMPARER.
1655 compareTo(left, leftOffset, leftLen, right, rightOffset, rightLen) == 0;
1656 }
1657
1658
1659
1660
1661
1662
1663
1664 public static boolean equals(byte[] a, ByteBuffer buf) {
1665 if (a == null) return buf == null;
1666 if (buf == null) return false;
1667 if (a.length != buf.remaining()) return false;
1668
1669
1670 ByteBuffer b = buf.duplicate();
1671 for (byte anA : a) {
1672 if (anA != b.get()) {
1673 return false;
1674 }
1675 }
1676 return true;
1677 }
1678
1679
1680
1681
1682
1683
1684 public static boolean startsWith(byte[] bytes, byte[] prefix) {
1685 return bytes != null && prefix != null &&
1686 bytes.length >= prefix.length &&
1687 LexicographicalComparerHolder.BEST_COMPARER.
1688 compareTo(bytes, 0, prefix.length, prefix, 0, prefix.length) == 0;
1689 }
1690
1691
1692
1693
1694
1695
1696
1697 public static int hashCode(final byte [] b) {
1698 return hashCode(b, b.length);
1699 }
1700
1701
1702
1703
1704
1705
1706
1707
1708 public static int hashCode(final byte [] b, final int length) {
1709 return WritableComparator.hashBytes(b, length);
1710 }
1711
1712
1713
1714
1715
1716
1717 public static Integer mapKey(final byte [] b) {
1718 return hashCode(b);
1719 }
1720
1721
1722
1723
1724
1725
1726
1727 public static Integer mapKey(final byte [] b, final int length) {
1728 return hashCode(b, length);
1729 }
1730
1731
1732
1733
1734
1735
1736 public static byte [] add(final byte [] a, final byte [] b) {
1737 return add(a, b, EMPTY_BYTE_ARRAY);
1738 }
1739
1740
1741
1742
1743
1744
1745
1746 public static byte [] add(final byte [] a, final byte [] b, final byte [] c) {
1747 byte [] result = new byte[a.length + b.length + c.length];
1748 System.arraycopy(a, 0, result, 0, a.length);
1749 System.arraycopy(b, 0, result, a.length, b.length);
1750 System.arraycopy(c, 0, result, a.length + b.length, c.length);
1751 return result;
1752 }
1753
1754
1755
1756
1757
1758 public static byte [] add(final byte [][] arrays) {
1759 int length = 0;
1760 for (int i = 0; i < arrays.length; i++) {
1761 length += arrays[i].length;
1762 }
1763 byte [] result = new byte[length];
1764 int index = 0;
1765 for (int i = 0; i < arrays.length; i++) {
1766 System.arraycopy(arrays[i], 0, result, index, arrays[i].length);
1767 index += arrays[i].length;
1768 }
1769 return result;
1770 }
1771
1772
1773
1774
1775
1776
1777 public static byte [] head(final byte [] a, final int length) {
1778 if (a.length < length) {
1779 return null;
1780 }
1781 byte [] result = new byte[length];
1782 System.arraycopy(a, 0, result, 0, length);
1783 return result;
1784 }
1785
1786
1787
1788
1789
1790
1791 public static byte [] tail(final byte [] a, final int length) {
1792 if (a.length < length) {
1793 return null;
1794 }
1795 byte [] result = new byte[length];
1796 System.arraycopy(a, a.length - length, result, 0, length);
1797 return result;
1798 }
1799
1800
1801
1802
1803
1804
1805 public static byte [] padHead(final byte [] a, final int length) {
1806 byte [] padding = new byte[length];
1807 for (int i = 0; i < length; i++) {
1808 padding[i] = 0;
1809 }
1810 return add(padding,a);
1811 }
1812
1813
1814
1815
1816
1817
1818 public static byte [] padTail(final byte [] a, final int length) {
1819 byte [] padding = new byte[length];
1820 for (int i = 0; i < length; i++) {
1821 padding[i] = 0;
1822 }
1823 return add(a,padding);
1824 }
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835 public static byte [][] split(final byte [] a, final byte [] b, final int num) {
1836 return split(a, b, false, num);
1837 }
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851 public static byte[][] split(final byte[] a, final byte[] b,
1852 boolean inclusive, final int num) {
1853 byte[][] ret = new byte[num + 2][];
1854 int i = 0;
1855 Iterable<byte[]> iter = iterateOnSplits(a, b, inclusive, num);
1856 if (iter == null)
1857 return null;
1858 for (byte[] elem : iter) {
1859 ret[i++] = elem;
1860 }
1861 return ret;
1862 }
1863
1864
1865
1866
1867 public static Iterable<byte[]> iterateOnSplits(final byte[] a,
1868 final byte[] b, final int num)
1869 {
1870 return iterateOnSplits(a, b, false, num);
1871 }
1872
1873
1874
1875
1876 public static Iterable<byte[]> iterateOnSplits(
1877 final byte[] a, final byte[]b, boolean inclusive, final int num)
1878 {
1879 byte [] aPadded;
1880 byte [] bPadded;
1881 if (a.length < b.length) {
1882 aPadded = padTail(a, b.length - a.length);
1883 bPadded = b;
1884 } else if (b.length < a.length) {
1885 aPadded = a;
1886 bPadded = padTail(b, a.length - b.length);
1887 } else {
1888 aPadded = a;
1889 bPadded = b;
1890 }
1891 if (compareTo(aPadded,bPadded) >= 0) {
1892 throw new IllegalArgumentException("b <= a");
1893 }
1894 if (num <= 0) {
1895 throw new IllegalArgumentException("num cannot be <= 0");
1896 }
1897 byte [] prependHeader = {1, 0};
1898 final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
1899 final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
1900 BigInteger diffBI = stopBI.subtract(startBI);
1901 if (inclusive) {
1902 diffBI = diffBI.add(BigInteger.ONE);
1903 }
1904 final BigInteger splitsBI = BigInteger.valueOf(num + 1);
1905
1906 if(diffBI.compareTo(splitsBI) < 0) {
1907 byte[] aPaddedAdditional = new byte[aPadded.length+1];
1908 byte[] bPaddedAdditional = new byte[bPadded.length+1];
1909 for (int i = 0; i < aPadded.length; i++){
1910 aPaddedAdditional[i] = aPadded[i];
1911 }
1912 for (int j = 0; j < bPadded.length; j++){
1913 bPaddedAdditional[j] = bPadded[j];
1914 }
1915 aPaddedAdditional[aPadded.length] = 0;
1916 bPaddedAdditional[bPadded.length] = 0;
1917 return iterateOnSplits(aPaddedAdditional, bPaddedAdditional, inclusive, num);
1918 }
1919 final BigInteger intervalBI;
1920 try {
1921 intervalBI = diffBI.divide(splitsBI);
1922 } catch(Exception e) {
1923 LOG.error("Exception caught during division", e);
1924 return null;
1925 }
1926
1927 final Iterator<byte[]> iterator = new Iterator<byte[]>() {
1928 private int i = -1;
1929
1930 @Override
1931 public boolean hasNext() {
1932 return i < num+1;
1933 }
1934
1935 @Override
1936 public byte[] next() {
1937 i++;
1938 if (i == 0) return a;
1939 if (i == num + 1) return b;
1940
1941 BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
1942 byte [] padded = curBI.toByteArray();
1943 if (padded[1] == 0)
1944 padded = tail(padded, padded.length - 2);
1945 else
1946 padded = tail(padded, padded.length - 1);
1947 return padded;
1948 }
1949
1950 @Override
1951 public void remove() {
1952 throw new UnsupportedOperationException();
1953 }
1954
1955 };
1956
1957 return new Iterable<byte[]>() {
1958 @Override
1959 public Iterator<byte[]> iterator() {
1960 return iterator;
1961 }
1962 };
1963 }
1964
1965
1966
1967
1968
1969
1970 public static int hashCode(byte[] bytes, int offset, int length) {
1971 int hash = 1;
1972 for (int i = offset; i < offset + length; i++)
1973 hash = (31 * hash) + (int) bytes[i];
1974 return hash;
1975 }
1976
1977
1978
1979
1980
1981 public static byte [][] toByteArrays(final String [] t) {
1982 byte [][] result = new byte[t.length][];
1983 for (int i = 0; i < t.length; i++) {
1984 result[i] = Bytes.toBytes(t[i]);
1985 }
1986 return result;
1987 }
1988
1989
1990
1991
1992
1993 public static byte[][] toBinaryByteArrays(final String[] t) {
1994 byte[][] result = new byte[t.length][];
1995 for (int i = 0; i < t.length; i++) {
1996 result[i] = Bytes.toBytesBinary(t[i]);
1997 }
1998 return result;
1999 }
2000
2001
2002
2003
2004
2005
2006 public static byte [][] toByteArrays(final String column) {
2007 return toByteArrays(toBytes(column));
2008 }
2009
2010
2011
2012
2013
2014
2015 public static byte [][] toByteArrays(final byte [] column) {
2016 byte [][] result = new byte[1][];
2017 result[0] = column;
2018 return result;
2019 }
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036 public static int binarySearch(byte [][]arr, byte []key, int offset,
2037 int length, RawComparator<?> comparator) {
2038 int low = 0;
2039 int high = arr.length - 1;
2040
2041 while (low <= high) {
2042 int mid = (low+high) >>> 1;
2043
2044
2045 int cmp = comparator.compare(key, offset, length,
2046 arr[mid], 0, arr[mid].length);
2047
2048 if (cmp > 0)
2049 low = mid + 1;
2050
2051 else if (cmp < 0)
2052 high = mid - 1;
2053
2054 else
2055 return mid;
2056 }
2057 return - (low+1);
2058 }
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074 public static int binarySearch(byte[][] arr, Cell key, RawComparator<Cell> comparator) {
2075 int low = 0;
2076 int high = arr.length - 1;
2077 KeyValue.KeyOnlyKeyValue r = new KeyValue.KeyOnlyKeyValue();
2078 while (low <= high) {
2079 int mid = (low+high) >>> 1;
2080
2081
2082 r.setKey(arr[mid], 0, arr[mid].length);
2083 int cmp = comparator.compare(key, r);
2084
2085 if (cmp > 0)
2086 low = mid + 1;
2087
2088 else if (cmp < 0)
2089 high = mid - 1;
2090
2091 else
2092 return mid;
2093 }
2094 return - (low+1);
2095 }
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105 public static byte [] incrementBytes(byte[] value, long amount)
2106 {
2107 byte[] val = value;
2108 if (val.length < SIZEOF_LONG) {
2109
2110 byte [] newvalue;
2111 if (val[0] < 0) {
2112 newvalue = new byte[]{-1, -1, -1, -1, -1, -1, -1, -1};
2113 } else {
2114 newvalue = new byte[SIZEOF_LONG];
2115 }
2116 System.arraycopy(val, 0, newvalue, newvalue.length - val.length,
2117 val.length);
2118 val = newvalue;
2119 } else if (val.length > SIZEOF_LONG) {
2120 throw new IllegalArgumentException("Increment Bytes - value too big: " +
2121 val.length);
2122 }
2123 if(amount == 0) return val;
2124 if(val[0] < 0){
2125 return binaryIncrementNeg(val, amount);
2126 }
2127 return binaryIncrementPos(val, amount);
2128 }
2129
2130
2131 private static byte [] binaryIncrementPos(byte [] value, long amount) {
2132 long amo = amount;
2133 int sign = 1;
2134 if (amount < 0) {
2135 amo = -amount;
2136 sign = -1;
2137 }
2138 for(int i=0;i<value.length;i++) {
2139 int cur = ((int)amo % 256) * sign;
2140 amo = (amo >> 8);
2141 int val = value[value.length-i-1] & 0x0ff;
2142 int total = val + cur;
2143 if(total > 255) {
2144 amo += sign;
2145 total %= 256;
2146 } else if (total < 0) {
2147 amo -= sign;
2148 }
2149 value[value.length-i-1] = (byte)total;
2150 if (amo == 0) return value;
2151 }
2152 return value;
2153 }
2154
2155
2156 private static byte [] binaryIncrementNeg(byte [] value, long amount) {
2157 long amo = amount;
2158 int sign = 1;
2159 if (amount < 0) {
2160 amo = -amount;
2161 sign = -1;
2162 }
2163 for(int i=0;i<value.length;i++) {
2164 int cur = ((int)amo % 256) * sign;
2165 amo = (amo >> 8);
2166 int val = ((~value[value.length-i-1]) & 0x0ff) + 1;
2167 int total = cur - val;
2168 if(total >= 0) {
2169 amo += sign;
2170 } else if (total < -256) {
2171 amo -= sign;
2172 total %= 256;
2173 }
2174 value[value.length-i-1] = (byte)total;
2175 if (amo == 0) return value;
2176 }
2177 return value;
2178 }
2179
2180
2181
2182
2183 public static void writeStringFixedSize(final DataOutput out, String s,
2184 int size) throws IOException {
2185 byte[] b = toBytes(s);
2186 if (b.length > size) {
2187 throw new IOException("Trying to write " + b.length + " bytes (" +
2188 toStringBinary(b) + ") into a field of length " + size);
2189 }
2190
2191 out.writeBytes(s);
2192 for (int i = 0; i < size - s.length(); ++i)
2193 out.writeByte(0);
2194 }
2195
2196
2197
2198
2199 public static String readStringFixedSize(final DataInput in, int size)
2200 throws IOException {
2201 byte[] b = new byte[size];
2202 in.readFully(b);
2203 int n = b.length;
2204 while (n > 0 && b[n - 1] == 0)
2205 --n;
2206
2207 return toString(b, 0, n);
2208 }
2209
2210
2211
2212
2213
2214
2215
2216 public static byte [] copy(byte [] bytes) {
2217 if (bytes == null) return null;
2218 byte [] result = new byte[bytes.length];
2219 System.arraycopy(bytes, 0, result, 0, bytes.length);
2220 return result;
2221 }
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231 public static byte [] copy(byte [] bytes, final int offset, final int length) {
2232 if (bytes == null) return null;
2233 byte [] result = new byte[length];
2234 System.arraycopy(bytes, offset, result, 0, length);
2235 return result;
2236 }
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248 public static int unsignedBinarySearch(byte[] a, int fromIndex, int toIndex, byte key) {
2249 int unsignedKey = key & 0xff;
2250 int low = fromIndex;
2251 int high = toIndex - 1;
2252
2253 while (low <= high) {
2254 int mid = (low + high) >>> 1;
2255 int midVal = a[mid] & 0xff;
2256
2257 if (midVal < unsignedKey) {
2258 low = mid + 1;
2259 } else if (midVal > unsignedKey) {
2260 high = mid - 1;
2261 } else {
2262 return mid;
2263 }
2264 }
2265 return -(low + 1);
2266 }
2267
2268
2269
2270
2271
2272
2273
2274
2275 public static byte[] unsignedCopyAndIncrement(final byte[] input) {
2276 byte[] copy = copy(input);
2277 if (copy == null) {
2278 throw new IllegalArgumentException("cannot increment null array");
2279 }
2280 for (int i = copy.length - 1; i >= 0; --i) {
2281 if (copy[i] == -1) {
2282 copy[i] = 0;
2283 } else {
2284 ++copy[i];
2285 return copy;
2286 }
2287 }
2288
2289 byte[] out = new byte[copy.length + 1];
2290 out[0] = 1;
2291 System.arraycopy(copy, 0, out, 1, copy.length);
2292 return out;
2293 }
2294
2295 public static boolean equals(List<byte[]> a, List<byte[]> b) {
2296 if (a == null) {
2297 if (b == null) {
2298 return true;
2299 }
2300 return false;
2301 }
2302 if (b == null) {
2303 return false;
2304 }
2305 if (a.size() != b.size()) {
2306 return false;
2307 }
2308 for (int i = 0; i < a.size(); ++i) {
2309 if (!Bytes.equals(a.get(i), b.get(i))) {
2310 return false;
2311 }
2312 }
2313 return true;
2314 }
2315
2316 public static boolean isSorted(Collection<byte[]> arrays) {
2317 byte[] previous = new byte[0];
2318 for (byte[] array : IterableUtils.nullSafe(arrays)) {
2319 if (Bytes.compareTo(previous, array) > 0) {
2320 return false;
2321 }
2322 previous = array;
2323 }
2324 return true;
2325 }
2326
2327 public static List<byte[]> getUtf8ByteArrays(List<String> strings) {
2328 List<byte[]> byteArrays = Lists.newArrayListWithCapacity(CollectionUtils.nullSafeSize(strings));
2329 for (String s : IterableUtils.nullSafe(strings)) {
2330 byteArrays.add(Bytes.toBytes(s));
2331 }
2332 return byteArrays;
2333 }
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344 public static int indexOf(byte[] array, byte target) {
2345 for (int i = 0; i < array.length; i++) {
2346 if (array[i] == target) {
2347 return i;
2348 }
2349 }
2350 return -1;
2351 }
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364 public static int indexOf(byte[] array, byte[] target) {
2365 checkNotNull(array, "array");
2366 checkNotNull(target, "target");
2367 if (target.length == 0) {
2368 return 0;
2369 }
2370
2371 outer:
2372 for (int i = 0; i < array.length - target.length + 1; i++) {
2373 for (int j = 0; j < target.length; j++) {
2374 if (array[i + j] != target[j]) {
2375 continue outer;
2376 }
2377 }
2378 return i;
2379 }
2380 return -1;
2381 }
2382
2383
2384
2385
2386
2387
2388 public static boolean contains(byte[] array, byte target) {
2389 return indexOf(array, target) > -1;
2390 }
2391
2392
2393
2394
2395
2396
2397 public static boolean contains(byte[] array, byte[] target) {
2398 return indexOf(array, target) > -1;
2399 }
2400
2401
2402
2403
2404
2405 public static void zero(byte[] b) {
2406 zero(b, 0, b.length);
2407 }
2408
2409
2410
2411
2412
2413
2414
2415 public static void zero(byte[] b, int offset, int length) {
2416 checkPositionIndex(offset, b.length, "offset");
2417 checkArgument(length > 0, "length must be greater than 0");
2418 checkPositionIndex(offset + length, b.length, "offset + length");
2419 Arrays.fill(b, offset, offset + length, (byte) 0);
2420 }
2421
2422 private static final SecureRandom RNG = new SecureRandom();
2423
2424
2425
2426
2427
2428 public static void random(byte[] b) {
2429 RNG.nextBytes(b);
2430 }
2431
2432
2433
2434
2435
2436
2437
2438 public static void random(byte[] b, int offset, int length) {
2439 checkPositionIndex(offset, b.length, "offset");
2440 checkArgument(length > 0, "length must be greater than 0");
2441 checkPositionIndex(offset + length, b.length, "offset + length");
2442 byte[] buf = new byte[length];
2443 RNG.nextBytes(buf);
2444 System.arraycopy(buf, 0, b, offset, length);
2445 }
2446
2447
2448
2449
2450
2451
2452 public static byte[] createMaxByteArray(int maxByteCount) {
2453 byte[] maxByteArray = new byte[maxByteCount];
2454 for (int i = 0; i < maxByteArray.length; i++) {
2455 maxByteArray[i] = (byte) 0xff;
2456 }
2457 return maxByteArray;
2458 }
2459
2460
2461
2462
2463
2464
2465
2466 public static byte[] multiple(byte[] srcBytes, int multiNum) {
2467 if (multiNum <= 0) {
2468 return new byte[0];
2469 }
2470 byte[] result = new byte[srcBytes.length * multiNum];
2471 for (int i = 0; i < multiNum; i++) {
2472 System.arraycopy(srcBytes, 0, result, i * srcBytes.length,
2473 srcBytes.length);
2474 }
2475 return result;
2476 }
2477
2478 private static final char[] HEX_CHARS = {
2479 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
2480 };
2481
2482
2483
2484
2485 public static String toHex(byte[] b, int offset, int length) {
2486 checkArgument(length <= Integer.MAX_VALUE / 2);
2487 int numChars = length * 2;
2488 char[] ch = new char[numChars];
2489 for (int i = 0; i < numChars; i += 2)
2490 {
2491 byte d = b[offset + i/2];
2492 ch[i] = HEX_CHARS[(d >> 4) & 0x0F];
2493 ch[i+1] = HEX_CHARS[d & 0x0F];
2494 }
2495 return new String(ch);
2496 }
2497
2498
2499
2500
2501 public static String toHex(byte[] b) {
2502 return toHex(b, 0, b.length);
2503 }
2504
2505 private static int hexCharToNibble(char ch) {
2506 if (ch <= '9' && ch >= '0') {
2507 return ch - '0';
2508 } else if (ch >= 'a' && ch <= 'f') {
2509 return ch - 'a' + 10;
2510 } else if (ch >= 'A' && ch <= 'F') {
2511 return ch - 'A' + 10;
2512 }
2513 throw new IllegalArgumentException("Invalid hex char: " + ch);
2514 }
2515
2516 private static byte hexCharsToByte(char c1, char c2) {
2517 return (byte) ((hexCharToNibble(c1) << 4) | hexCharToNibble(c2));
2518 }
2519
2520
2521
2522
2523
2524
2525 public static byte[] fromHex(String hex) {
2526 checkArgument(hex.length() % 2 == 0, "length must be a multiple of 2");
2527 int len = hex.length();
2528 byte[] b = new byte[len / 2];
2529 for (int i = 0; i < len; i += 2) {
2530 b[i / 2] = hexCharsToByte(hex.charAt(i),hex.charAt(i+1));
2531 }
2532 return b;
2533 }
2534
2535 }