ByteBufferUtil { public static int sliceIfRequired(final ByteBuffer data, final int maxSliceSize, final Slice<ByteBuffer> slice) { final int capacity = data.capacity(); if (capacity == data.remaining() && capacity <= maxSliceSize) { slice.each(data, true); return 1; } ByteBuffer d = data; int remaining = 0; int sliceCount = 0; while ((remaining = d.remaining()) > 0) { sliceCount++; final byte[] bytes = new byte[maxSliceSize < remaining ? maxSliceSize : remaining]; final boolean goOn = slice.each(ByteBuffer.wrap(bytes), d.get(bytes).remaining() == 0); if (!goOn) { break; } d = d.slice(); } return sliceCount; } private  ByteBufferUtil(); static int slice(final ByteBuffer data, final int maxSliceSize,
            final Slice<ByteBuffer> slice); static int sliceIfRequired(final ByteBuffer data,
            final int maxSliceSize, final Slice<ByteBuffer> slice); static ByteBuffer merge(final ByteBuffer... dataArray);  }
@Test public void testSliceIfRequired() throws Exception { { final String s = "1234567890abc"; final ByteBuffer inputData = ByteBuffer .wrap(s.getBytes(StandardCharsets.UTF_8)); assertEquals(13, inputData.capacity()); final int totalSlices = ByteBufferUtil.sliceIfRequired(inputData, s.length(), (part, last) -> { assertTrue(inputData == part); assertEquals(inputData, part); assertTrue(last); return !last; }); assertEquals(1, totalSlices); } { final String s = "1234567890abc"; final ByteBuffer inputData = ByteBuffer .wrap(s.getBytes(StandardCharsets.UTF_8)); assertEquals(13, inputData.capacity()); final int totalSlices = ByteBufferUtil.sliceIfRequired(inputData, s.length() + 1, (part, last) -> { assertTrue(inputData == part); assertEquals(inputData, part); assertTrue(last); return !last; }); assertEquals(1, totalSlices); } { final String s = "1234567890abc"; final ByteBuffer inputData = ByteBuffer .wrap(s.getBytes(StandardCharsets.UTF_8)); assertEquals(13, inputData.capacity()); final int totalSlices = ByteBufferUtil.sliceIfRequired(inputData, s.length() + 10, (part, last) -> { assertTrue(inputData == part); assertEquals(inputData, part); assertTrue(last); return !last; }); assertEquals(1, totalSlices); } { final String s = "1234567890abc"; final ByteBuffer inputData = ByteBuffer .wrap(s.getBytes(StandardCharsets.UTF_8)); assertEquals(13, inputData.capacity()); final int totalSlices = ByteBufferUtil.sliceIfRequired(inputData, s.length() - 1, (part, last) -> { assertFalse(inputData == part); return !last; }); assertEquals(2, totalSlices); } }