Debian Codegraph @

proton-j/src/main/java/org/apache/qpid/proton/codec/CompositeReadableBuffer.java

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.qpid.proton.codec;
18
19 import java.nio.BufferUnderflowException;
20 import java.nio.ByteBuffer;
21 import java.nio.CharBuffer;
22 import java.nio.InvalidMarkException;
23 import java.nio.charset.CharacterCodingException;
24 import java.nio.charset.CharsetDecoder;
25 import java.nio.charset.CoderResult;
26 import java.nio.charset.StandardCharsets;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.List;
30
31 /**
32 * ReadableBuffer implementation whose content is made up of one or more
33 * byte arrays.
34 */
35 public class CompositeReadableBuffer implements ReadableBuffer {
36
37 private static final List<byte[]> EMPTY_LIST = Collections.unmodifiableList(new ArrayList<byte[]>());
38 private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]);
39 private static final CompositeReadableBuffer EMPTY_SLICE = new CompositeReadableBuffer(false);
40 private static int UNSET_MARK = -1;
41
42 private static final int SHORT_BYTES = 2;
43 private static final int INT_BYTES = 4;
44 private static final int LONG_BYTES = 8;
45
46 private ArrayList<byte[]> contents;
47
48 // Track active array and our offset into it.
49 private int currentArrayIndex = -1;
50 private byte[] currentArray;
51 private int currentOffset;
52
53 // State global to the buffer.
54 private int position;
55 private int limit;
56 private int capacity;
57 private int mark = -1;
58 private boolean compactable = true;
59
60 /**
61 * Creates a default empty composite buffer
62 */
63 public CompositeReadableBuffer() {
64 }
65
66 private CompositeReadableBuffer(byte[] array, int offset) {
67 this.currentArray = array;
68 this.currentOffset = offset;
69 if(array != null) {
70 this.capacity = array.length;
71 }
72 this.limit = capacity;
73 }
74
75 private CompositeReadableBuffer(boolean compactable) {
76 this.compactable = compactable;
77 }
78
79 public List<byte[]> getArrays() {
80 return contents == null ? EMPTY_LIST : Collections.unmodifiableList(contents);
81 }
82
83 public int getCurrentIndex() {
84 return currentArrayIndex;
85 }
86
87 /**
88 * Gets the current position index in the current backing array, which represents the current buffer position.
89 *
90 * This value includes any buffer position movement, and resets when moving across array segments, so it only
91 * gives the starting offset for the first array if the buffer position is 0.
92 *
93 * Value may be out of array bounds if the the buffer currently has no content remaining.
94 *
95 * @return the position index in the current array representing the current buffer position.
96 */
97 public int getCurrentArrayPosition() {
98 return currentOffset;
99 }
100
101 @Override
102 public boolean hasArray() {
103 return currentArray != null && (contents == null || contents.size() == 1);
104 }
105
106 @Override
107 public int capacity() {
108 return capacity;
109 }
110
111 @Override
112 public byte[] array() {
113 if (hasArray()) {
114 return currentArray;
115 }
116
117 throw new UnsupportedOperationException("Buffer not backed by a single array");
118 }
119
120 @Override
121 public int arrayOffset() {
122 if (hasArray()) {
123 return currentOffset - position;
124 }
125
126 throw new UnsupportedOperationException("Buffer not backed by a single array");
127 }
128
129 @Override
130 public byte get() {
131 if (position == limit) {
132 throw new BufferUnderflowException();
133 }
134
135 final byte result = currentArray[currentOffset++];
136 position++;
137 maybeMoveToNextArray();
138
139 return result;
140 }
141
142 @Override
143 public byte get(int index) {
144 if (index < 0 || index >= limit) {
145 throw new IndexOutOfBoundsException("The given index is not valid: " + index);
146 }
147
148 byte result = 0;
149
150 if (index == position) {
151 result = currentArray[currentOffset];
152 } else if (index < position) {
153 result = getBackwards(index);
154 } else {
155 result = getForward(index);
156 }
157
158 return result;
159 }
160
161 private byte getForward(int index) {
162 byte result = 0;
163
164 int currentArrayIndex = this.currentArrayIndex;
165 int currentOffset = this.currentOffset;
166 byte[] currentArray = this.currentArray;
167
168 for (int amount = index - position; amount >= 0;) {
169 if (amount < currentArray.length - currentOffset) {
170 result = currentArray[currentOffset + amount];
171 break;
172 } else {
173 amount -= currentArray.length - currentOffset;
174 currentArray = contents.get(++currentArrayIndex);
175 currentOffset = 0;
176 }
177 }
178
179 return result;
180 }
181
182 private byte getBackwards(int index) {
183 byte result = 0;
184
185 int currentArrayIndex = this.currentArrayIndex;
186 int currentOffset = this.currentOffset;
187 byte[] currentArray = this.currentArray;
188
189 for (int amount = position - index; amount >= 0;) {
190 if ((currentOffset - amount) >= 0) {
191 result = currentArray[currentOffset - amount];
192 break;
193 } else {
194 amount -= currentOffset;
195 currentArray = contents.get(--currentArrayIndex);
196 currentOffset = currentArray.length;
197 }
198 }
199
200 return result;
201 }
202
203 @Override
204 public int getInt() {
205 if (remaining() < INT_BYTES) {
206 throw new BufferUnderflowException();
207 }
208
209 int result = 0;
210
211 if (currentArray.length - currentOffset >= 4) {
212 result = (int)(currentArray[currentOffset++] & 0xFF) << 24 |
213 (int)(currentArray[currentOffset++] & 0xFF) << 16 |
214 (int)(currentArray[currentOffset++] & 0xFF) << 8 |
215 (int)(currentArray[currentOffset++] & 0xFF) << 0;
216 maybeMoveToNextArray();
217 } else {
218 for (int i = INT_BYTES - 1; i >= 0; --i) {
219 result |= (int)(currentArray[currentOffset++] & 0xFF) << (i * Byte.SIZE);
220 maybeMoveToNextArray();
221 }
222 }
223
224 position += 4;
225
226 return result;
227 }
228
229 @Override
230 public long getLong() {
231 if (remaining() < LONG_BYTES) {
232 throw new BufferUnderflowException();
233 }
234
235 long result = 0;
236
237 if (currentArray.length - currentOffset >= 8) {
238 result = (long)(currentArray[currentOffset++] & 0xFF) << 56 |
239 (long)(currentArray[currentOffset++] & 0xFF) << 48 |
240 (long)(currentArray[currentOffset++] & 0xFF) << 40 |
241 (long)(currentArray[currentOffset++] & 0xFF) << 32 |
242 (long)(currentArray[currentOffset++] & 0xFF) << 24 |
243 (long)(currentArray[currentOffset++] & 0xFF) << 16 |
244 (long)(currentArray[currentOffset++] & 0xFF) << 8 |
245 (long)(currentArray[currentOffset++] & 0xFF) << 0;
246 maybeMoveToNextArray();
247 } else {
248 for (int i = LONG_BYTES - 1; i >= 0; --i) {
249 result |= (long)(currentArray[currentOffset++] & 0xFF) << (i * Byte.SIZE);
250 maybeMoveToNextArray();
251 }
252 }
253
254 position += 8;
255
256 return result;
257 }
258
259 @Override
260 public short getShort() {
261 if (remaining() < SHORT_BYTES) {
262 throw new BufferUnderflowException();
263 }
264
265 short result = 0;
266
267 for (int i = SHORT_BYTES - 1; i >= 0; --i) {
268 result |= (currentArray[currentOffset++] & 0xFF) << (i * Byte.SIZE);
269 maybeMoveToNextArray();
270 }
271
272 position += 2;
273
274 return result;
275 }
276
277 @Override
278 public float getFloat() {
279 return Float.intBitsToFloat(getInt());
280 }
281
282 @Override
283 public double getDouble() {
284 return Double.longBitsToDouble(getLong());
285 }
286
287 @Override
288 public CompositeReadableBuffer get(byte[] data) {
289 return get(data, 0, data.length);
290 }
291
292 @Override
293 public CompositeReadableBuffer get(byte[] data, int offset, int length) {
294 validateReadTarget(data.length, offset, length);
295
296 if (length > remaining()) {
297 throw new BufferUnderflowException();
298 }
299
300 int copied = 0;
301 while (length > 0) {
302 final int chunk = Math.min((currentArray.length - currentOffset), length);
303 System.arraycopy(currentArray, currentOffset, data, offset + copied, chunk);
304
305 currentOffset += chunk;
306 length -= chunk;
307 copied += chunk;
308
309 maybeMoveToNextArray();
310 }
311
312 position += copied;
313
314 return this;
315 }
316
317 @Override
318 public CompositeReadableBuffer get(WritableBuffer target) {
319 int length = Math.min(target.remaining(), remaining());
320
321 do {
322 final int chunk = Math.min((currentArray.length - currentOffset), length);
323
324 if (chunk == 0) {
325 break; // This buffer is out of data
326 }
327
328 target.put(currentArray, currentOffset, chunk);
329
330 currentOffset += chunk;
331 position += chunk;
332 length -= chunk;
333
334 maybeMoveToNextArray();
335 } while (length > 0);
336
337 return this;
338 }
339
340 @Override
341 public CompositeReadableBuffer position(int position) {
342 if (position < 0 || position > limit) {
343 throw new IllegalArgumentException("position must be non-negative and no greater than the limit");
344 }
345
346 int moveBy = position - this.position;
347 if (moveBy >= 0) {
348 moveForward(moveBy);
349 } else {
350 moveBackwards(Math.abs(moveBy));
351 }
352
353 this.position = position;
354
355 if (mark > position) {
356 mark = UNSET_MARK;
357 }
358
359 return this;
360 }
361
362 private void moveForward(int moveBy) {
363 while (moveBy > 0) {
364 if (moveBy < currentArray.length - currentOffset) {
365 currentOffset += moveBy;
366 break;
367 } else {
368 moveBy -= currentArray.length - currentOffset;
369 if (currentArrayIndex != -1 && currentArrayIndex < contents.size() - 1) {
370 currentArray = contents.get(++currentArrayIndex);
371 currentOffset = 0;
372 } else {
373 currentOffset = currentArray.length;
374 }
375 }
376 }
377 }
378
379 private void moveBackwards(int moveBy) {
380 while (moveBy > 0) {
381 if ((currentOffset - moveBy) >= 0) {
382 currentOffset -= moveBy;
383 break;
384 } else {
385 moveBy -= currentOffset;
386 currentArray = contents.get(--currentArrayIndex);
387 currentOffset = currentArray.length;
388 }
389 }
390 }
391
392 @Override
393 public int position() {
394 return position;
395 }
396
397 @Override
398 public CompositeReadableBuffer slice() {
399 int newCapacity = limit() - position();
400
401 final CompositeReadableBuffer result;
402
403 if (newCapacity == 0) {
404 result = EMPTY_SLICE;
405 } else {
406 result = new CompositeReadableBuffer(currentArray, currentOffset);
407 result.contents = contents;
408 result.currentArrayIndex = currentArrayIndex;
409 result.capacity = newCapacity;
410 result.limit = newCapacity;
411 result.position = 0;
412 result.compactable = false;
413 }
414
415 return result;
416 }
417
418 @Override
419 public CompositeReadableBuffer flip() {
420 limit = position;
421 position(0); // Move by index to avoid corrupting a slice.
422 mark = UNSET_MARK;
423
424 return this;
425 }
426
427 @Override
428 public CompositeReadableBuffer limit(int limit) {
429 if (limit < 0 || limit > capacity) {
430 throw new IllegalArgumentException("limit must be non-negative and no greater than the capacity");
431 }
432
433 if (mark > limit) {
434 mark = UNSET_MARK;
435 }
436
437 if (position > limit) {
438 position(limit);
439 }
440
441 this.limit = limit;
442
443 return this;
444 }
445
446 @Override
447 public int limit() {
448 return limit;
449 }
450
451 @Override
452 public CompositeReadableBuffer mark() {
453 this.mark = position;
454 return this;
455 }
456
457 @Override
458 public CompositeReadableBuffer reset() {
459 if (mark < 0) {
460 throw new InvalidMarkException();
461 }
462
463 position(mark);
464
465 return this;
466 }
467
468 @Override
469 public CompositeReadableBuffer rewind() {
470 return position(0);
471 }
472
473 @Override
474 public CompositeReadableBuffer clear() {
475 mark = UNSET_MARK;
476 limit = capacity;
477
478 return position(0);
479 }
480
481 @Override
482 public int remaining() {
483 return limit - position;
484 }
485
486 @Override
487 public boolean hasRemaining() {
488 return remaining() > 0;
489 }
490
491 @Override
492 public CompositeReadableBuffer duplicate() {
493 CompositeReadableBuffer duplicated =
494 new CompositeReadableBuffer(currentArray, currentOffset);
495
496 if (contents != null) {
497 duplicated.contents = new ArrayList<>(contents);
498 }
499
500 duplicated.capacity = capacity;
501 duplicated.currentArrayIndex = currentArrayIndex;
502 duplicated.limit = limit;
503 duplicated.position = position;
504 duplicated.mark = mark;
505 duplicated.compactable = compactable; // A slice duplicated should not allow compaction.
506
507 return duplicated;
508 }
509
510 @Override
511 public ByteBuffer byteBuffer() {
512 int viewSpan = limit() - position();
513
514 final ByteBuffer result;
515
516 if (viewSpan == 0) {
517 result = EMPTY_BUFFER;
518 } else if (viewSpan <= currentArray.length - currentOffset) {
519 result = ByteBuffer.wrap(currentArray, currentOffset, viewSpan);
520 } else {
521 result = buildByteBuffer(viewSpan);
522 }
523
524 return result.asReadOnlyBuffer();
525 }
526
527 private ByteBuffer buildByteBuffer(int span) {
528 byte[] compactedView = new byte[span];
529 int arrayIndex = currentArrayIndex;
530
531 // Take whatever is left from the current array;
532 System.arraycopy(currentArray, currentOffset, compactedView, 0, currentArray.length - currentOffset);
533 int copied = currentArray.length - currentOffset;
534
535 while (copied < span) {
536 byte[] next = contents.get(++arrayIndex);
537 final int length = Math.min(span - copied, next.length);
538 System.arraycopy(next, 0, compactedView, copied, length);
539 copied += length;
540 }
541
542 return ByteBuffer.wrap(compactedView);
543 }
544
545 @Override
546 public String readUTF8() throws CharacterCodingException {
547 return readString(StandardCharsets.UTF_8.newDecoder());
548 }
549
550 @Override
551 public String readString(CharsetDecoder decoder) throws CharacterCodingException {
552 if (!hasRemaining()) {
553 return "";
554 }
555
556 CharBuffer decoded = null;
557
558 if (hasArray()) {
559 decoded = decoder.decode(ByteBuffer.wrap(currentArray, currentOffset, remaining()));
560 } else {
561 decoded = readStringFromComponents(decoder);
562 }
563
564 // Ensure that all currently readable bytes are consumed.
565 position(limit);
566
567 return decoded.toString();
568 }
569
570 private CharBuffer readStringFromComponents(CharsetDecoder decoder) throws CharacterCodingException {
571 int size = (int)(remaining() * decoder.averageCharsPerByte());
572 CharBuffer decoded = CharBuffer.allocate(size);
573
574 int arrayIndex = currentArrayIndex;
575 final int viewSpan = limit() - position();
576 int processed = Math.min(currentArray.length - currentOffset, viewSpan);
577 ByteBuffer wrapper = ByteBuffer.wrap(currentArray, currentOffset, processed);
578
579 CoderResult step = CoderResult.OVERFLOW;
580
581 do {
582 boolean endOfInput = processed == viewSpan;
583 step = decoder.decode(wrapper, decoded, endOfInput);
584
585 if (step.isUnderflow()) {
586 if (endOfInput) {
587 step = decoder.flush(decoded);
588 break;
589 } if (wrapper.hasRemaining()) {
590 final int unprocessed = wrapper.remaining();
591 final byte[] next = contents.get(++arrayIndex);
592 final ByteBuffer previous = wrapper;
593 final int nextAmount = Math.min(next.length, viewSpan - processed);
594 wrapper = ByteBuffer.allocate(unprocessed + nextAmount);
595
596 wrapper.put(previous);
597 wrapper.put(next, 0, nextAmount);
598 processed += nextAmount;
599
600 wrapper.flip();
601 } else {
602 final byte[] next = contents.get(++arrayIndex);
603 final int wrapSize = Math.min(next.length, viewSpan - processed);
604 wrapper = ByteBuffer.wrap(next, 0, wrapSize);
605 processed += wrapSize;
606 }
607 } else if (step.isOverflow()) {
608 size = 2 * size + 1;
609 CharBuffer upsized = CharBuffer.allocate(size);
610 decoded.flip();
611 upsized.put(decoded);
612 decoded = upsized;
613 continue;
614 }
615 } while (!step.isError());
616
617 if (step.isError()) {
618 step.throwException();
619 }
620
621 return (CharBuffer) decoded.flip();
622 }
623
624 /**
625 * Compact the buffer dropping arrays that have been consumed by previous
626 * reads from this Composite buffer. The limit is reset to the new capacity
627 */
628 @Override
629 public CompositeReadableBuffer reclaimRead() {
630 if (!compactable || (currentArray == null && contents == null)) {
631 return this;
632 }
633
634 int totalCompaction = 0;
635 int totalRemovals = 0;
636
637 for (; totalRemovals < currentArrayIndex; ++totalRemovals) {
638 byte[] element = contents.remove(0);
639 totalCompaction += element.length;
640 }
641
642 currentArrayIndex -= totalRemovals;
643
644 if (currentArray.length == currentOffset) {
645 totalCompaction += currentArray.length;
646
647 // If we are sitting on the end of the data (length == offest) then
648 // we are also at the last element in the ArrayList if one is currently
649 // in use, so remove the data and release the list.
650 if (currentArrayIndex == 0) {
651 contents.clear();
652 contents = null;
653 }
654
655 currentArray = null;
656 currentArrayIndex = -1;
657 currentOffset = 0;
658 }
659
660 position -= totalCompaction;
661 limit = capacity -= totalCompaction;
662
663 if (mark != UNSET_MARK) {
664 mark -= totalCompaction;
665 }
666
667 return this;
668 }
669
670 /**
671 * Adds the given array into the composite buffer at the end.
672 * <p>
673 * The appended array is not copied so changes to the source array are visible in this
674 * buffer and vice versa. If this composite was empty than it would return true for the
675 * {@link #hasArray()} method until another array is appended.
676 * <p>
677 * Calling this method resets the limit to the new capacity.
678 *
679 * @param array
680 * The array to add to this composite buffer.
681 *
682 * @throws IllegalArgumentException if the array is null or zero size.
683 * @throws IllegalStateException if the buffer does not allow appends.
684 *
685 * @return a reference to this {@link CompositeReadableBuffer}.
686 */
687 public CompositeReadableBuffer append(byte[] array) {
688 validateAppendable();
689
690 if (array == null || array.length == 0) {
691 throw new IllegalArgumentException("Array must not be empty or null");
692 }
693
694 if (currentArray == null) {
695 currentArray = array;
696 currentOffset = 0;
697 } else if (contents == null) {
698 contents = new ArrayList<>();
699 contents.add(currentArray);
700 contents.add(array);
701 currentArrayIndex = 0;
702 // If we exhausted the array previously then it should move to the new one now.
703 maybeMoveToNextArray();
704 } else {
705 contents.add(array);
706 // If we exhausted the list previously then it didn't move onward at the time, so it should now.
707 maybeMoveToNextArray();
708 }
709
710 capacity += array.length;
711 limit = capacity;
712
713 return this;
714 }
715
716 private void validateAppendable() {
717 if (!compactable) {
718 throw new IllegalStateException();
719 }
720 }
721
722 private void validateBuffer(ReadableBuffer buffer) {
723 if (buffer == null) {
724 throw new IllegalArgumentException("A non-null buffer must be provided");
725 }
726
727 if (!buffer.hasRemaining()) {
728 throw new IllegalArgumentException("Buffer has no remaining content to append");
729 }
730 }
731
732 /**
733 * Adds the given composite buffer contents (from current position, up to the limit) into this
734 * composite buffer at the end. The source buffer position will be set to its limit.
735 * <p>
736 * The appended buffer contents are not copied wherever possible, so changes to the source
737 * arrays are typically visible in this buffer and vice versa. Exceptions include where the
738 * source buffer position is not located at the start of its current backing array, or where the
739 * given buffer has a limit that doesn't encompass all of the last array used, and
740 * so the remainder of that arrays contents must be copied first to append here.
741 * <p>
742 * Calling this method resets the limit to the new capacity.
743 *
744 * @param buffer
745 * the buffer with contents to append into this composite buffer.
746 *
747 * @throws IllegalArgumentException if the given buffer is null or has zero remainder.
748 * @throws IllegalStateException if the buffer does not allow appends.
749 *
750 * @return a reference to this {@link CompositeReadableBuffer}.
751 */
752 public CompositeReadableBuffer append(CompositeReadableBuffer buffer) {
753 validateAppendable();
754 validateBuffer(buffer);
755
756 byte[] chunk;
757 do {
758 int bufferRemaining = buffer.remaining();
759 int arrayRemaining = buffer.currentArray.length - buffer.currentOffset;
760 if (buffer.currentOffset > 0 || bufferRemaining < arrayRemaining) {
761 int length = Math.min(arrayRemaining, bufferRemaining);
762 chunk = new byte[length];
763 System.arraycopy(buffer.currentArray, buffer.currentOffset, chunk, 0, length);
764 } else {
765 chunk = buffer.currentArray;
766 }
767
768 append(chunk);
769
770 buffer.position(buffer.position() + chunk.length);
771 } while (buffer.hasRemaining());
772
773 return this;
774 }
775
776 /**
777 * Adds the given readable buffer contents (from current position, up to the limit) into this
778 * composite buffer at the end. The source buffer position will be set to its limit.
779 * <p>
780 * The appended buffer contents are not copied wherever possible, so changes to the source
781 * arrays are typically visible in this buffer and vice versa. Exceptions are where the
782 * source buffer is not backed by an array, or where the source buffer position is not
783 * located at the start of its backing array, and so the remainder of the contents must
784 * be copied first to append here.
785 * <p>
786 * Calling this method resets the limit to the new capacity.
787 *
788 * @param buffer
789 * the buffer with contents to append into this composite buffer.
790 *
791 * @throws IllegalArgumentException if the given buffer is null or has zero remainder.
792 * @throws IllegalStateException if the buffer does not allow appends.
793 *
794 * @return a reference to this {@link CompositeReadableBuffer}.
795 */
796 public CompositeReadableBuffer append(ReadableBuffer buffer) {
797 if(buffer instanceof CompositeReadableBuffer) {
798 append((CompositeReadableBuffer) buffer);
799 } else {
800 validateAppendable();
801 validateBuffer(buffer);
802
803 if (buffer.hasArray()) {
804 byte[] chunk = buffer.array();
805
806 int bufferRemaining = buffer.remaining();
807 if (buffer.arrayOffset() > 0 || bufferRemaining < chunk.length) {
808 chunk = new byte[bufferRemaining];
809 System.arraycopy(buffer.array(), buffer.arrayOffset(), chunk, 0, bufferRemaining);
810 }
811
812 append(chunk);
813
814 buffer.position(buffer.position() + chunk.length);
815 } else {
816 byte[] chunk = new byte[buffer.remaining()];
817 buffer.get(chunk);
818
819 append(chunk);
820 }
821 }
822
823 return this;
824 }
825
826 @Override
827 public int hashCode() {
828 int hash = 1;
829 int remaining = remaining();
830
831 if (currentArrayIndex < 0 || remaining <= currentArray.length - currentOffset) {
832 while (remaining > 0) {
833 hash = 31 * hash + currentArray[currentOffset + --remaining];
834 }
835 } else {
836 hash = hashCodeFromComponents();
837 }
838
839 return hash;
840 }
841
842 private int hashCodeFromComponents() {
843 int hash = 1;
844 byte[] array = currentArray;
845 int arrayOffset = currentOffset;
846 int arraysIndex = currentArrayIndex;
847
848 // Run to the the array and offset where we want to start the hash from
849 final int remaining = remaining();
850 for (int moveBy = remaining; moveBy > 0; ) {
851 if (moveBy <= array.length - arrayOffset) {
852 arrayOffset += moveBy;
853 break;
854 } else {
855 moveBy -= array.length - arrayOffset;
856 array = contents.get(++arraysIndex);
857 arrayOffset = 0;
858 }
859 }
860
861 // Now run backwards through the arrays to match what ByteBuffer would produce
862 for (int moveBy = remaining; moveBy > 0; moveBy--) {
863 hash = 31 * hash + array[--arrayOffset];
864 if (arrayOffset == 0 && arraysIndex > 0) {
865 array = contents.get(--arraysIndex);
866 arrayOffset = array.length;
867 }
868 }
869
870 return hash;
871 }
872
873 @Override
874 public boolean equals(Object other) {
875 if (this == other) {
876 return true;
877 }
878
879 if (!(other instanceof ReadableBuffer)) {
880 return false;
881 }
882
883 ReadableBuffer buffer = (ReadableBuffer) other;
884 final int remaining = remaining();
885 if (remaining != buffer.remaining()) {
886 return false;
887 }
888
889 if (remaining == 0) {
890 // No content to compare, and we already checked 'remaining' is equal. Protects from NPE below.
891 return true;
892 }
893
894 if (hasArray() || remaining <= currentArray.length - currentOffset) {
895 // Either there is only one array, or the span to compare is within a single chunk of this buffer,
896 // allowing the compare to directly access the underlying array instead of using slower get methods.
897 return equals(currentArray, currentOffset, remaining, buffer);
898 } else {
899 return equals(this, buffer);
900 }
901 }
902
903 private static boolean equals(byte[] buffer, int start, int length, ReadableBuffer other) {
904 final int position = other.position();
905 for (int i = 0; i < length; i++) {
906 if (buffer[start + i] != other.get(position + i)) {
907 return false;
908 }
909 }
910 return true;
911 }
912
913 private static boolean equals(ReadableBuffer buffer, ReadableBuffer other) {
914 final int origPos = buffer.position();
915 try {
916 for (int i = other.position(); buffer.hasRemaining(); i++) {
917 if (!equals(buffer.get(), other.get(i))) {
918 return false;
919 }
920 }
921 return true;
922 } finally {
923 buffer.position(origPos);
924 }
925 }
926
927 @Override
928 public String toString() {
929 StringBuffer builder = new StringBuffer();
930 builder.append("CompositeReadableBuffer");
931 builder.append("{ pos=");
932 builder.append(position());
933 builder.append(" limit=");
934 builder.append(limit());
935 builder.append(" capacity=");
936 builder.append(capacity());
937 builder.append(" }");
938
939 return builder.toString();
940 }
941
942 private static boolean equals(byte x, byte y) {
943 return x == y;
944 }
945
946 private void maybeMoveToNextArray() {
947 if (currentArray.length == currentOffset) {
948 if (currentArrayIndex >= 0 && currentArrayIndex < (contents.size() - 1)) {
949 currentArray = contents.get(++currentArrayIndex);
950 currentOffset = 0;
951 }
952 }
953 }
954
955 private static void validateReadTarget(int destSize, int offset, int length) {
956 if ((offset | length) < 0) {
957 throw new IndexOutOfBoundsException("offset and legnth must be non-negative");
958 }
959
960 if (((long) offset + (long) length) > destSize) {
961 throw new IndexOutOfBoundsException("target is to small for specified read size");
962 }
963 }
964 }