31 package com.google.protobuf;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.nio.ByteBuffer;
38 import java.util.Iterator;
40 class IterableByteBufferInputStream
extends InputStream {
42 private Iterator<ByteBuffer> iterator;
44 private ByteBuffer currentByteBuffer;
52 private int currentIndex;
54 private int currentByteBufferPos;
56 private boolean hasArray;
61 private byte[] currentArray;
63 private int currentArrayOffset;
68 private long currentAddress;
70 IterableByteBufferInputStream(Iterable<ByteBuffer>
data) {
71 iterator =
data.iterator();
73 for (ByteBuffer unused :
data) {
78 if (!getNextByteBuffer()) {
79 currentByteBuffer = EMPTY_BYTE_BUFFER;
81 currentByteBufferPos = 0;
86 private boolean getNextByteBuffer() {
88 if (!iterator.hasNext()) {
91 currentByteBuffer = iterator.next();
92 currentByteBufferPos = currentByteBuffer.position();
93 if (currentByteBuffer.hasArray()) {
95 currentArray = currentByteBuffer.array();
96 currentArrayOffset = currentByteBuffer.arrayOffset();
99 currentAddress = UnsafeUtil.addressOffset(currentByteBuffer);
105 private void updateCurrentByteBufferPos(
int numberOfBytesRead) {
106 currentByteBufferPos += numberOfBytesRead;
107 if (currentByteBufferPos == currentByteBuffer.limit()) {
113 public int read() throws IOException {
114 if (currentIndex == dataSize) {
118 int result = currentArray[currentByteBufferPos + currentArrayOffset] & 0xFF;
119 updateCurrentByteBufferPos(1);
122 int result = UnsafeUtil.getByte(currentByteBufferPos + currentAddress) & 0xFF;
123 updateCurrentByteBufferPos(1);
130 if (currentIndex == dataSize) {
133 int remaining = currentByteBuffer.limit() - currentByteBufferPos;
140 updateCurrentByteBufferPos(
length);
142 int prevPos = currentByteBuffer.position();
143 currentByteBuffer.position(currentByteBufferPos);
145 currentByteBuffer.position(prevPos);
146 updateCurrentByteBufferPos(
length);