class BufferReaderWriterUtil {

	@Nullable
	static Buffer sliceNextBuffer(ByteBuffer memory) {
		final int remaining = memory.remaining();

		// we only check the correct case where data is exhausted
		// all other cases can only occur if our write logic is wrong and will already throw
		// buffer underflow exceptions which will cause the read to fail.
		if (remaining == 0) {
			return null;
		}

		final int header = memory.getInt();
		final int size = memory.getInt();

		memory.limit(memory.position() + size);
		ByteBuffer buf = memory.slice();
		memory.position(memory.limit());
		memory.limit(memory.capacity());

		MemorySegment memorySegment = MemorySegmentFactory.wrapOffHeapMemory(buf);

		return bufferFromMemorySegment(
				memorySegment,
				FreeingBufferRecycler.INSTANCE,
				size,
				header == HEADER_VALUE_IS_EVENT);
	}

}