-
Notifications
You must be signed in to change notification settings - Fork 84
/
BytesInternal.java
3435 lines (3142 loc) · 136 KB
/
BytesInternal.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 (c) 2016-2022 chronicle.software
*
* https://chronicle.software
*
* Licensed 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 net.openhft.chronicle.bytes.internal;
import net.openhft.chronicle.bytes.*;
import net.openhft.chronicle.bytes.util.DecoratedBufferOverflowException;
import net.openhft.chronicle.bytes.util.DecoratedBufferUnderflowException;
import net.openhft.chronicle.bytes.util.StringInternerBytes;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.Memory;
import net.openhft.chronicle.core.UnsafeMemory;
import net.openhft.chronicle.core.annotation.NonNegative;
import net.openhft.chronicle.core.io.*;
import net.openhft.chronicle.core.pool.ClassAliasPool;
import net.openhft.chronicle.core.pool.EnumInterner;
import net.openhft.chronicle.core.pool.StringBuilderPool;
import net.openhft.chronicle.core.scoped.ScopedResource;
import net.openhft.chronicle.core.scoped.ScopedResourcePool;
import net.openhft.chronicle.core.scoped.ScopedThreadLocal;
import net.openhft.chronicle.core.util.Histogram;
import net.openhft.chronicle.core.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UTFDataFormatException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static net.openhft.chronicle.assertions.AssertUtil.SKIP_ASSERTIONS;
import static net.openhft.chronicle.bytes.StreamingDataOutput.JAVA9_STRING_CODER_LATIN;
import static net.openhft.chronicle.bytes.StreamingDataOutput.JAVA9_STRING_CODER_UTF16;
import static net.openhft.chronicle.bytes.internal.ReferenceCountedUtil.throwExceptionIfReleased;
import static net.openhft.chronicle.core.UnsafeMemory.MEMORY;
import static net.openhft.chronicle.core.io.ReferenceOwner.temporary;
import static net.openhft.chronicle.core.util.Longs.requireNonNegative;
import static net.openhft.chronicle.core.util.ObjectUtils.requireNonNull;
import static net.openhft.chronicle.core.util.StringUtils.*;
/**
* Utility methods to support common functionality in this package. This is not intended to be
* accessed directly.
*/
@SuppressWarnings("rawtypes")
public
enum BytesInternal {
; // none
private static final int THREAD_LOCAL_BYTES_POOL_SIZE = Jvm.getInteger("bytesInternal.bytes.instancesPerThread", 2);
public static final ThreadLocal<ByteBuffer> BYTE_BUFFER_TL = ThreadLocal.withInitial(() -> ByteBuffer.allocateDirect(0));
public static final ThreadLocal<ByteBuffer> BYTE_BUFFER2_TL = ThreadLocal.withInitial(() -> ByteBuffer.allocateDirect(0));
public static final ScopedThreadLocal<Bytes<?>> BYTES_SCOPED_THREAD_LOCAL = new ScopedThreadLocal<>(
() -> {
Bytes<?> bbb = Bytes.allocateElasticDirect(256);
IOTools.unmonitor(bbb);
return bbb;
},
Bytes::clear,
THREAD_LOCAL_BYTES_POOL_SIZE);
public static final StringInternerBytes SI;
static final char[] HEXADECIMAL = "0123456789abcdef".toCharArray();
private static final String INFINITY = "Infinity";
private static final String NAN = "NaN";
private static final String MALFORMED_INPUT_PARTIAL_CHARACTER_AT_END = "malformed input: partial character at end";
private static final String MALFORMED_INPUT_AROUND_BYTE = "malformed input around byte ";
private static final String WAS = " was ";
private static final String CAN_T_PARSE_FLEXIBLE_LONG_WITHOUT_PRECISION_LOSS = "Can't parse flexible long without precision loss: ";
private static final byte[] MIN_VALUE_TEXT = ("" + Long.MIN_VALUE).getBytes(ISO_8859_1);
private static final ScopedResourcePool<StringBuilder> STRING_BUILDER_SCOPED_RESOURCE_POOL = StringBuilderPool.createThreadLocal();
private static final byte[] INFINITY_BYTES = INFINITY.getBytes(ISO_8859_1);
private static final byte[] NAN_BYTES = NAN.getBytes(ISO_8859_1);
private static final long MAX_VALUE_DIVIDE_5 = Long.MAX_VALUE / 5;
private static final long MAX_VALUE_DIVIDE_10 = Long.MAX_VALUE / 10;
private static final ThreadLocal<DateCache> dateCacheTL = new ThreadLocal<>();
private static final int MAX_STRING_LEN = Jvm.getInteger("bytes.max-string-len", 128 * 1024);
private static final int NEG_ONE = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN ? 0x80 : 0x8000;
private static final MethodHandle VECTORIZED_MISMATCH_METHOD_HANDLE;
private static final ThreadLocal<byte[]> BYTE_ARRAY_TL = ThreadLocal.withInitial(() -> new byte[20]);
static {
try {
SI = new StringInternerBytes(Jvm.getInteger("wire.string-interner.size", 4096));
ClassAliasPool.CLASS_ALIASES.addAlias(BytesStore.class, "!binary");
} catch (Exception e) {
throw new AssertionError(e);
}
MethodHandle vectorizedMismatchMethodHandle = null;
try {
if (Jvm.isJava9Plus() && !Jvm.getBoolean("disable.vectorized.content_equals")) {
final Class<?> arraysSupportClass = Class.forName("jdk.internal.util.ArraysSupport");
final Method vectorizedMismatch = Jvm.getMethod(arraysSupportClass, "vectorizedMismatch",
Object.class,
long.class,
Object.class,
long.class,
int.class,
int.class);
vectorizedMismatch.setAccessible(true);
vectorizedMismatchMethodHandle = MethodHandles.lookup().unreflect(vectorizedMismatch);
}
} catch (Exception e) {
if (e.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException"))
Jvm.debug().on(BytesInternal.class, "Cannot get access to vectorizedMismatch. The following command line args are required: " +
"--illegal-access=permit --add-exports java.base/jdk.internal.ref=ALL-UNNAMED --add-exports java.base/jdk.internal.util=ALL-UNNAMED" +
". exception: " + e);
else
Jvm.warn().on(BytesInternal.class, e);
} finally {
VECTORIZED_MISMATCH_METHOD_HANDLE = vectorizedMismatchMethodHandle;
}
}
public static boolean contentEqual(@Nullable final BytesStore<?, ?> a,
@Nullable final BytesStore<?, ?> b) throws ClosedIllegalStateException {
if (a == null) return b == null;
if (b == null) {
// The contract stipulates that if either ByteStores are closed then we throw an Exception
throwExceptionIfReleased(a);
return false;
}
throwExceptionIfReleased(a);
throwExceptionIfReleased(b);
final long readRemaining = a.readRemaining();
if (readRemaining != b.readRemaining())
// The size is different so, we know that a and b cannot be equal
return false;
if (VECTORIZED_MISMATCH_METHOD_HANDLE != null
&& b.realReadRemaining() == a.realReadRemaining()
&& a.realReadRemaining() < Integer.MAX_VALUE
&& a.realReadRemaining() > 7
&& !(a instanceof HexDumpBytes) && !(b instanceof HexDumpBytes)) {
// this will use AVX instructions, this is very fast; much faster than a handwritten loop.
try {
Boolean vectorizedResult = java11ContentEqualUsingVectorizedMismatch(a, b);
if (vectorizedResult != null)
return vectorizedResult;
} catch (UnsupportedOperationException e) {
Jvm.warn().on(BytesInternal.class, e);
}
}
return readRemaining <= Integer.MAX_VALUE
? contentEqualInt(a, b)
: contentEqualsLong(a, b);
}
/**
* returns true if the contents are equal using VectorizedMismatch*
*
* @param left the byte on the left
* @param right the byte on the right
* @return true if the content are equal
* see <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8136924">...</a>
* JDK-8033148 will add methods to Arrays for array equals, compare and mismatch.
* The implementations of equals, compare and mismatch can be reimplemented using underlying mismatch methods that in turn defer to a single method, vectorizedMismatch, that accesses the memory contents of arrays using Unsafe.getLongUnaligned.
* The vectorizedMismatch implementation can be optimized efficiently by C2 to obtain an approximate 8x speed up when performing a mismatch on byte[] arrays (of a suitable size to overcome fixed costs).
* The contract of vectorizedMismatch is simple enough that it can be made an intrinsic (see JDK-8044082) and leverage SIMDs instructions to perform operations up to a width of say 512 bits on supported architectures. Thus even further performance improvements may be possible.
*/
private static Boolean java11ContentEqualUsingVectorizedMismatch(@NotNull final BytesStore<?, ?> left,
@NotNull final BytesStore<?, ?> right) {
try {
final Object leftObject;
final long leftOffset;
if (left.isDirectMemory()) {
leftObject = null;
leftOffset = left.addressForRead(left.readPosition());
} else {
BytesStore<?, ?> bytesStore = left.bytesStore();
if (!(bytesStore instanceof HeapBytesStore))
return null;
HeapBytesStore heapBytesStore = (HeapBytesStore) bytesStore;
leftObject = heapBytesStore.realUnderlyingObject();
leftOffset = heapBytesStore.dataOffset() + left.readPosition();
}
final Object rightObject;
final long rightOffset;
if (right.isDirectMemory()) {
rightObject = null;
rightOffset = right.addressForRead(right.readPosition());
} else {
BytesStore<?, ?> bytesStore = right.bytesStore();
if (!(bytesStore instanceof HeapBytesStore))
return null;
HeapBytesStore heapBytesStore = (HeapBytesStore) bytesStore;
rightObject = heapBytesStore.realUnderlyingObject();
rightOffset = heapBytesStore.dataOffset() + right.readPosition();
}
final int length = (int) left.realReadRemaining();
final int invoke = (int) VECTORIZED_MISMATCH_METHOD_HANDLE.invoke(leftObject,
leftOffset,
rightObject,
rightOffset,
length,
0);
if (invoke >= 0)
return Boolean.FALSE;
int remaining = length - ~invoke;
for (; remaining < length; remaining++) {
if (left.readByte(left.readPosition() + remaining) !=
right.readByte(right.readPosition() + remaining)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
} catch (Throwable e) {
Jvm.warn().on(BytesInternal.class, e);
return null;
}
}
@SuppressWarnings("unchecked")
// Optimise for the common case where the length is 31-bit.
static <U extends BytesStore<?, ?> & HasUncheckedRandomDataInput>
boolean contentEqualInt(@NotNull final BytesStore<?, ?> a,
@NotNull final BytesStore<?, ?> b) throws ClosedIllegalStateException {
final int aLength = (int) a.realReadRemaining();
final int bLength = (int) b.realReadRemaining();
if (a instanceof HasUncheckedRandomDataInput && b instanceof HasUncheckedRandomDataInput) {
// Make sure a >= b
if (aLength < bLength)
return contentEqualIntUnchecked((U) b, (U) a, bLength, aLength);
else
return contentEqualIntUnchecked((U) a, (U) b, aLength, bLength);
} else {
// Make sure a >= b
if (aLength < bLength)
return contentEqualInt(b, a, bLength, aLength);
else
return contentEqualInt(a, b, aLength, bLength);
}
}
// a >= b here and we also know it is safe to read bLength
static boolean contentEqualInt(@NotNull final BytesStore<?, ?> a,
@NotNull final BytesStore<?, ?> b,
@NonNegative final int aLength,
@NonNegative final int bLength) throws ClosedIllegalStateException {
assert SKIP_ASSERTIONS || aLength >= bLength;
final long aPos = a.readPosition();
final long bPos = b.readPosition();
int i;
for (i = 0; i < bLength - 7; i += 8) {
if (a.readLong(aPos + i) != b.readLong(bPos + i))
return false;
}
for (; i < bLength; i++) {
if (a.readByte(aPos + i) != b.readByte(bPos + i))
return false;
}
// check for zeros
for (; i < aLength - 7; i += 8) {
if (a.readLong(aPos + i) != 0L)
return false;
}
for (; i < aLength; i++) {
if (a.readByte(aPos + i) != 0)
return false;
}
return true;
}
// a >= b here and we also know it is safe to read bLength
static <U extends BytesStore<?, ?> & HasUncheckedRandomDataInput>
boolean contentEqualIntUnchecked(@NotNull final U a,
@NotNull final U b,
@NonNegative final int aLength,
@NonNegative final int bLength) throws ClosedIllegalStateException {
assert SKIP_ASSERTIONS || aLength >= bLength;
final UncheckedRandomDataInput ua = a.acquireUncheckedInput();
final UncheckedRandomDataInput ub = b.acquireUncheckedInput();
final long aPos = a.readPosition();
final long bPos = b.readPosition();
int i;
for (i = 0; i < bLength - 7; i += 8) {
if (ua.readLong(aPos + i) != ub.readLong(bPos + i))
return false;
}
for (; i < bLength; i++) {
if (ua.readByte(aPos + i) != ub.readByte(bPos + i))
return false;
}
// check for zeros
for (; i < aLength - 7; i += 8) {
if (ua.readLong(aPos + i) != 0L)
return false;
}
for (; i < aLength; i++) {
if (ua.readByte(aPos + i) != 0)
return false;
}
return true;
}
@SuppressWarnings("unchecked")
static <U extends BytesStore<?, ?> & HasUncheckedRandomDataInput>
boolean contentEqualsLong(@NotNull final BytesStore<?, ?> a,
@NotNull final BytesStore<?, ?> b) {
final long aLength = a.realReadRemaining();
final long bLength = b.realReadRemaining();
if (a instanceof HasUncheckedRandomDataInput && b instanceof HasUncheckedRandomDataInput) {
// Make sure a >= b
if (a.realCapacity() < b.realCapacity())
return contentEqualsLongUnchecked((U) b, (U) a, bLength, aLength);
else
return contentEqualsLongUnchecked((U) a, (U) b, aLength, bLength);
} else {
// Make sure a >= b
if (a.realCapacity() < b.realCapacity())
return contentEqualsLong(b, a, bLength, aLength);
else
return contentEqualsLong(a, b, aLength, bLength);
}
}
// a >= b here and we also know it is safe to read bLength
private static boolean contentEqualsLong(@NotNull final BytesStore<?, ?> a,
@NotNull final BytesStore<?, ?> b,
@NonNegative final long aLength,
@NonNegative final long bLength) throws ClosedIllegalStateException {
assert SKIP_ASSERTIONS || aLength >= bLength;
// assume a >= b
long aPos = a.readPosition();
long bPos = b.readPosition();
long i;
for (i = 0; i < bLength - 7; i += 8) {
if (a.readLong(aPos + i) != b.readLong(bPos + i))
return false;
}
for (; i < bLength; i++) {
if (a.readByte(aPos + i) != b.readByte(bPos + i))
return false;
}
// check for zeros
for (; i < aLength - 7; i += 8) {
if (a.readLong(aPos + i) != 0L)
return false;
}
for (; i < aLength; i++) {
if (a.readByte(aPos + i) != 0)
return false;
}
return true;
}
// a >= b here and we also know it is safe to read bLength
private static <U extends BytesStore<?, ?> & HasUncheckedRandomDataInput>
boolean contentEqualsLongUnchecked(@NotNull final U a,
@NotNull final U b,
@NonNegative final long aLength,
@NonNegative final long bLength) {
assert SKIP_ASSERTIONS || aLength >= bLength;
final UncheckedRandomDataInput ua = a.acquireUncheckedInput();
final UncheckedRandomDataInput ub = b.acquireUncheckedInput();
// assume a >= b
long aPos = a.readPosition();
long bPos = b.readPosition();
long i;
for (i = 0; i < bLength - 7; i += 8) {
if (ua.readLong(aPos + i) != ub.readLong(bPos + i))
return false;
}
for (; i < bLength; i++) {
if (ua.readByte(aPos + i) != ub.readByte(bPos + i))
return false;
}
// check for zeros
for (; i < aLength - 7; i += 8) {
if (ua.readLong(aPos + i) != 0L)
return false;
}
for (; i < aLength; i++) {
if (ua.readByte(aPos + i) != 0)
return false;
}
return true;
}
public static boolean startsWith(@NotNull BytesStore<?, ?> a, @NotNull BytesStore<?, ?> b)
throws ClosedIllegalStateException {
throwExceptionIfReleased(a);
throwExceptionIfReleased(b);
final long bRealReadRemaining = b.realReadRemaining();
if (a.realReadRemaining() < bRealReadRemaining)
return false;
return startsWith(a, b, a.readPosition(), b.readPosition(), bRealReadRemaining);
}
public static <U extends BytesStore<?, ?> & HasUncheckedRandomDataInput>
boolean startsWithUnchecked(@NotNull final U a,
@NotNull final BytesStore<?, ?> b) {
throwExceptionIfReleased(a);
throwExceptionIfReleased(b);
final long bRealReadRemaining = b.realReadRemaining();
if (a.realReadRemaining() < bRealReadRemaining) {
return false;
}
if (b instanceof HasUncheckedRandomDataInput) {
// We have hoisted out boundary checks in this path
return startsWithUnchecked(a.acquireUncheckedInput(),
((HasUncheckedRandomDataInput) b).acquireUncheckedInput(),
a.readPosition(),
b.readPosition(),
bRealReadRemaining);
} else {
return startsWith(a, b, a.readPosition(), b.readPosition(), bRealReadRemaining);
}
}
private static boolean startsWithUnchecked(@NotNull final UncheckedRandomDataInput ua,
@NotNull final UncheckedRandomDataInput ub,
@NonNegative final long aPos,
@NonNegative final long bPos,
@NonNegative final long length) {
int i;
for (i = 0; i < length - 7; i += 8) {
if (ua.readLong(aPos + i) != ub.readLong(bPos + i))
return false;
}
if (i < length - 3) {
if (ua.readInt(aPos + i) != ub.readInt(bPos + i))
return false;
i += 4;
}
if (i < length - 1) {
if (ua.readShort(aPos + i) != ub.readShort(bPos + i))
return false;
i += 2;
}
if (i < length) {
return ua.readByte(aPos + i) == ub.readByte(bPos + i);
}
return true;
}
private static boolean startsWith(@NotNull final BytesStore<?, ?> a,
@NotNull final BytesStore<?, ?> b,
@NonNegative final long aPos,
@NonNegative final long bPos,
@NonNegative final long length) {
int i;
for (i = 0; i < length - 7; i += 8) {
if (a.readLong(aPos + i) != b.readLong(bPos + i))
return false;
}
if (i < length - 3) {
if (a.readInt(aPos + i) != b.readInt(bPos + i))
return false;
i += 4;
}
if (i < length - 1) {
if (a.readShort(aPos + i) != b.readShort(bPos + i))
return false;
i += 2;
}
if (i < length) {
return a.readByte(aPos + i) == b.readByte(bPos + i);
}
return true;
}
public static void parseUtf8(
@NotNull StreamingDataInput bytes, Appendable appendable, boolean utf, @NonNegative int length)
throws UTFDataFormatRuntimeException, BufferUnderflowException, ClosedIllegalStateException {
throwExceptionIfReleased(bytes);
// Because Bytes implements Appendable, we need to check if it might be closed
throwExceptionIfReleased(appendable);
if (appendable instanceof StringBuilder
&& bytes.isDirectMemory()
&& length < 1 << 20
&& utf) {
// todo fix, a problem with very long sequences. #35
parseUtf8_SB1((Bytes) bytes, (StringBuilder) appendable, utf, length);
} else {
parseUtf81(bytes, appendable, utf, length);
}
}
public static void parseUtf8(
@NotNull RandomDataInput input, @NonNegative long offset, Appendable appendable, boolean utf, @NonNegative int length)
throws UTFDataFormatRuntimeException, BufferUnderflowException, ClosedIllegalStateException {
assert utf;
throwExceptionIfReleased(input);
throwExceptionIfReleased(appendable);
if (appendable instanceof StringBuilder) {
if (input instanceof NativeBytesStore) {
parseUtf8_SB1((NativeBytesStore) input, offset, (StringBuilder) appendable, length);
return;
} else if (input instanceof Bytes
&& ((Bytes) input).bytesStore() instanceof NativeBytesStore) {
@Nullable NativeBytesStore bs = (NativeBytesStore) ((Bytes) input).bytesStore();
parseUtf8_SB1(bs, offset, (StringBuilder) appendable, length);
return;
}
}
parseUtf81(input, offset, appendable, length);
}
public static boolean compareUtf8(@NotNull RandomDataInput input, @NonNegative long offset, @Nullable CharSequence other)
throws IORuntimeException, BufferUnderflowException, ClosedIllegalStateException {
throwExceptionIfReleased(input);
if (other != null)
throwExceptionIfReleased(other);
long utfLen;
if ((utfLen = input.readByte(offset++)) < 0) {
utfLen &= 0x7FL;
long b;
int count = 7;
while ((b = input.readByte(offset++)) < 0) {
utfLen |= (b & 0x7FL) << count;
count += 7;
}
if (b != 0) {
if (count > 56)
throw new IORuntimeException(
"Cannot read more than 9 stop bits of positive value");
utfLen |= (b << count);
} else {
if (count > 63)
throw new IORuntimeException(
"Cannot read more than 10 stop bits of negative value");
utfLen = ~utfLen;
}
}
if (utfLen == -1)
return other == null;
return other != null && compareUtf8(input, offset, utfLen, other);
}
private static boolean compareUtf8(
@NotNull RandomDataInput input, @NonNegative long offset, @NonNegative long utfLen, @NotNull CharSequence other)
throws UTFDataFormatRuntimeException, BufferUnderflowException, IndexOutOfBoundsException, ClosedIllegalStateException {
throwExceptionIfReleased(input);
throwExceptionIfReleased(other);
if (offset + utfLen > input.realCapacity())
throw new BufferUnderflowException();
int i = 0;
while (i < utfLen && i < other.length()) {
int c = input.readByte(offset + i);
if (c < 0)
break;
if ((char) c != other.charAt(i))
return false;
i++;
}
if (i < utfLen && i < other.length())
return compareUtf82(input, offset + i, i, utfLen, other);
return utfLen == other.length();
}
private static boolean compareUtf82(
@NotNull RandomDataInput input, @NonNegative long offset, int charI, @NonNegative long utfLen, @NotNull CharSequence other)
throws UTFDataFormatRuntimeException, BufferUnderflowException, IndexOutOfBoundsException, ClosedIllegalStateException {
throwExceptionIfReleased(input);
throwExceptionIfReleased(other);
long limit = offset + utfLen;
while (offset < limit && charI < other.length()) {
int c = input.readUnsignedByte(offset++);
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
/* 0xxxxxxx */
if ((char) c != other.charAt(charI))
return false;
break;
case 12:
case 13: {
/* 110x xxxx 10xx xxxx */
if (offset == limit)
throw new UTFDataFormatRuntimeException(
MALFORMED_INPUT_PARTIAL_CHARACTER_AT_END);
int char2 = input.readUnsignedByte(offset++);
if ((char2 & 0xC0) != 0x80)
throw newUTFDataFormatRuntimeException((offset - limit + utfLen), "was " + char2);
int c2 = (char) (((c & 0x1F) << 6) |
(char2 & 0x3F));
if ((char) c2 != other.charAt(charI))
return false;
break;
}
case 14: {
/* 1110 xxxx 10xx xxxx 10xx xxxx */
if (offset + 2 > limit)
throw new UTFDataFormatRuntimeException(
MALFORMED_INPUT_PARTIAL_CHARACTER_AT_END);
int char2 = input.readUnsignedByte(offset++);
int char3 = input.readUnsignedByte(offset++);
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatRuntimeException(
MALFORMED_INPUT_AROUND_BYTE + (offset - limit + utfLen - 1) +
WAS + char2 + " " + char3);
int c3 = (char) (((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
(char3 & 0x3F));
if ((char) c3 != other.charAt(charI))
return false;
break;
}
// TODO add code point of characters > 0xFFFF support.
default:
/* 10xx xxxx, 1111 xxxx */
throw newUTFDataFormatRuntimeException(offset - limit + utfLen, "");
}
charI++;
}
return offset == limit && charI == other.length();
}
public static void parse8bit(@NonNegative long offset, @NotNull RandomDataInput bytesStore, Appendable appendable, @NonNegative int utflen)
throws BufferUnderflowException, IOException, ClosedIllegalStateException {
throwExceptionIfReleased(bytesStore);
throwExceptionIfReleased(appendable);
if (bytesStore instanceof NativeBytesStore
&& appendable instanceof StringBuilder) {
parse8bit_SB1(offset, (NativeBytesStore) bytesStore, (StringBuilder) appendable, utflen);
} else {
parse8bit1(offset, bytesStore, appendable, utflen);
}
}
public static void parseUtf81(
@NotNull StreamingDataInput bytes, @NotNull Appendable appendable, boolean utf, @NonNegative int length)
throws UTFDataFormatRuntimeException, BufferUnderflowException, ClosedIllegalStateException {
throwExceptionIfReleased(bytes);
throwExceptionIfReleased(appendable);
if (bytes.readRemaining() < length)
throw new IllegalArgumentException();
try {
int count = 0;
while (count < length) {
int c = bytes.rawReadByte();
if (c < 0) {
bytes.readSkip(-1);
break;
}
count++;
appendable.append((char) c);
}
if (length > count)
parseUtf82(bytes, appendable, utf, length, count);
} catch (IOException e) {
throw Jvm.rethrow(e);
}
}
public static void parseUtf81(@NotNull RandomDataInput input, @NonNegative long offset,
@NotNull Appendable appendable, int utflen)
throws UTFDataFormatRuntimeException, BufferUnderflowException, ClosedIllegalStateException {
throwExceptionIfReleased(input);
throwExceptionIfReleased(appendable);
try {
assert input.realCapacity() >= offset + utflen;
long limit = offset + utflen;
while (offset < limit) {
int c = input.readUnsignedByte(offset++);
if (c >= 128) {
offset--;
break;
} else if (c < 0) {
break;
}
appendable.append((char) c);
}
if (limit > offset)
parseUtf82(input, offset, limit, appendable, utflen);
} catch (IOException e) {
throw Jvm.rethrow(e);
}
}
public static void parse8bit1(@NotNull StreamingDataInput bytes, @NotNull StringBuilder sb, @NonNegative int utflen)
throws ClosedIllegalStateException {
throwExceptionIfReleased(bytes);
if (bytes.readRemaining() < utflen)
throw new IllegalArgumentException();
sb.ensureCapacity(utflen);
if (Jvm.isJava9Plus()) {
byte[] sbBytes = extractBytes(sb);
for (int count = 0; count < utflen; count++) {
int c = bytes.readUnsignedByte();
sbBytes[count] = (byte) c;
}
} else {
char[] chars = StringUtils.extractChars(sb);
for (int count = 0; count < utflen; count++) {
int c = bytes.readUnsignedByte();
chars[count] = (char) c;
}
}
StringUtils.setLength(sb, utflen);
}
public static void parse8bit1(@NotNull StreamingDataInput bytes, @NotNull Appendable appendable, @NonNegative int utflen)
throws ClosedIllegalStateException, IOException {
throwExceptionIfReleased(bytes);
throwExceptionIfReleased(appendable);
assert bytes.readRemaining() >= utflen;
for (int count = 0; count < utflen; count++) {
int c = bytes.readUnsignedByte();
appendable.append((char) c);
}
}
public static void parse8bit1(@NonNegative long offset, @NotNull RandomDataInput bytes, @NotNull Appendable appendable, @NonNegative int utflen)
throws BufferUnderflowException, ClosedIllegalStateException, IOException {
throwExceptionIfReleased(bytes);
throwExceptionIfReleased(appendable);
if (bytes.realCapacity() < utflen + offset)
throw new DecoratedBufferUnderflowException(bytes.realCapacity() + " < " + utflen + " +" + offset);
for (int count = 0; count < utflen; count++) {
int c = bytes.readUnsignedByte(offset + count);
appendable.append((char) c);
}
}
public static void parseUtf8_SB1(@NotNull Bytes<?> bytes, @NotNull StringBuilder sb, boolean utf, @NonNegative int utflen)
throws UTFDataFormatRuntimeException, BufferUnderflowException {
try {
throwExceptionIfReleased(bytes);
assert utf;
if (utflen > bytes.readRemaining()) {
@NotNull final BufferUnderflowException bue = new BufferUnderflowException();
bue.initCause(new ClosedIllegalStateException("utflen: " + utflen + ", readRemaining: " + bytes.readRemaining()));
throw bue;
}
long readPosition = bytes.readPosition();
sb.ensureCapacity(utflen);
int count = calculateCount(bytes, sb, utflen, readPosition);
bytes.readSkip(count);
setCount(sb, count);
if (count < utflen) {
final long rp0 = bytes.readPosition();
parseUtf82Guarded(bytes, sb, utf, utflen, count, rp0);
}
} catch (IOException | ClosedIllegalStateException e) {
throw Jvm.rethrow(e);
}
}
private static void parseUtf82Guarded(@NotNull Bytes<?> bytes, @NotNull StringBuilder sb, boolean utf, @NonNegative int utflen, int count, long rp0) throws IOException {
try {
parseUtf82(bytes, sb, utf, utflen, count);
} catch (UTFDataFormatRuntimeException e) {
long rp = Math.max(rp0 - 128, 0);
throw new UTFDataFormatRuntimeException(Long.toHexString(rp0) + "\n" + bytes.toHexString(rp, 200), e);
}
}
private static int calculateCount(@NotNull Bytes<?> bytes, @NotNull StringBuilder sb, @NonNegative int utflen, @NonNegative long readPosition) throws ClosedIllegalStateException {
int count = 0;
if (Jvm.isJava9Plus()) {
sb.setLength(utflen);
while (count < utflen) {
byte c = bytes.readByte(readPosition + count);
if (c < 0)
break;
sb.setCharAt(count++, (char) c); // This is not as fast as it could be.
}
} else {
final char[] chars = extractChars(sb);
while (count < utflen) {
int c = bytes.readByte(readPosition + count);
if (c < 0)
break;
chars[count++] = (char) c;
}
}
return count;
}
public static void parseUtf8_SB1(@NotNull NativeBytesStore bytes, @NonNegative long offset,
@NotNull StringBuilder sb, @NonNegative int utflen)
throws UTFDataFormatRuntimeException, BufferUnderflowException, ClosedIllegalStateException {
throwExceptionIfReleased(bytes);
requireNonNull(sb);
try {
if (offset + utflen > bytes.realCapacity())
throw new BufferUnderflowException();
long address = bytes.address + bytes.translate(offset);
Memory memory = bytes.memory;
sb.ensureCapacity(utflen);
int count = 0;
if (Jvm.isJava9Plus()) {
sb.setLength(utflen);
while (count < utflen) {
byte c = memory.readByte(address + count);
if (c < 0)
break;
sb.setCharAt(count++, (char) c);
}
} else {
char[] chars = extractChars(sb);
while (count < utflen) {
int c = memory.readByte(address + count);
if (c < 0)
break;
chars[count++] = (char) c;
}
}
setCount(sb, count);
if (count < utflen)
parseUtf82(bytes, offset + count, offset + utflen, sb, utflen);
assert bytes.memory != null;
} catch (IOException e) {
throw Jvm.rethrow(e);
}
}
public static int parse8bit_SB1(@NonNegative long offset, @NotNull NativeBytesStore nbs, @NotNull StringBuilder sb, @NonNegative int length) {
throwExceptionIfReleased(nbs);
requireNonNull(sb);
long address = nbs.address + nbs.translate(offset);
@Nullable Memory memory = nbs.memory;
sb.ensureCapacity(length);
int count = 0;
if (Jvm.isJava9Plus()) {
byte coder = getStringCoder(sb);
if (coder == JAVA9_STRING_CODER_LATIN) {
byte[] bytes = extractBytes(sb);
while (count < length) {
byte b = memory.readByte(address + count);
bytes[count++] = b;
}
} else {
assert coder == JAVA9_STRING_CODER_UTF16;
sb.setLength(length);
while (count < length) {
byte b = memory.readByte(address + count);
sb.setCharAt(count++, (char) b);
}
}
} else {
char[] chars = extractChars(sb);
while (count < length) {
int c = memory.readByte(address + count) & 0xFF;
chars[count++] = (char) c;
}
}
setCount(sb, count);
return count;
}
static void parseUtf82(@NotNull StreamingDataInput bytes, @NotNull Appendable appendable, boolean utf, @NonNegative int length, @NonNegative int count)
throws IOException, UTFDataFormatRuntimeException, ClosedIllegalStateException {
throwExceptionIfReleased(bytes);
throwExceptionIfReleased(appendable);
while (count < length) {
int c = bytes.readUnsignedByte();
if (c < 0)
break;
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
/* 0xxxxxxx */
count++;
appendable.append((char) c);
break;
case 12:
case 13: {
/* 110x xxxx 10xx xxxx */
count += utf ? 2 : 1;
if (count > length)
throw new UTFDataFormatRuntimeException(
MALFORMED_INPUT_PARTIAL_CHARACTER_AT_END);
int char2 = bytes.readUnsignedByte();
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatRuntimeException(
MALFORMED_INPUT_AROUND_BYTE + count + WAS + char2);
int c2 = (char) (((c & 0x1F) << 6) |
(char2 & 0x3F));
appendable.append((char) c2);
break;
}
case 14: {
/* 1110 xxxx 10xx xxxx 10xx xxxx */
count += utf ? 3 : 1;
if (count > length)
throw new UTFDataFormatRuntimeException(
MALFORMED_INPUT_PARTIAL_CHARACTER_AT_END);
int char2 = bytes.readUnsignedByte();
int char3 = bytes.readUnsignedByte();
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw newUTFDataFormatRuntimeException(count - 1L, WAS + char2 + " " + char3);
int c3 = (char) (((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
(char3 & 0x3F));
appendable.append((char) c3);
break;
}
// TODO add code point of characters > 0xFFFF support.
default:
/* 10xx xxxx, 1111 xxxx */
throw newUTFDataFormatRuntimeException(count, "");
}
}
}
static void parseUtf82(@NotNull RandomDataInput input, @NonNegative long offset, @NonNegative long limit,
@NotNull Appendable appendable, @NonNegative int utflen)
throws IOException, UTFDataFormatRuntimeException, BufferUnderflowException, ClosedIllegalStateException {
throwExceptionIfReleased(input);
throwExceptionIfReleased(appendable);
while (offset < limit) {
int c = input.readUnsignedByte(offset++);
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
/* 0xxxxxxx */
appendable.append((char) c);
break;