-
Notifications
You must be signed in to change notification settings - Fork 33
/
Bytes.java
2253 lines (2061 loc) · 84.9 KB
/
Bytes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 Patrick Favre-Bulle
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package at.favre.lib.bytes;
import java.io.*;
import java.math.BigInteger;
import java.nio.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.text.Normalizer;
import java.util.*;
/**
* "Bytes" is wrapper class for a byte-array that allows a lot of convenience operations on it:
* <ul>
* <li>Creation from various source: arrays, primitives, parsed or random</li>
* <li>Encoding in many formats: hex, base64, etc.</li>
* <li>Helper functions like: indexOf, count, entropy</li>
* <li>Transformations like: append, reverse, xor, and, resize, ...</li>
* <li>Conversation to other types: primitives, List, object array, ByteBuffer, BigInteger, ...</li>
* <li>Validation: built-in or provided</li>
* <li>Making it mutable or read-only</li>
* </ul>
* <p>
* It supports byte ordering (little/big endianness).
* <p>
* This class is immutable as long as the internal array is not changed from outside (which can't be assured, when
* using <code>wrap()</code>). It is possible to create a mutable version (see {@link MutableBytes}).
* <p>
* <strong>Example:</strong>
* <pre>
* Bytes b = Bytes.from(array).mutable();
* b.not();
* System.out.println(b.encodeHex());
* </pre>
*
* <h3>Comparable</h3>
* The implemented comparator treats the bytes as signed bytes. If you want to sort, treating each byte as unsigned,
* use {@link BytesTransformers#sortUnsigned()}.
*/
@SuppressWarnings("WeakerAccess")
public class Bytes implements Comparable<Bytes>, Serializable, Iterable<Byte> {
private static final Bytes EMPTY = Bytes.wrap(new byte[0]);
/* FACTORY ***************************************************************************************************/
/**
* Creates a new instance with an empty array filled with zeros.
*
* @param length of the internal array
* @return new instance
*/
public static Bytes allocate(int length) {
return allocate(length, (byte) 0);
}
/**
* Creates a new instance with an empty array filled with given defaultValue
*
* @param length of the internal array
* @param defaultValue to fill with
* @return new instance
*/
public static Bytes allocate(int length, byte defaultValue) {
if (length == 0) return empty();
byte[] array = new byte[length];
if (defaultValue != 0) {
Arrays.fill(array, defaultValue);
}
return wrap(array);
}
/**
* Creates a Byte instance with an internal empty byte array. Same as calling {@link #allocate(int)} with 0.
*
* @return the empty instance (always the same reference
*/
public static Bytes empty() {
return EMPTY;
}
/**
* Creates a new reference backed by the same byte array.
* Inherits all attributes (readonly, etc.)
*
* @param bytes to use as template
* @return new instance
*/
public static Bytes wrap(Bytes bytes) {
return wrap(Objects.requireNonNull(bytes, "passed Byte instance must not be null").internalArray(), bytes.byteOrder);
}
/**
* Creates a new instance with given byte array.
* <p>
* The new instance will be backed by the given byte array;
* that is, modifications to the bytes will cause the array to be modified
* and vice versa.
* <p>
* If given array is null, a zero length byte array will be created and used instead.
*
* @param array to use directly or zero length byte array
* @return new instance
*/
public static Bytes wrapNullSafe(byte[] array) {
return array != null ? wrap(array) : empty();
}
/**
* Creates a new instance with given byte array.
* <p>
* The new instance will be backed by the given byte array;
* that is, modifications to the bytes will cause the array to be modified
* and vice versa.
*
* @param array to use directly
* @return new instance
*/
public static Bytes wrap(byte[] array) {
return wrap(array, ByteOrder.BIG_ENDIAN);
}
/**
* Creates a new instance with given byte array.
* <p>
* The new instance will be backed by the given byte array;
* that is, modifications to the bytes will cause the array to be modified
* and vice versa.
*
* @param array to use directly
* @param byteOrder the byte order of passed array
* @return new instance
*/
public static Bytes wrap(byte[] array, ByteOrder byteOrder) {
return new Bytes(Objects.requireNonNull(array, "passed array must not be null"), byteOrder);
}
/**
* Creates a new instance from given collections of single bytes.
* This will create a copy of given bytes and will not directly use given bytes or byte array.
*
* @param byteArrayToCopy must not be null and will not be used directly, but a copy
* @return new instance
*/
public static Bytes from(byte[] byteArrayToCopy) {
return wrap(Arrays.copyOf(Objects.requireNonNull(byteArrayToCopy, "must at least pass a single byte"), byteArrayToCopy.length));
}
/**
* Creates a new instance from given collections of single bytes.
* This will create a copy of given bytes and will not directly use given bytes or byte array.
* <p>
* If given array is null, a zero length byte array will be created and used instead.
*
* @param byteArrayToCopy will not be used directly, but a copy; may be null
* @return new instance
*/
public static Bytes fromNullSafe(byte[] byteArrayToCopy) {
return byteArrayToCopy != null ? from(byteArrayToCopy) : empty();
}
/**
* Creates a new instance from a slice of given array
*
* @param array to slice
* @param offset start position
* @param length length
* @return new instance
*/
public static Bytes from(byte[] array, int offset, int length) {
Objects.requireNonNull(array, "passed array must not be null");
byte[] part = new byte[length];
System.arraycopy(array, offset, part, 0, length);
return wrap(part);
}
/**
* Creates a new instance from given array of byte arrays
*
* @param moreArrays must not be null
* @return new instance
*/
public static Bytes from(byte[]... moreArrays) {
return wrap(Util.Byte.concat(moreArrays));
}
/**
* Creates a new instance from given array of byte arrays
*
* @param moreBytes must not be null
* @return new instance
*/
public static Bytes from(Bytes... moreBytes) {
Objects.requireNonNull(moreBytes, "bytes most not be null");
byte[][] bytes = new byte[moreBytes.length][];
for (int i = 0; i < moreBytes.length; i++) {
bytes[i] = moreBytes[i].array();
}
return from(bytes);
}
/**
* Creates a new instance from given collections. This will create a lot of auto-unboxing events,
* so use with care with bigger lists.
*
* @param bytesCollection to create from
* @return new instance
*/
public static Bytes from(Collection<Byte> bytesCollection) {
return wrap(Util.Converter.toArray(bytesCollection));
}
/**
* Creates a new instance from given object byte array. Will copy and unbox every element.
*
* @param boxedObjectArray to create from
* @return new instance
*/
public static Bytes from(Byte[] boxedObjectArray) {
return wrap(Util.Converter.toPrimitiveArray(boxedObjectArray));
}
/**
* Creates a new single array element array instance from given byte
*
* @param singleByte to create from
* @return new instance
*/
public static Bytes from(byte singleByte) {
return wrap(new byte[]{singleByte});
}
/**
* Creates a new instance from given collections of single bytes.
* This will create a copy of given bytes and will not directly use given bytes or byte array.
*
* @param firstByte must not be null and will not be used directly, but a copy
* @param moreBytes more bytes vararg
* @return new instance
*/
public static Bytes from(byte firstByte, byte... moreBytes) {
return wrap(Util.Byte.concatVararg(firstByte, moreBytes));
}
/**
* Creates a new instance from given boolean.
* This will create a new single array element array instance using the convention that false is zero.
* E.g. Creates array <code>new byte[] {1}</code> if booleanValue is true and <code>new byte[] {0}</code> if
* booleanValue is false.
*
* @param booleanValue to convert (false is zero, true is one)
* @return new instance
*/
public static Bytes from(boolean booleanValue) {
return wrap(new byte[]{booleanValue ? (byte) 1 : 0});
}
/**
* Creates a new instance from given unsigned 2 byte char.
*
* @param char2Byte to create from
* @return new instance
*/
public static Bytes from(char char2Byte) {
return wrap(ByteBuffer.allocate(2).putChar(char2Byte).array());
}
/**
* Creates a new instance from given 2 byte short.
*
* @param short2Byte to create from
* @return new instance
*/
public static Bytes from(short short2Byte) {
return wrap(ByteBuffer.allocate(2).putShort(short2Byte).array());
}
/**
* Creates a new instance from given 2 byte short array.
*
* @param shortArray to create from
* @return new instance
*/
public static Bytes from(short... shortArray) {
return wrap(Util.Converter.toByteArray(Objects.requireNonNull(shortArray, "must provide at least a single short")));
}
/**
* Creates a new instance from given 4 byte integer.
*
* @param integer4byte to create from
* @return new instance
*/
public static Bytes from(int integer4byte) {
return wrap(ByteBuffer.allocate(4).putInt(integer4byte).array());
}
/**
* Creates a new instance from given 4 byte integer array.
*
* @param intArray to create from
* @return new instance
*/
public static Bytes from(int... intArray) {
return wrap(Util.Converter.toByteArray(Objects.requireNonNull(intArray, "must provide at least a single int")));
}
/**
* Creates a new instance from given 8 byte long.
*
* @param long8byte to create from
* @return new instance
*/
public static Bytes from(long long8byte) {
return wrap(ByteBuffer.allocate(8).putLong(long8byte).array());
}
/**
* Creates a new instance from given 8 byte long array.
*
* @param longArray to create from
* @return new instance
*/
public static Bytes from(long... longArray) {
return wrap(Util.Converter.toByteArray(Objects.requireNonNull(longArray, "must provide at least a single long")));
}
/**
* Creates a new instance from given 4 byte floating point number (float).
*
* @param float4byte to create from
* @return new instance
*/
public static Bytes from(float float4byte) {
return wrap(ByteBuffer.allocate(4).putFloat(float4byte).array());
}
/**
* Creates a new instance from given float array.
*
* @param floatArray to create from
* @return new instance
*/
public static Bytes from(float... floatArray) {
return wrap(Util.Converter.toByteArray(Objects.requireNonNull(floatArray, "must provide at least a single float")));
}
/**
* Creates a new instance from given 8 byte floating point number (double).
*
* @param double8Byte to create from
* @return new instance
*/
public static Bytes from(double double8Byte) {
return wrap(ByteBuffer.allocate(8).putDouble(double8Byte).array());
}
/**
* Creates a new instance from given double array.
*
* @param doubleArray to create from
* @return new instance
*/
public static Bytes from(double... doubleArray) {
return wrap(Util.Converter.toByteArray(Objects.requireNonNull(doubleArray, "must provide at least a single double")));
}
/**
* Creates a new instance from given {@link ByteBuffer}.
* Will use the same backing byte array and honour the buffer's byte order.
*
* @param buffer to get the byte array from (must not be null)
* @return new instance
*/
public static Bytes from(ByteBuffer buffer) {
return wrap(Objects.requireNonNull(buffer, "provided byte buffer must not be null").array(), buffer.order());
}
/**
* Creates a new instance from given {@link CharBuffer}.
* Will ignore buffer's byte order and use {@link ByteOrder#BIG_ENDIAN}
*
* @param buffer to get the char array from (must not be null)
* @return new instance
*/
public static Bytes from(CharBuffer buffer) {
return from(Objects.requireNonNull(buffer, "provided char buffer must not be null").array());
}
/**
* Creates a new instance from given {@link IntBuffer}.
* Will ignore buffer's byte order and use {@link ByteOrder#BIG_ENDIAN}
*
* @param buffer to get the int array from (must not be null)
* @return new instance
*/
public static Bytes from(IntBuffer buffer) {
return from(Objects.requireNonNull(buffer, "provided int buffer must not be null").array());
}
/**
* Creates a new instance from given {@link BitSet}.
*
* @param set to get the byte array from
* @return new instance
*/
public static Bytes from(BitSet set) {
return wrap(set.toByteArray());
}
/**
* Creates a new instance from given {@link BigInteger}.
*
* @param bigInteger to get the byte array from
* @return new instance
*/
public static Bytes from(BigInteger bigInteger) {
return wrap(bigInteger.toByteArray());
}
/**
* Reads given whole input stream and creates a new instance from read data
*
* @param stream to read from
* @return new instance
*/
public static Bytes from(InputStream stream) {
return wrap(Util.File.readFromStream(stream, -1));
}
/**
* Reads given input stream up to maxLength and creates a new instance from read data.
* Read maxLength is never longer than stream size (i.e. maxLength is only limiting, not assuring maxLength)
*
* @param stream to read from
* @param maxLength read to this maxLength or end of stream
* @return new instance
*/
public static Bytes from(InputStream stream, int maxLength) {
return wrap(Util.File.readFromStream(stream, maxLength));
}
/**
* Reads given {@link DataInput} and creates a new instance from read data
*
* @param dataInput to read from
* @param length how many bytes should be read
* @return new instance
*/
public static Bytes from(DataInput dataInput, int length) {
return wrap(Util.File.readFromDataInput(dataInput, length));
}
/**
* Reads given file and returns the byte content. Be aware that the whole file content will be loaded to
* memory, so be careful what to read in.
*
* @param file to read from
* @return new instance
* @throws IllegalArgumentException if file does not exist
* @throws IllegalStateException if file could not be read
*/
public static Bytes from(File file) {
return wrap(Util.File.readFromFile(file));
}
/**
* Reads given file and returns the byte content. Be aware that the whole defined file content will be loaded to
* memory, so be careful what to read in. This uses {@link java.io.RandomAccessFile} under the hood.
*
* @param file to read from
* @param offset byte offset from zero position of the file
* @param length to read from offset
* @return new instance
* @throws IllegalArgumentException if file does not exist
* @throws IllegalStateException if file could not be read
*/
public static Bytes from(File file, int offset, int length) {
return wrap(Util.File.readFromFile(file, offset, length));
}
/**
* Creates a new instance from given utf-8 encoded string
*
* @param utf8String to get the internal byte array from
* @return new instance
*/
public static Bytes from(CharSequence utf8String) {
return from(utf8String, StandardCharsets.UTF_8);
}
/**
* Creates a new instance from normalized form of given utf-8 encoded string
*
* @param utf8String to get the internal byte array from
* @param form to normalize, usually you want {@link java.text.Normalizer.Form#NFKD} for compatibility
* @return new instance
*/
public static Bytes from(CharSequence utf8String, Normalizer.Form form) {
return from(Normalizer.normalize(utf8String, form), StandardCharsets.UTF_8);
}
/**
* Creates a new instance from given string
*
* @param string to get the internal byte array from
* @param charset used to decode the string
* @return new instance
*/
public static Bytes from(CharSequence string, Charset charset) {
return wrap(Objects.requireNonNull(string, "provided string must not be null").toString().getBytes(Objects.requireNonNull(charset, "provided charset must not be null")));
}
/**
* Creates a new instance from given char array using utf-8 encoding
*
* @param charArray to get the internal byte array from
* @return new instance
*/
public static Bytes from(char[] charArray) {
return from(charArray, StandardCharsets.UTF_8);
}
/**
* Creates a new instance from given char array. The array will be handles like an encoded string
*
* @param charArray to get the internal byte array from
* @param charset charset to be used to decode the char array
* @return new instance
*/
public static Bytes from(char[] charArray, Charset charset) {
return from(charArray, charset, 0, charArray.length);
}
/**
* Creates a new instance from given char array with given range. The array will be handles like an encoded string
*
* @param charArray to get the internal byte array from
* @param charset charset to be used to decode the char array
* @param offset start position (from given char array not encoded byte array out)
* @param length length in relation to offset (from given char array not encoded byte array out)
* @return new instance
*/
public static Bytes from(char[] charArray, Charset charset, int offset, int length) {
return from(Util.Converter.charToByteArray(charArray, charset, offset, length));
}
/**
* Convert UUID to a newly generated 16 byte long array representation. Puts the 8 byte most significant bits and
* 8 byte the least significant bits into a byte array.
*
* @param uuid to convert to array
* @return new instance
*/
public static Bytes from(UUID uuid) {
return wrap(Util.Converter.toBytesFromUUID(Objects.requireNonNull(uuid)).array());
}
/**
* Parses a big endian binary string (e.g. <code>10010001</code>)
*
* @param binaryString the encoded string
* @return decoded instance
*/
public static Bytes parseBinary(CharSequence binaryString) {
return parseRadix(binaryString, 2);
}
/**
* Parsing of octal encoded byte arrays.
*
* @param octalString the encoded string
* @return decoded instance
*/
public static Bytes parseOctal(CharSequence octalString) {
return parseRadix(octalString, 8);
}
/**
* Parsing of decimal encoded byte arrays.
*
* @param decString the encoded string
* @return decoded instance
*/
public static Bytes parseDec(CharSequence decString) {
return parseRadix(decString, 10);
}
/**
* Encodes with given radix string representation (e.g. radix 16 would be hex).
* See also {@link BigInteger#toString(int)}.
* <p>
* This is usually a number encoding, not a data encoding (i.e. leading zeros are not preserved), but this implementation
* tries to preserve the leading zeros, to keep the in/output byte length size the same, but use at your own risk!
*
* @param radixNumberString the encoded string
* @param radix radix of the String representation (supported are 2-36)
* @return decoded instance
*/
public static Bytes parseRadix(CharSequence radixNumberString, int radix) {
return parse(radixNumberString, new BinaryToTextEncoding.BaseRadixNumber(radix));
}
/**
* Parsing of base16/HEX encoded byte arrays. This is by design a very flexible decoder accepting the following cases:
*
* <ul>
* <li>Upper- and lowercase <code>a-f</code> (also mixed case)</li>
* <li>Prefix with <code>0x</code> which will be ignored</li>
* <li>Even and odd number of string length with auto zero padding (i.e. 'E3F' is same as '0E3F')</li>
* </ul>
*
* @param hexString the encoded string
* @return decoded instance
* @throws IllegalArgumentException if string contains something else than [0-9a-fA-F]
*/
public static Bytes parseHex(CharSequence hexString) {
return parse(hexString, new BinaryToTextEncoding.Hex());
}
/**
* Parsing of base32/RFC 4648 encoded byte arrays.
* <p>
* Uses the RFC 4648 non-hex alphabet, see <a href="https://en.wikipedia.org/wiki/Base32#RFC_4648_Base32_alphabet">Base32 alphabet</a>.
*
* @param base32Rfc4648String the encoded string
* @return decoded instance
*/
public static Bytes parseBase32(CharSequence base32Rfc4648String) {
return parse(base32Rfc4648String, new BaseEncoding(BaseEncoding.BASE32_RFC4848, BaseEncoding.BASE32_RFC4848_PADDING));
}
/**
* Parsing of base36 encoded byte arrays.
* <p>
* This is usually a number encoding, not a data encoding (i.e. leading zeros are not preserved), but this implementation
* tries to preserve the leading zeros, to keep the in/output byte length size the same.
*
* @param base36String the encoded string
* @return decoded instance
* @deprecated use {@link #parseRadix(CharSequence, int)} with 36 instead; will be removed in v1.0+
*/
@Deprecated
public static Bytes parseBase36(CharSequence base36String) {
return parse(base36String, new BinaryToTextEncoding.BaseRadixNumber(36));
}
/**
* Parsing of base64 encoded byte arrays.
* Supporting RFC 4648 normal and url safe encoding, with or without padding.
*
* @param base64String the encoded string
* @return decoded instance
*/
public static Bytes parseBase64(CharSequence base64String) {
return parse(base64String, new BinaryToTextEncoding.Base64Encoding());
}
/**
* Parsing of arbitrary encoded format
*
* @param encoded the encoded string
* @param decoder the decoder used to decode the string
* @return decoded instance
*/
public static Bytes parse(CharSequence encoded, BinaryToTextEncoding.Decoder decoder) {
return wrap(Objects.requireNonNull(decoder, "passed decoder instance must no be null").decode(Objects.requireNonNull(encoded, "encoded data must not be null")));
}
/**
* A new instance with random bytes. Uses a cryptographically secure {@link SecureRandom} instance.
*
* @param length desired array length
* @return random instance
*/
public static Bytes random(int length) {
return random(length, new SecureRandom());
}
/**
* A new instance with pseudo random bytes using an unsecure random number generator.
* This may be used in e.g. tests. In production code use {@link #random(int)} per default.
* <p>
* <strong>ONLY USE IN NON-SECURITY RELEVANT CONTEXT!</strong>
*
* @param length desired array length
* @return random instance
*/
public static Bytes unsecureRandom(int length) {
return random(length, new Random());
}
/**
* A new instance with pseudo random bytes using an unsecure random number generator.
* This may be used in e.g. tests to create predictable numbers.
* <p>
* In production code use {@link #random(int)} per default.
* <p>
* <strong>ONLY USE IN NON-SECURITY RELEVANT CONTEXT!</strong>
*
* @param length desired array length
* @param seed used to seed random number generator - using same seed will generate same numbers
* @return random instance
*/
public static Bytes unsecureRandom(int length, long seed) {
return random(length, new Random(seed));
}
/**
* A new instance with random bytes.
*
* @param length desired array length
* @param random to create the entropy for the random bytes
* @return random instance
*/
public static Bytes random(int length, Random random) {
byte[] array = new byte[length];
random.nextBytes(array);
return wrap(array);
}
/* OBJECT ****************************************************************************************************/
private final byte[] byteArray;
private final ByteOrder byteOrder;
private final BytesFactory factory;
Bytes(byte[] byteArray, ByteOrder byteOrder) {
this(byteArray, byteOrder, new Factory());
}
/**
* Creates a new immutable instance
*
* @param byteArray internal byte array
* @param byteOrder the internal byte order - this is used to interpret given array, not to change it
*/
Bytes(byte[] byteArray, ByteOrder byteOrder, BytesFactory factory) {
this.byteArray = byteArray;
this.byteOrder = byteOrder;
this.factory = factory;
}
/* TRANSFORMER **********************************************************************************************/
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end).
* <p>
* This will create a new byte array internally, so it is not suitable to use as extensive builder pattern -
* use {@link ByteBuffer} or {@link java.io.ByteArrayOutputStream} for that.
*
* @param bytes to append
* @return appended instance
*/
public Bytes append(Bytes bytes) {
return append(bytes.internalArray());
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param singleByte to append
* @return appended instance
*/
public Bytes append(byte singleByte) {
return append(Bytes.from(singleByte));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param char2Bytes to append
* @return appended instance
*/
public Bytes append(char char2Bytes) {
return append(Bytes.from(char2Bytes));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param short2Bytes to append
* @return appended instance
*/
public Bytes append(short short2Bytes) {
return append(Bytes.from(short2Bytes));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param integer4Bytes to append
* @return appended instance
*/
public Bytes append(int integer4Bytes) {
return append(Bytes.from(integer4Bytes));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param long8Bytes to append
* @return appended instance
*/
public Bytes append(long long8Bytes) {
return append(Bytes.from(long8Bytes));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end).
* You may use this to append multiple byte arrays without the need for chaining the {@link #append(byte[])} call
* and therefore generating intermediate copies of the byte array, making this approach use less memory.
*
* @param arrays to append
* @return appended instance
*/
public Bytes append(byte[]... arrays) {
return append(Bytes.from(arrays));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param secondArray to append
* @return appended instance
*/
public Bytes append(byte[] secondArray) {
return transform(new BytesTransformer.ConcatTransformer(secondArray));
}
/**
* Creates a new instance with the current array appended to the provided data (i.e. append at the end)
* <p>
* If given array is null, the nothing will be appended.
*
* @param secondArrayNullable to append, may be null
* @return appended instance or same if passed array is null
*/
public Bytes appendNullSafe(byte[] secondArrayNullable) {
return secondArrayNullable == null ? this : append(secondArrayNullable);
}
/**
* Creates a new instance with the current array appended to the provided utf-8 encoded representation of this string
*
* @param stringUtf8 string used to get utf-8 bytes from
* @return appended instance
*/
public Bytes append(CharSequence stringUtf8) {
return append(stringUtf8, StandardCharsets.UTF_8);
}
/**
* Creates a new instance with the current array appended to the provided string with provided encoding
*
* @param string string used to get bytes from
* @param charset encoding of provided string
* @return appended instance
*/
public Bytes append(CharSequence string, Charset charset) {
return transform(new BytesTransformer.ConcatTransformer(Objects.requireNonNull(string).toString().getBytes(Objects.requireNonNull(charset))));
}
/**
* Bitwise XOR operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param bytes must be of same length as this instance
* @return xor'ed instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#XOR">Bitwise operators: XOR</a>
*/
public Bytes xor(Bytes bytes) {
return xor(bytes.internalArray());
}
/**
* Bitwise XOR operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param secondArray must be of same length as this instance
* @return xor'ed instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#XOR">Bitwise operators: XOR</a>
*/
public Bytes xor(byte[] secondArray) {
return transform(new BytesTransformer.BitWiseOperatorTransformer(secondArray, BytesTransformer.BitWiseOperatorTransformer.Mode.XOR));
}
/**
* Bitwise AND operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param bytes must be of same length as this instance
* @return and'ed instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#AND">Bitwise operators: AND</a>
*/
public Bytes and(Bytes bytes) {
return and(bytes.internalArray());
}
/**
* Bitwise AND operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param secondArray must be of same length as this instance
* @return and'ed instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#AND">Bitwise operators: AND</a>
*/
public Bytes and(byte[] secondArray) {
return transform(new BytesTransformer.BitWiseOperatorTransformer(secondArray, BytesTransformer.BitWiseOperatorTransformer.Mode.AND));
}
/**
* Bitwise OR operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param bytes must be of same length as this instance
* @return or'ed instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#OR">Bitwise operators: OR</a>
*/
public Bytes or(Bytes bytes) {
return or(bytes.internalArray());
}
/**
* Bitwise OR operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param secondArray must be of same length as this instance
* @return or'ed instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#OR">Bitwise operators: OR</a>
*/
public Bytes or(byte[] secondArray) {
return transform(new BytesTransformer.BitWiseOperatorTransformer(secondArray, BytesTransformer.BitWiseOperatorTransformer.Mode.OR));
}
/**
* Bitwise not operation on the whole internal byte array.
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @return negated instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#NOT">Bitwise operators: NOT</a>
*/
public Bytes not() {
return transform(new BytesTransformer.NegateTransformer());
}
/**
* Bitwise left shifting of internal byte array (i.e. <code><<</code>). Unlike {@link BigInteger}'s implementation, this one will never
* grow or shrink the underlying array. Either a bit is pushed out of the array or a zero is pushed in.
* <p>
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param shiftCount how many bits (not bytes)
* @return shifted instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts">Bit shifts</a>
*/
public Bytes leftShift(int shiftCount) {
return transform(new BytesTransformer.ShiftTransformer(
shiftCount,
BytesTransformer.ShiftTransformer.Type.LEFT_SHIFT,
byteOrder
));
}
/**
* Bitwise unsigned/logical right shifting of internal byte array (i.e. <code>>>></code>). Unlike
* {@link BigInteger}'s implementation, this one will never grow or shrink the underlying array. Either a bit is pushed
* out of the array or a zero is pushed in.
* <p>
* See the considerations about possible in-place operation in {@link #transform(BytesTransformer)}.
*
* @param shiftCount how many bits (not bytes)
* @return shifted instance
* @see <a href="https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts">Bit shifts</a>
*/
public Bytes rightShift(int shiftCount) {
return transform(new BytesTransformer.ShiftTransformer(
shiftCount,
BytesTransformer.ShiftTransformer.Type.RIGHT_SHIFT,