Created
September 19, 2018 14:13
-
-
Save kogupta/677d2f585e4b7687a8349b6410e7cd76 to your computer and use it in GitHub Desktop.
Iterating over a jdk ByteBuffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class ByteBufIterator { | |
public static void main(String[] args) { | |
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES * 10); | |
for (int i = 0; i < 10; i++) buffer.putInt(i); | |
buffer.flip(); // dont forget to flip!!! | |
// read in groups of 3 | |
// so 4 BBs, 3 of size 3 and 1 of 1 | |
final int end = buffer.limit(), stride = 3 * Integer.BYTES; | |
for (int start = 0; start != end; start = buffer.limit()) { | |
int delta = Math.min(end - start, stride); | |
buffer.position(start).limit(start + delta); | |
consume(buffer.asReadOnlyBuffer()); | |
} | |
} | |
private static void consume(ByteBuffer buffer) { | |
System.out.println(state(buffer)); | |
while (buffer.hasRemaining()) System.out.print(buffer.getInt() + " "); | |
System.out.println(); | |
} | |
public static String state(ByteBuffer bb) { | |
return String.format("direct: %s, position: %,d, limit: %,d, capacity: %,d", | |
bb.isDirect(), bb.position(), bb.limit(), bb.capacity()); | |
} | |
} | |
// Result is as follows: | |
// direct: false, position: 0, limit: 12, capacity: 40 | |
// 0 1 2 | |
// direct: false, position: 12, limit: 24, capacity: 40 | |
// 3 4 5 | |
// direct: false, position: 24, limit: 36, capacity: 40 | |
// 6 7 8 | |
// direct: false, position: 36, limit: 40, capacity: 40 | |
// 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment