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 boolean isEvent = memory.getShort() == HEADER_VALUE_IS_EVENT;
		final boolean isCompressed = memory.getShort() == BUFFER_IS_COMPRESSED;
		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);

		Buffer.DataType dataType = isEvent ? Buffer.DataType.EVENT_BUFFER : Buffer.DataType.DATA_BUFFER;
		return new NetworkBuffer(memorySegment, FreeingBufferRecycler.INSTANCE, dataType, isCompressed, size);
	}

}