class Async::HTTP::Headers

def self.[] hash

def self.[] hash
	self.new(hash.to_a)
end

def == other

def == other
	if other.is_a? Hash
		to_h == other
	else
		@fields == other.fields
	end
end

def [] key

def [] key
	@indexed ||= to_h
	
	@indexed[key]
end

def []= key, value

def []= key, value
	@fields << [key, value]
	
	if @indexed
		# It would be good to do some kind of validation here.
		merge(@indexed, key.downcase, value)
	end
end

def add(key, value)

def add(key, value)
	self[key] = value
end

def delete(key)

Delete all headers with the given key, and return the value of the last one, if any.
def delete(key)
	values, @fields = @fields.partition do |field|
		field.first.downcase == key
	end
	
	if @indexed
		@indexed.delete(key)
	end
	
	if field = values.last
		return field.last
	end
end

def each(&block)

def each(&block)
	@fields.each(&block)
end

def empty?

def empty?
	@fields.empty?
end

def freeze

def freeze
	return if frozen?
	
	@indexed = to_h
	
	super
end

def include? key

def include? key
	self[key] != nil
end

def initialize(fields = [])

def initialize(fields = [])
	@fields = fields
	@indexed = to_h
end

def merge(hash, key, value)

def merge(hash, key, value)
	if policy = MERGE_POLICY[key]
		if current_value = hash[key]
			current_value << value
		else
			hash[key] = policy.new(value)
		end
	else
		raise ArgumentError, "Header #{key} can only be set once!" if hash.include?(key)
		
		# We can't merge these, we only expose the last one set.
		hash[key] = value
	end
end

def slice!(keys)

def slice!(keys)
	values, @fields = @fields.partition do |field|
		keys.include?(field.first.downcase)
	end
	
	if @indexed
		keys.each do |key|
			@indexed.delete(key)
		end
	end
end

def to_h

def to_h
	@fields.inject({}) do |hash, (key, value)|
		merge(hash, key.downcase, value)
		
		hash
	end
end