This repository was archived by the owner on Dec 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCompositeBuffer.java
1806 lines (1612 loc) · 58.6 KB
/
CompositeBuffer.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 2020 The Netty Project
*
* The Netty Project 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:
*
* https://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 io.netty.buffer.api;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
final class CompositeBuffer extends RcSupport<Buffer, CompositeBuffer> implements Buffer {
/**
* The max array size is JVM implementation dependant, but most seem to settle on {@code Integer.MAX_VALUE - 8}.
* We set the max composite buffer capacity to the same, since it would otherwise be impossible to create a
* non-composite copy of the buffer.
*/
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private static final Drop<CompositeBuffer> COMPOSITE_DROP = new Drop<CompositeBuffer>() {
@Override
public void drop(CompositeBuffer buf) {
for (Buffer b : buf.bufs) {
b.close();
}
buf.makeInaccessible();
}
@Override
public String toString() {
return "COMPOSITE_DROP";
}
};
private final BufferAllocator allocator;
private final TornBufferAccessors tornBufAccessors;
private Buffer[] bufs;
private int[] offsets; // The offset, for the composite buffer, where each constituent buffer starts.
private int capacity;
private int roff;
private int woff;
private int subOffset; // The next offset *within* a consituent buffer to read from or write to.
private ByteOrder order;
private boolean closed;
private boolean readOnly;
CompositeBuffer(BufferAllocator allocator, Deref<Buffer>[] refs) {
this(allocator, filterExternalBufs(refs), COMPOSITE_DROP, false);
}
private static Buffer[] filterExternalBufs(Deref<Buffer>[] refs) {
// We filter out all zero-capacity buffers because they wouldn't contribute to the composite buffer anyway,
// and also, by ensuring that all constituent buffers contribute to the size of the composite buffer,
// we make sure that the number of composite buffers will never become greater than the number of bytes in
// the composite buffer.
// This restriction guarantees that methods like countComponents, forEachReadable and forEachWritable,
// will never overflow their component counts.
// Allocating a new array unconditionally also prevents external modification of the array.
Buffer[] bufs = Arrays.stream(refs)
.map(r -> r.get()) // Increments reference counts.
.filter(CompositeBuffer::discardEmpty)
.flatMap(CompositeBuffer::flattenBuffer)
.toArray(Buffer[]::new);
// Make sure there are no duplicates among the buffers.
Set<Buffer> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>());
duplicatesCheck.addAll(Arrays.asList(bufs));
if (duplicatesCheck.size() < bufs.length) {
for (Buffer buf : bufs) {
buf.close(); // Undo the increment we did with Deref.get().
}
throw new IllegalArgumentException(
"Cannot create composite buffer with duplicate constituent buffer components.");
}
return bufs;
}
private static boolean discardEmpty(Buffer buf) {
if (buf.capacity() > 0) {
return true;
} else {
// If we filter a buffer out, then we must make sure to close it since we incremented the reference count
// with Deref.get() earlier.
buf.close();
return false;
}
}
private static Stream<Buffer> flattenBuffer(Buffer buf) {
if (buf instanceof CompositeBuffer) {
// Extract components and move our reference count from the composite onto the components.
var composite = (CompositeBuffer) buf;
var bufs = composite.bufs;
for (Buffer b : bufs) {
b.acquire();
}
buf.close(); // Important: acquire on components *before* closing composite.
return Stream.of(bufs);
}
return Stream.of(buf);
}
private CompositeBuffer(BufferAllocator allocator, Buffer[] bufs, Drop<CompositeBuffer> drop,
boolean acquireBufs) {
super(drop);
this.allocator = allocator;
if (acquireBufs) {
for (Buffer buf : bufs) {
buf.acquire();
}
}
try {
if (bufs.length > 0) {
ByteOrder targetOrder = bufs[0].order();
for (Buffer buf : bufs) {
if (buf.order() != targetOrder) {
throw new IllegalArgumentException("Constituent buffers have inconsistent byte order.");
}
}
order = bufs[0].order();
boolean targetReadOnly = bufs[0].readOnly();
for (Buffer buf : bufs) {
if (buf.readOnly() != targetReadOnly) {
throw new IllegalArgumentException("Constituent buffers have inconsistent read-only state.");
}
}
readOnly = targetReadOnly;
} else {
order = ByteOrder.nativeOrder();
}
this.bufs = bufs;
computeBufferOffsets();
tornBufAccessors = new TornBufferAccessors(this);
} catch (Exception e) {
// Always close bufs on exception, regardless of acquireBufs value.
// If acquireBufs is false, it just means the ref count increments happened prior to this constructor call.
for (Buffer buf : bufs) {
buf.close();
}
throw e;
}
}
private void computeBufferOffsets() {
if (bufs.length > 0) {
int woff = 0;
int roff = 0;
boolean woffMidpoint = false;
for (Buffer buf : bufs) {
if (buf.writableBytes() == 0) {
woff += buf.capacity();
} else if (!woffMidpoint) {
woff += buf.writerOffset();
woffMidpoint = true;
} else if (buf.writerOffset() != 0) {
throw new IllegalArgumentException(
"The given buffers cannot be composed because they leave an unwritten gap: " +
Arrays.toString(bufs) + '.');
}
}
boolean roffMidpoint = false;
for (Buffer buf : bufs) {
if (buf.readableBytes() == 0 && buf.writableBytes() == 0) {
roff += buf.capacity();
} else if (!roffMidpoint) {
roff += buf.readerOffset();
roffMidpoint = true;
} else if (buf.readerOffset() != 0) {
throw new IllegalArgumentException(
"The given buffers cannot be composed because they leave an unread gap: " +
Arrays.toString(bufs) + '.');
}
}
assert roff <= woff:
"The given buffers place the read offset ahead of the write offset: " + Arrays.toString(bufs) + '.';
// Commit computed offsets.
this.woff = woff;
this.roff = roff;
}
offsets = new int[bufs.length];
long cap = 0;
for (int i = 0; i < bufs.length; i++) {
offsets[i] = (int) cap;
cap += bufs[i].capacity();
}
if (cap > MAX_CAPACITY) {
throw new IllegalArgumentException(
"Combined size of the constituent buffers is too big. " +
"The maximum buffer capacity is " + MAX_CAPACITY + " (Interger.MAX_VALUE - 8), " +
"but the sum of the constituent buffer capacities was " + cap + '.');
}
capacity = (int) cap;
}
@Override
public String toString() {
return "Buffer[roff:" + roff + ", woff:" + woff + ", cap:" + capacity + ']';
}
@Override
public Buffer order(ByteOrder order) {
if (this.order != order) {
this.order = order;
for (Buffer buf : bufs) {
buf.order(order);
}
}
return this;
}
@Override
public ByteOrder order() {
return order;
}
@Override
public int capacity() {
return capacity;
}
@Override
public int readerOffset() {
return roff;
}
@Override
public Buffer readerOffset(int index) {
prepRead(index, 0);
int indexLeft = index;
for (Buffer buf : bufs) {
buf.readerOffset(Math.min(indexLeft, buf.capacity()));
indexLeft = Math.max(0, indexLeft - buf.capacity());
}
roff = index;
return this;
}
@Override
public int writerOffset() {
return woff;
}
@Override
public Buffer writerOffset(int index) {
checkWriteBounds(index, 0);
int indexLeft = index;
for (Buffer buf : bufs) {
buf.writerOffset(Math.min(indexLeft, buf.capacity()));
indexLeft = Math.max(0, indexLeft - buf.capacity());
}
woff = index;
return this;
}
@Override
public Buffer fill(byte value) {
for (Buffer buf : bufs) {
buf.fill(value);
}
return this;
}
@Override
public long nativeAddress() {
return 0;
}
@Override
public Buffer readOnly(boolean readOnly) {
for (Buffer buf : bufs) {
buf.readOnly(readOnly);
}
this.readOnly = readOnly;
return this;
}
@Override
public boolean readOnly() {
return readOnly;
}
@Override
public Buffer slice(int offset, int length) {
checkWriteBounds(offset, length);
if (offset < 0 || length < 0) {
throw new IllegalArgumentException(
"Offset and length cannot be negative, but offset was " +
offset + ", and length was " + length + '.');
}
Buffer choice = (Buffer) chooseBuffer(offset, 0);
Buffer[] slices;
if (length > 0) {
slices = new Buffer[bufs.length];
int off = subOffset;
int cap = length;
int i;
for (i = searchOffsets(offset); cap > 0; i++) {
var buf = bufs[i];
int avail = buf.capacity() - off;
slices[i] = buf.slice(off, Math.min(cap, avail));
cap -= avail;
off = 0;
}
slices = Arrays.copyOf(slices, i);
} else {
// Specialize for length == 0, since we must slice from at least one constituent buffer.
slices = new Buffer[] { choice.slice(subOffset, 0) };
}
// Use the constructor that skips filtering out empty buffers, and skips acquiring on the buffers.
// This is important because 1) slice() already acquired the buffers, and 2) if this slice is empty
// then we need to keep holding on to it to prevent this originating composite buffer from getting
// ownership. If it did, its behaviour would be inconsistent with that of a non-composite buffer.
return new CompositeBuffer(allocator, slices, COMPOSITE_DROP, false);
}
@Override
public void copyInto(int srcPos, byte[] dest, int destPos, int length) {
copyInto(srcPos, (b, s, d, l) -> b.copyInto(s, dest, d, l), destPos, length);
}
@Override
public void copyInto(int srcPos, ByteBuffer dest, int destPos, int length) {
copyInto(srcPos, (b, s, d, l) -> b.copyInto(s, dest, d, l), destPos, length);
}
private void copyInto(int srcPos, CopyInto dest, int destPos, int length) {
if (length < 0) {
throw new IndexOutOfBoundsException("Length cannot be negative: " + length + '.');
}
if (srcPos < 0) {
throw indexOutOfBounds(srcPos, false);
}
if (srcPos + length > capacity) {
throw indexOutOfBounds(srcPos + length, false);
}
while (length > 0) {
var buf = (Buffer) chooseBuffer(srcPos, 0);
int toCopy = Math.min(buf.capacity() - subOffset, length);
dest.copyInto(buf, subOffset, destPos, toCopy);
srcPos += toCopy;
destPos += toCopy;
length -= toCopy;
}
}
@FunctionalInterface
private interface CopyInto {
void copyInto(Buffer src, int srcPos, int destPos, int length);
}
@Override
public void copyInto(int srcPos, Buffer dest, int destPos, int length) {
if (length < 0) {
throw new IndexOutOfBoundsException("Length cannot be negative: " + length + '.');
}
if (srcPos < 0) {
throw indexOutOfBounds(srcPos, false);
}
if (srcPos + length > capacity) {
throw indexOutOfBounds(srcPos + length, false);
}
// Iterate in reverse to account for src and dest buffer overlap.
// todo optimise by delegating to constituent buffers.
var cursor = openReverseCursor(srcPos + length - 1, length);
ByteOrder prevOrder = dest.order();
// We read longs in BE, in reverse, so they need to be flipped for writing.
dest.order(ByteOrder.LITTLE_ENDIAN);
try {
while (cursor.readLong()) {
length -= Long.BYTES;
dest.setLong(destPos + length, cursor.getLong());
}
while (cursor.readByte()) {
dest.setByte(destPos + --length, cursor.getByte());
}
} finally {
dest.order(prevOrder);
}
}
@Override
public ByteCursor openCursor() {
return openCursor(readerOffset(), readableBytes());
}
@Override
public ByteCursor openCursor(int fromOffset, int length) {
if (fromOffset < 0) {
throw new IllegalArgumentException("The fromOffset cannot be negative: " + fromOffset + '.');
}
if (length < 0) {
throw new IllegalArgumentException("The length cannot be negative: " + length + '.');
}
if (capacity < fromOffset + length) {
throw new IllegalArgumentException("The fromOffset+length is beyond the end of the buffer: " +
"fromOffset=" + fromOffset + ", length=" + length + '.');
}
int startBufferIndex = searchOffsets(fromOffset);
int off = fromOffset - offsets[startBufferIndex];
Buffer startBuf = bufs[startBufferIndex];
ByteCursor startCursor = startBuf.openCursor(off, Math.min(startBuf.capacity() - off, length));
return new ByteCursor() {
int index = fromOffset;
final int end = fromOffset + length;
int bufferIndex = startBufferIndex;
int initOffset = startCursor.currentOffset();
ByteCursor cursor = startCursor;
long longValue = -1;
byte byteValue = -1;
@Override
public boolean readLong() {
if (cursor.readLong()) {
longValue = cursor.getLong();
return true;
}
if (bytesLeft() >= Long.BYTES) {
longValue = nextLongFromBytes();
return true;
}
return false;
}
private long nextLongFromBytes() {
if (cursor.bytesLeft() == 0) {
nextCursor();
if (cursor.readLong()) {
return cursor.getLong();
}
}
long val = 0;
for (int i = 0; i < 8; i++) {
readByte();
val <<= 8;
val |= getByte();
}
return val;
}
@Override
public long getLong() {
return longValue;
}
@Override
public boolean readByte() {
if (cursor.readByte()) {
byteValue = cursor.getByte();
return true;
}
if (bytesLeft() > 0) {
nextCursor();
cursor.readByte();
byteValue = cursor.getByte();
return true;
}
return false;
}
private void nextCursor() {
bufferIndex++;
Buffer nextBuf = bufs[bufferIndex];
cursor = nextBuf.openCursor(0, Math.min(nextBuf.capacity(), bytesLeft()));
initOffset = 0;
}
@Override
public byte getByte() {
return byteValue;
}
@Override
public int currentOffset() {
int currOff = cursor.currentOffset();
index += currOff - initOffset;
initOffset = currOff;
return index;
}
@Override
public int bytesLeft() {
return end - currentOffset();
}
};
}
@Override
public ByteCursor openReverseCursor(int fromOffset, int length) {
if (fromOffset < 0) {
throw new IllegalArgumentException("The fromOffset cannot be negative: " + fromOffset + '.');
}
if (length < 0) {
throw new IllegalArgumentException("The length cannot be negative: " + length + '.');
}
if (fromOffset - length < -1) {
throw new IllegalArgumentException("The fromOffset-length would underflow the buffer: " +
"fromOffset=" + fromOffset + ", length=" + length + '.');
}
int startBufferIndex = searchOffsets(fromOffset);
int off = fromOffset - offsets[startBufferIndex];
Buffer startBuf = bufs[startBufferIndex];
ByteCursor startCursor = startBuf.openReverseCursor(off, Math.min(off + 1, length));
return new ByteCursor() {
int index = fromOffset;
final int end = fromOffset - length;
int bufferIndex = startBufferIndex;
int initOffset = startCursor.currentOffset();
ByteCursor cursor = startCursor;
long longValue = -1;
byte byteValue = -1;
@Override
public boolean readLong() {
if (cursor.readLong()) {
longValue = cursor.getLong();
return true;
}
if (bytesLeft() >= Long.BYTES) {
longValue = nextLongFromBytes();
return true;
}
return false;
}
private long nextLongFromBytes() {
if (cursor.bytesLeft() == 0) {
nextCursor();
if (cursor.readLong()) {
return cursor.getLong();
}
}
long val = 0;
for (int i = 0; i < 8; i++) {
readByte();
val <<= 8;
val |= getByte();
}
return val;
}
@Override
public long getLong() {
return longValue;
}
@Override
public boolean readByte() {
if (cursor.readByte()) {
byteValue = cursor.getByte();
return true;
}
if (bytesLeft() > 0) {
nextCursor();
cursor.readByte();
byteValue = cursor.getByte();
return true;
}
return false;
}
private void nextCursor() {
bufferIndex--;
Buffer nextBuf = bufs[bufferIndex];
int length = Math.min(nextBuf.capacity(), bytesLeft());
int offset = nextBuf.capacity() - 1;
cursor = nextBuf.openReverseCursor(offset, length);
initOffset = offset;
}
@Override
public byte getByte() {
return byteValue;
}
@Override
public int currentOffset() {
int currOff = cursor.currentOffset();
index -= initOffset - currOff;
initOffset = currOff;
return index;
}
@Override
public int bytesLeft() {
return currentOffset() - end;
}
};
}
@Override
public void ensureWritable(int size, boolean allowCompaction) {
if (!isOwned()) {
throw new IllegalStateException("Buffer is not owned. Only owned buffers can call ensureWritable.");
}
if (size < 0) {
throw new IllegalArgumentException("Cannot ensure writable for a negative size: " + size + '.');
}
if (readOnly) {
throw bufferIsReadOnly();
}
if (writableBytes() >= size) {
// We already have enough space.
return;
}
if (allowCompaction && size <= roff) {
// Let's see if we can solve some or all of the requested size with compaction.
// We always compact as much as is possible, regardless of size. This amortizes our work.
int compactableBuffers = 0;
for (Buffer buf : bufs) {
if (buf.capacity() != buf.readerOffset()) {
break;
}
compactableBuffers++;
}
if (compactableBuffers > 0) {
Buffer[] compactable;
if (compactableBuffers < bufs.length) {
compactable = new Buffer[compactableBuffers];
System.arraycopy(bufs, 0, compactable, 0, compactable.length);
System.arraycopy(bufs, compactable.length, bufs, 0, bufs.length - compactable.length);
System.arraycopy(compactable, 0, bufs, bufs.length - compactable.length, compactable.length);
} else {
compactable = bufs;
}
for (Buffer buf : compactable) {
buf.reset();
}
computeBufferOffsets();
if (writableBytes() >= size) {
// Now we have enough space.
return;
}
}
}
long newSize = capacity() + (long) size;
BufferAllocator.checkSize(newSize);
int growth = size - writableBytes();
Buffer extension = bufs.length == 0? allocator.allocate(growth) : allocator.allocate(growth, order());
unsafeExtendWith(extension);
}
void extendWith(Buffer extension) {
Objects.requireNonNull(extension, "Extension buffer cannot be null.");
if (!isOwned()) {
throw new IllegalStateException("This buffer cannot be extended because it is not in an owned state.");
}
if (bufs.length > 0 && extension.order() != order()) {
throw new IllegalArgumentException(
"This buffer uses " + order() + " byte order, and cannot be extended with " +
"a buffer that uses " + extension.order() + " byte order.");
}
if (bufs.length > 0 && extension.readOnly() != readOnly()) {
throw new IllegalArgumentException(
"This buffer is " + (readOnly? "read-only" : "writable") + ", " +
"and cannot be extended with a buffer that is " +
(extension.readOnly()? "read-only." : "writable."));
}
long extensionCapacity = extension.capacity();
if (extensionCapacity == 0) {
// Extending by a zero-sized buffer makes no difference. Especially since it's not allowed to change the
// capacity of buffers that are constiuents of composite buffers.
// This also ensures that methods like countComponents, and forEachReadable, do not have to worry about
// overflow in their component counters.
return;
}
long newSize = capacity() + extensionCapacity;
BufferAllocator.checkSize(newSize);
Buffer[] restoreTemp = bufs; // We need this to restore our buffer array, in case offset computations fail.
try {
if (extension instanceof CompositeBuffer) {
// If the extension is itself a composite buffer, then extend this one by all of the constituent
// component buffers.
CompositeBuffer compositeExtension = (CompositeBuffer) extension;
Buffer[] addedBuffers = compositeExtension.bufs;
Set<Buffer> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>());
duplicatesCheck.addAll(Arrays.asList(bufs));
duplicatesCheck.addAll(Arrays.asList(addedBuffers));
if (duplicatesCheck.size() < bufs.length + addedBuffers.length) {
throw extensionDuplicatesException();
}
for (Buffer addedBuffer : addedBuffers) {
addedBuffer.acquire();
}
int extendAtIndex = bufs.length;
bufs = Arrays.copyOf(bufs, extendAtIndex + addedBuffers.length);
System.arraycopy(addedBuffers, 0, bufs, extendAtIndex, addedBuffers.length);
computeBufferOffsets();
} else {
for (Buffer buf : restoreTemp) {
if (buf == extension) {
throw extensionDuplicatesException();
}
}
unsafeExtendWith(extension.acquire());
}
if (restoreTemp.length == 0) {
order = extension.order();
readOnly = extension.readOnly();
}
} catch (Exception e) {
bufs = restoreTemp;
throw e;
}
}
private static IllegalArgumentException extensionDuplicatesException() {
return new IllegalArgumentException(
"The composite buffer cannot be extended with the given extension," +
" as it would cause the buffer to have duplicate constituent buffers.");
}
private void unsafeExtendWith(Buffer extension) {
bufs = Arrays.copyOf(bufs, bufs.length + 1);
bufs[bufs.length - 1] = extension;
computeBufferOffsets();
}
@Override
public Buffer bifurcate() {
if (!isOwned()) {
throw new IllegalStateException("Cannot bifurcate a buffer that is not owned.");
}
if (bufs.length == 0) {
// Bifurcating a zero-length buffer is trivial.
return new CompositeBuffer(allocator, bufs, unsafeGetDrop(), true).order(order);
}
int i = searchOffsets(woff);
int off = woff - offsets[i];
Buffer[] bifs = Arrays.copyOf(bufs, off == 0? i : 1 + i);
bufs = Arrays.copyOfRange(bufs, off == bufs[i].capacity()? 1 + i : i, bufs.length);
if (off > 0 && bifs.length > 0 && off < bifs[bifs.length - 1].capacity()) {
bifs[bifs.length - 1] = bufs[0].bifurcate();
}
computeBufferOffsets();
try {
var compositeBuf = new CompositeBuffer(allocator, bifs, unsafeGetDrop(), true);
compositeBuf.order = order; // Preserve byte order even if bifs array is empty.
return compositeBuf;
} finally {
// Drop our references to the buffers in the bifs array. They belong to the new composite buffer now.
for (Buffer bif : bifs) {
bif.close();
}
}
}
@Override
public void compact() {
if (!isOwned()) {
throw new IllegalStateException("Buffer must be owned in order to compact.");
}
if (readOnly()) {
throw new IllegalStateException("Buffer must be writable in order to compact, but was read-only.");
}
int distance = roff;
if (distance == 0) {
return;
}
int pos = 0;
var oldOrder = order;
order = ByteOrder.BIG_ENDIAN;
try {
var cursor = openCursor();
while (cursor.readLong()) {
setLong(pos, cursor.getLong());
pos += Long.BYTES;
}
while (cursor.readByte()) {
setByte(pos, cursor.getByte());
pos++;
}
} finally {
order = oldOrder;
}
readerOffset(0);
writerOffset(woff - distance);
}
@Override
public int countComponents() {
int sum = 0;
for (Buffer buf : bufs) {
sum += buf.countComponents();
}
return sum;
}
@Override
public int countReadableComponents() {
int sum = 0;
for (Buffer buf : bufs) {
sum += buf.countReadableComponents();
}
return sum;
}
@Override
public int countWritableComponents() {
int sum = 0;
for (Buffer buf : bufs) {
sum += buf.countWritableComponents();
}
return sum;
}
@Override
public <E extends Exception> int forEachReadable(int initialIndex, ReadableComponentProcessor<E> processor)
throws E {
checkReadBounds(readerOffset(), Math.max(1, readableBytes()));
int visited = 0;
for (Buffer buf : bufs) {
if (buf.readableBytes() > 0) {
int count = buf.forEachReadable(visited + initialIndex, processor);
if (count > 0) {
visited += count;
} else {
visited = -visited + count;
break;
}
}
}
return visited;
}
@Override
public <E extends Exception> int forEachWritable(int initialIndex, WritableComponentProcessor<E> processor)
throws E {
checkWriteBounds(writerOffset(), Math.max(1, writableBytes()));
int visited = 0;
for (Buffer buf : bufs) {
if (buf.writableBytes() > 0) {
int count = buf.forEachWritable(visited + initialIndex, processor);
if (count > 0) {
visited += count;
} else {
visited = -visited + count;
break;
}
}
}
return visited;
}
// <editor-fold defaultstate="collapsed" desc="Primitive accessors.">
@Override
public byte readByte() {
return prepRead(Byte.BYTES).readByte();
}
@Override
public byte getByte(int roff) {
return prepGet(roff, Byte.BYTES).getByte(subOffset);
}
@Override
public int readUnsignedByte() {
return prepRead(Byte.BYTES).readUnsignedByte();
}
@Override
public int getUnsignedByte(int roff) {
return prepGet(roff, Byte.BYTES).getUnsignedByte(subOffset);
}
@Override
public Buffer writeByte(byte value) {
prepWrite(Byte.BYTES).writeByte(value);
return this;
}
@Override
public Buffer setByte(int woff, byte value) {
prepWrite(woff, Byte.BYTES).setByte(subOffset, value);
return this;
}
@Override
public Buffer writeUnsignedByte(int value) {
prepWrite(Byte.BYTES).writeUnsignedByte(value);
return this;
}
@Override
public Buffer setUnsignedByte(int woff, int value) {
prepWrite(woff, Byte.BYTES).setUnsignedByte(subOffset, value);
return this;
}
@Override
public char readChar() {
return prepRead(2).readChar();
}
@Override
public char getChar(int roff) {
return prepGet(roff, 2).getChar(subOffset);
}
@Override
public Buffer writeChar(char value) {
prepWrite(2).writeChar(value);
return this;
}
@Override
public Buffer setChar(int woff, char value) {
prepWrite(woff, 2).setChar(subOffset, value);
return this;
}
@Override
public short readShort() {
return prepRead(Short.BYTES).readShort();
}
@Override
public short getShort(int roff) {
return prepGet(roff, Short.BYTES).getShort(subOffset);
}
@Override
public int readUnsignedShort() {
return prepRead(Short.BYTES).readShort();
}
@Override
public int getUnsignedShort(int roff) {
return prepGet(roff, Short.BYTES).getUnsignedShort(subOffset);
}
@Override
public Buffer writeShort(short value) {
prepWrite(Short.BYTES).writeShort(value);
return this;
}
@Override
public Buffer setShort(int woff, short value) {
prepWrite(woff, Short.BYTES).setShort(subOffset, value);
return this;
}
@Override
public Buffer writeUnsignedShort(int value) {
prepWrite(Short.BYTES).writeUnsignedShort(value);
return this;
}
@Override
public Buffer setUnsignedShort(int woff, int value) {
prepWrite(woff, Short.BYTES).setUnsignedShort(subOffset, value);
return this;
}
@Override
public int readMedium() {
return prepRead(3).readMedium();
}
@Override
public int getMedium(int roff) {
return prepGet(roff, 3).getMedium(subOffset);
}
@Override
public int readUnsignedMedium() {
return prepRead(3).readMedium();
}
@Override
public int getUnsignedMedium(int roff) {
return prepGet(roff, 3).getMedium(subOffset);
}
@Override
public Buffer writeMedium(int value) {