module Protocol::HTTP::Body::Stream::Reader

def read_until(pattern, offset = 0, chomp: false)

@returns [String] The contents of the stream up until the pattern, which is consumed but not returned.
@parameter chomp [Boolean] Whether to remove the pattern from the returned data.
@parameter offset [Integer] The offset to start searching from.
@parameter pattern [String] The pattern to match.

Read data from the stream until encountering pattern.
def read_until(pattern, offset = 0, chomp: false)
	# We don't want to split on the pattern, so we subtract the size of the pattern.
	split_offset = pattern.bytesize - 1
	
	@buffer ||= read_next
	return nil if @buffer.nil?
	
	until index = @buffer.index(pattern, offset)
		offset = @buffer.bytesize - split_offset
		
		offset = 0 if offset < 0
		
		if chunk = read_next
			@buffer << chunk
		else
			return nil
		end
	end
	
	@buffer.freeze
	matched = @buffer.byteslice(0, index+(chomp ? 0 : pattern.bytesize))
	@buffer = @buffer.byteslice(index+pattern.bytesize, @buffer.bytesize)
	
	return matched
end