23
23
import java .nio .InvalidMarkException ;
24
24
import java .util .ArrayDeque ;
25
25
import java .util .Deque ;
26
+ import java .util .Queue ;
26
27
import javax .annotation .Nullable ;
27
28
28
29
/**
@@ -38,6 +39,7 @@ public class CompositeReadableBuffer extends AbstractReadableBuffer {
38
39
private final Deque <ReadableBuffer > readableBuffers ;
39
40
private Deque <ReadableBuffer > rewindableBuffers ;
40
41
private int readableBytes ;
42
+ private final Queue <ReadableBuffer > buffers = new ArrayDeque <ReadableBuffer >(2 );
41
43
private boolean marked ;
42
44
43
45
public CompositeReadableBuffer (int initialCapacity ) {
@@ -159,6 +161,31 @@ public void readBytes(OutputStream dest, int length) throws IOException {
159
161
execute (STREAM_OP , length , dest , 0 );
160
162
}
161
163
164
+ /**
165
+ * Reads {@code length} bytes from this buffer and writes them to the destination buffer.
166
+ * Increments the read position by {@code length}. If the required bytes are not readable, throws
167
+ * {@link IndexOutOfBoundsException}.
168
+ *
169
+ * @param dest the destination buffer to receive the bytes.
170
+ * @param length the number of bytes to be copied.
171
+ * @throws IndexOutOfBoundsException if required bytes are not readable
172
+ */
173
+ public void readBytes (CompositeReadableBuffer dest , int length ) {
174
+ checkReadable (length );
175
+ readableBytes -= length ;
176
+
177
+ while (length > 0 ) {
178
+ ReadableBuffer buffer = buffers .peek ();
179
+ if (buffer .readableBytes () > length ) {
180
+ dest .addBuffer (buffer .readBytes (length ));
181
+ length = 0 ;
182
+ } else {
183
+ dest .addBuffer (buffers .poll ());
184
+ length -= buffer .readableBytes ();
185
+ }
186
+ }
187
+ }
188
+
162
189
@ Override
163
190
public ReadableBuffer readBytes (int length ) {
164
191
if (length <= 0 ) {
0 commit comments