dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / external / lib_http / header_list.lucb
#==============================================================================================
#
# header_list - HTTP::HeaderList: a response's or request's list of headers
#
# DESCRIPTION:
# Port of Libraries/LibHTTP/HeaderList.cpp (lines 16-354) with the inline members of
# HeaderList.h (lines 25-91). Region r28 ported create, contains, get and append for the
# responses phase 1 makes; region p2b the rest. HeaderList is reference counted in C++;
# here it is managed memory its owner refers to.
#
# HeaderList.h's three callback templates (delete_all_matching, for_each_header_value,
# for_each_vary_header) take an ak.Function1 (DESIGN.md §2.7 case 2).
#
# Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
# Copyright (c) 2022, Kenneth Myhra <kennethmyhra@serenityos.org>
# Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
# Copyright (c) 2024, Andreas Kling <andreas@ladybird.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
## HTTP::HeaderList (Libraries/LibHTTP/HeaderList.h:21). Filled by region r28.
# https://fetch.spec.whatwg.org/#concept-header-list
pub struct HttpHeaderList:
pub var m_headers: ak.Vector[HttpHeader]
## `HTTP::Header { name, value }`: a header made from two views (ByteString's constructor from a
## StringView), as C++ writes it in braces, `header_list->append({ "Range"sv, move(range_value) })`.
pub func http_header_create(name: ak.StringView, value: ak.StringView) -> HttpHeader:
return HttpHeader(name = ak.byte_string_from_string_view(name), value = ak.byte_string_from_string_view(value))
# mark: Creation and the inline members =========================================================
## Ported from Libraries/LibHTTP/HeaderList.cpp:16 HTTP::HeaderList::create.
pub func http_header_list_create(headers: ak.Vector[HttpHeader] = ak.Vector[HttpHeader]()) -> HttpHeaderList*:
let this = new HttpHeaderList(m_headers = ak.Vector[HttpHeader]()) else trap("out of memory")
http_header_list_construct(this, headers)
return this
## Ported from Libraries/LibHTTP/HeaderList.cpp:21 HTTP::HeaderList::HeaderList (private).
func http_header_list_construct(this: HttpHeaderList*, headers: ak.Vector[HttpHeader]):
this.m_headers = headers
## Ported from Libraries/LibHTTP/HeaderList.h:25 HTTP::HeaderList::headers.
pub func http_header_list_headers(this: const HttpHeaderList*) -> const ak.Vector[HttpHeader]*:
return &this.m_headers
## Ported from Libraries/LibHTTP/HeaderList.h:27 HTTP::HeaderList::is_empty.
pub func http_header_list_is_empty(this: const HttpHeaderList*) -> bool:
return ak.vector_is_empty(&this.m_headers)
## Ported from Libraries/LibHTTP/HeaderList.h:29 HTTP::HeaderList::begin.
pub func http_header_list_begin(this: HttpHeaderList*) -> ak.SimpleIterator[ak.Vector[HttpHeader], HttpHeader]:
return ak.vector_begin(&this.m_headers)
## Ported from Libraries/LibHTTP/HeaderList.h:30 HTTP::HeaderList::begin (const).
pub func http_header_list_begin_const(this: const HttpHeaderList*) -> ak.SimpleIterator[ak.Vector[HttpHeader], HttpHeader]:
return ak.vector_begin_const(&this.m_headers)
## Ported from Libraries/LibHTTP/HeaderList.h:32 HTTP::HeaderList::end.
pub func http_header_list_end(this: HttpHeaderList*) -> ak.SimpleIterator[ak.Vector[HttpHeader], HttpHeader]:
return ak.vector_end(&this.m_headers)
## Ported from Libraries/LibHTTP/HeaderList.h:33 HTTP::HeaderList::end (const).
pub func http_header_list_end_const(this: const HttpHeaderList*) -> ak.SimpleIterator[ak.Vector[HttpHeader], HttpHeader]:
return ak.vector_end_const(&this.m_headers)
## Ported from Libraries/LibHTTP/HeaderList.h:35 HTTP::HeaderList::clear.
pub func http_header_list_clear(this: HttpHeaderList*):
ak.vector_clear(&this.m_headers)
# mark: Contains, get, append, delete, set, combine ============================================
## Ported from Libraries/LibHTTP/HeaderList.cpp:27 HTTP::HeaderList::contains.
# https://fetch.spec.whatwg.org/#header-list-contains
pub func http_header_list_contains(this: const HttpHeaderList*, name: ak.StringView) -> bool:
# A header list list contains a header name name if list contains a header whose name is a byte-case-insensitive
# match for name.
for header in &ak.vector_span_const(&this.m_headers):
if ak.byte_string_equals_ignoring_ascii_case(&header.name, name):
return true
return false
## Ported from Libraries/LibHTTP/HeaderList.cpp:37 HTTP::HeaderList::get.
# https://fetch.spec.whatwg.org/#concept-header-list-get
pub func http_header_list_get(this: const HttpHeaderList*, name: ak.StringView) -> ak.ByteString?:
# 1. If list does not contain name, then return null.
if not http_header_list_contains(this, name):
return none
# 2. Return the values of all headers in list whose name is a byte-case-insensitive match for name, separated from
# each other by 0x2C 0x20, in order.
var builder = ak.string_builder_new()
var first = true
for header in &ak.vector_span_const(&this.m_headers):
if not ak.byte_string_equals_ignoring_ascii_case(&header.name, name):
continue
if not first:
ak.string_builder_append(&builder, ", ")
ak.string_builder_append_string_view(&builder, ak.byte_string_view(&header.value))
first = false
return ak.string_builder_to_byte_string(&builder)
## Ported from Libraries/LibHTTP/HeaderList.cpp:63 HTTP::HeaderList::get_decode_and_split.
# https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
pub func http_header_list_get_decode_and_split(this: const HttpHeaderList*, name: ak.StringView) -> ak.Vector[ak.String]?:
# 1. Let value be the result of getting name from list.
let value = http_header_list_get(this, name)
# 2. If value is null, then return null.
let actual_value = value else return none
# 3. Return the result of getting, decoding, and splitting value.
return http_get_decode_and_split_header_value(ak.byte_string_view(&actual_value))
## Ported from Libraries/LibHTTP/HeaderList.cpp:77 HTTP::HeaderList::append.
# https://fetch.spec.whatwg.org/#concept-header-list-append
pub func http_header_list_append(this: HttpHeaderList*, header: HttpHeader):
var appended = header
# 1. If list contains name, then set name to the first such header’s name.
# NOTE: This reuses the casing of the name of the header already in list, if any. If there are multiple matched
# headers their names will all be identical.
for existing_header in &ak.vector_span(&this.m_headers):
if ak.byte_string_equals_ignoring_ascii_case(&existing_header.name, ak.byte_string_view(&appended.name)):
appended.name = existing_header.name
break
# 2. Append (name, value) to list.
ak.vector_append_t(&this.m_headers, appended)
## The lambda of HeaderList::delete_: whether a header's name is a byte-case-insensitive match for `name`.
func http_header_list_delete_name_matches(context: void*?, header: const HttpHeader*) -> bool:
let name = (const ak.StringView*)(context else trap("delete_: no name"))
return ak.byte_string_equals_ignoring_ascii_case(&header.name, *name)
## Ported from Libraries/LibHTTP/HeaderList.cpp:94 HTTP::HeaderList::delete_.
# https://fetch.spec.whatwg.org/#concept-header-list-delete
pub func http_header_list_delete(this: HttpHeaderList*, name: ak.StringView):
# To delete a header name name from a header list list, remove all headers whose name is a byte-case-insensitive
# match for name from list.
_ = ak.vector_remove_all_matching(&this.m_headers, ak.Function1[const HttpHeader*, bool](call = http_header_list_delete_name_matches, context = (void*)&name))
## Ported from Libraries/LibHTTP/HeaderList.cpp:104 HTTP::HeaderList::set.
# https://fetch.spec.whatwg.org/#concept-header-list-set
pub func http_header_list_set(this: HttpHeaderList*, header: HttpHeader):
# 1. If list contains name, then set the value of the first such header to value and remove the others.
var first_index: usize? = none
for (index, existing_header) in ak.vector_span(&this.m_headers).indexed():
if ak.byte_string_equals_ignoring_ascii_case(&existing_header.name, ak.byte_string_view(&header.name)):
first_index = index
break
if let index = first_index:
let it = ak.vector_at(&this.m_headers, index)
it.value = header.value
# m_headers.remove_all_matching: every later header whose name matches the first one's.
var i: usize = index + 1
while i < ak.vector_size(&this.m_headers):
if ak.byte_string_equals_ignoring_ascii_case(&ak.vector_at(&this.m_headers, i).name, ak.byte_string_view(&ak.vector_at(&this.m_headers, index).name)):
ak.vector_remove(&this.m_headers, i)
else:
i += 1
# 2. Otherwise, append header (name, value) to list.
else:
http_header_list_append(this, header)
## Ported from Libraries/LibHTTP/HeaderList.cpp:129 HTTP::HeaderList::combine.
# https://fetch.spec.whatwg.org/#concept-header-list-combine
pub func http_header_list_combine(this: HttpHeaderList*, header: HttpHeader):
# 1. If list contains name, then set the value of the first such header to its value, followed by 0x2C 0x20,
# followed by value.
var matching_header: HttpHeader*? = none
for existing_header in &ak.vector_span(&this.m_headers):
if ak.byte_string_equals_ignoring_ascii_case(&existing_header.name, ak.byte_string_view(&header.name)):
matching_header = existing_header
break
if let matching = matching_header:
var builder = ak.string_builder_new()
ak.string_builder_append_string_view(&builder, ak.byte_string_view(&matching.value))
ak.string_builder_append(&builder, ", ")
ak.string_builder_append_string_view(&builder, ak.byte_string_view(&header.value))
matching.value = ak.string_builder_to_byte_string(&builder)
# 2. Otherwise, append (name, value) to list.
else:
http_header_list_append(this, header)
# mark: Sort and combine, extracting values ====================================================
## Ported from Libraries/LibHTTP/HeaderList.cpp:147 HTTP::HeaderList::sort_and_combine.
# https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
pub func http_header_list_sort_and_combine(this: const HttpHeaderList*) -> ak.Vector[HttpHeader]:
# 1. Let headers be an empty list of headers with the key being the name and value the value.
var headers = ak.Vector[HttpHeader]()
# 2. Let names be the result of convert header names to a sorted-lowercase set with all the names of the headers
# in list.
var names_list = ak.Vector[ak.ByteString]()
ak.vector_ensure_capacity(&names_list, ak.vector_size(&this.m_headers))
for header in &ak.vector_span_const(&this.m_headers):
ak.vector_unchecked_append_u(&names_list, header.name)
var names = http_convert_header_names_to_a_sorted_lowercase_set(ak.vector_span_const(&names_list))
# 3. For each name of names:
for name in &ak.vector_span(&names):
# 1. If name is `set-cookie`, then:
if ak.byte_string_eq_string_view(name, ak.sv("set-cookie")):
# 1. Let values be a list of all values of headers in list whose name is a byte-case-insensitive match for
# name, in order.
# 2. For each value of values:
for header in &ak.vector_span_const(&this.m_headers):
if ak.byte_string_equals_ignoring_ascii_case(&header.name, ak.byte_string_view(name)):
# 1. Append (name, value) to headers.
ak.vector_append_t(&headers, HttpHeader(name = *name, value = header.value))
# 2. Otherwise:
else:
# 1. Let value be the result of getting name from list.
let value = http_header_list_get(this, ak.byte_string_view(name))
# 2. Assert: value is not null.
# 3. Append (name, value) to headers.
ak.vector_append_t(&headers, HttpHeader(name = *name, value = value else trap("VERIFY: value.has_value()")))
# 4. Return headers.
return headers
## Ported from Libraries/LibHTTP/HeaderList.cpp:194 HTTP::HeaderList::extract_header_list_values.
# https://fetch.spec.whatwg.org/#extract-header-list-values
pub func http_header_list_extract_header_list_values(this: const HttpHeaderList*, name: ak.StringView) -> EmptyOrVectorOrHttpHeaderListExtractHeaderParseFailure:
# 1. If list does not contain name, then return null.
if not http_header_list_contains(this, name):
return .empty
# FIXME: 2. If the ABNF for name allows a single header and list contains more than one, then return failure.
# NOTE: If different error handling is needed, extract the desired header first.
# 3. Let values be an empty list.
var values = ak.Vector[ak.ByteString]()
# 4. For each header header list contains whose name is name:
for header in &ak.vector_span_const(&this.m_headers):
if not ak.byte_string_equals_ignoring_ascii_case(&header.name, name):
continue
# 1. Let extract be the result of extracting header values from header.
var extract = http_header_extract_header_values(header) else return .http_header_list_extract_header_parse_failure(HttpHeaderListExtractHeaderParseFailure())
# 2. If extract is failure, then return failure.
# 3. Append each value in extract, in order, to values.
ak.vector_extend(&values, &extract)
# 5. Return values.
return .vector_byte_string(values)
## Ported from Libraries/LibHTTP/HeaderList.cpp:227 HTTP::HeaderList::extract_length.
# https://fetch.spec.whatwg.org/#header-list-extract-a-length
pub func http_header_list_extract_length(this: const HttpHeaderList*) -> EmptyOrU64OrHttpHeaderListExtractLengthFailure:
# 1. Let values be the result of getting, decoding, and splitting `Content-Length` from headers.
let values = http_header_list_get_decode_and_split(this, ak.sv("Content-Length"))
# 2. If values is null, then return null.
var actual_values = values else return .empty
# 3. Let candidateValue be null.
var candidate_value: ak.String? = none
# 4. For each value of values:
for value in &ak.vector_span(&actual_values):
# 1. If candidateValue is null, then set candidateValue to value.
if let candidate = candidate_value:
# 2. Otherwise, if value is not candidateValue, return failure.
if not ak.string_equals(&candidate, value):
return .http_header_list_extract_length_failure(HttpHeaderListExtractLengthFailure())
else:
candidate_value = *value
# 5. If candidateValue is the empty string or has a code point that is not an ASCII digit, then return null.
# 6. Return candidateValue, interpreted as decimal number.
# FIXME: This will return an empty Optional if it cannot fit into a u64, is this correct?
let candidate = candidate_value else trap("VERIFY: candidate_value.has_value()")
let result = ak.string_to_number_u64(&candidate, ak.TrimWhitespace.no) else return .empty
return .u64_(result)
## Ported from Libraries/LibHTTP/HeaderList.cpp:262 HTTP::parse_single_byte_content_range_as_values (internal linkage).
# https://wicg.github.io/background-fetch/#single-byte-content-range
func http_parse_single_byte_content_range_as_values(string: const ak.ByteString*) -> HttpHeaderListContentRangeValues?:
var result = HttpHeaderListContentRangeValues(first_byte_pos = 0, last_byte_pos = 0, complete_length = none)
var lexer = ak.generic_lexer_new(ak.byte_string_view(string))
# "bytes=" first-byte-pos "-" last-byte-pos "/" complete-length
# AD-HOC: The spec wants an '=', but the RFC mentioned in the spec requires a space.
# https://github.com/WICG/background-fetch/issues/154
if not ak.generic_lexer_consume_specific_string_view(&lexer, ak.sv("bytes ")):
return none
# first-byte-pos = 1*DIGIT
result.first_byte_pos = ak.generic_lexer_consume_decimal_integer_u64(&lexer) else return none
if not ak.generic_lexer_consume_specific_t_char_type(&lexer, '-'):
return none
# last-byte-pos = 1*DIGIT
result.last_byte_pos = ak.generic_lexer_consume_decimal_integer_u64(&lexer) else return none
if not ak.generic_lexer_consume_specific_t_char_type(&lexer, '/'):
return none
# complete-length = ( 1*DIGIT / "*" )
if ak.generic_lexer_consume_specific_t_char_type(&lexer, '*'):
result.complete_length = none
else:
result.complete_length = ak.generic_lexer_consume_decimal_integer_u64(&lexer) else return none
if not ak.generic_lexer_is_eof(&lexer):
return none
return result
## Ported from Libraries/LibHTTP/HeaderList.cpp:309 HTTP::HeaderList::extract_content_range_values.
# https://wicg.github.io/background-fetch/#extract-content-range-values
pub func http_header_list_extract_content_range_values(this: const HttpHeaderList*) -> HttpHeaderListContentRangeValuesOrHttpHeaderListExtractContentRangeFailure:
# 1. If response’s header list does not contain `Content-Range`, then return failure.
# 2. Let contentRangeValue be the value of the first header whose name is a byte-case-insensitive match for
# `Content-Range` in response’s header list.
let content_range_value = http_header_list_get(this, ak.sv("Content-Range")) else return .http_header_list_extract_content_range_failure(HttpHeaderListExtractContentRangeFailure())
# 3. If parsing contentRangeValue per single byte content-range fails, then return failure.
# 4. Let firstBytePos be the portion of contentRangeValue named first-byte-pos when parsed as single byte content-range,
# parsed as an integer.
# 5. Let lastBytePos be the portion of contentRangeValue named last-byte-pos when parsed as single byte content-range,
# parsed as an integer.
# 6. Let completeLength be the portion of contentRangeValue named complete-length when parsed as single byte
# content-range.
# 7. If completeLength is "*", then set completeLength to null, otherwise set completeLength to completeLength parsed as
# an integer.
# NB: The variables above are converted to integers as part of the single byte content-range parsing algorithm.
let result = http_parse_single_byte_content_range_as_values(&content_range_value) else return .http_header_list_extract_content_range_failure(HttpHeaderListExtractContentRangeFailure())
# 8. Return firstBytePos, lastBytePos, and completeLength.
return .http_header_list_content_range_values(result)
## Ported from Libraries/LibHTTP/HeaderList.cpp:338 HTTP::HeaderList::unique_names.
# Non-standard
pub func http_header_list_unique_names(this: const HttpHeaderList*) -> ak.Vector[ak.ByteString]:
var header_names_seen: ak.HashTable[ak.StringView, ak.CaseInsensitiveAsciiStringViewTraits]
var header_names = ak.Vector[ak.ByteString]()
for header in &ak.vector_span_const(&this.m_headers):
if ak.hash_table_contains_t(&header_names_seen, ak.byte_string_view(&header.name)):
continue
_ = ak.hash_table_set(&header_names_seen, ak.byte_string_view(&header.name))
ak.vector_append_t(&header_names, header.name)
return header_names
# mark: The callback templates of HeaderList.h =================================================
## Ported from Libraries/LibHTTP/HeaderList.h:63 HTTP::HeaderList::delete_all_matching.
pub func http_header_list_delete_all_matching(this: HttpHeaderList*, callback: ak.Function1[const HttpHeader*, bool]):
_ = ak.vector_remove_all_matching(&this.m_headers, callback)
## Ported from Libraries/LibHTTP/HeaderList.h:69 HTTP::HeaderList::for_each_header_value.
pub func http_header_list_for_each_header_value(this: const HttpHeaderList*, name: ak.StringView, callback: ak.Function1[ak.StringView, ak.IterationDecision]):
for header in &ak.vector_span_const(&this.m_headers):
if not ak.byte_string_equals_ignoring_ascii_case(&header.name, name):
continue
if ak.function1_call(&callback, ak.byte_string_view(&header.value)) == ak.IterationDecision.break_:
break
## The captures of for_each_vary_header's inner lambda, `[&](StringView header) -> IterationDecision`: the
## caller's callback and the outer lambda's `result`.
struct HttpHeaderListForEachVaryHeaderSplit: ak.StringViewCallback:
var callback: const ak.Function1[ak.StringView, ak.IterationDecision]*
var result: ak.IterationDecision
func call(header: ak.StringView) -> ak.IterationDecision!:
self.result = ak.function1_call(self.callback, http_normalize_header_value(header))
return self.result
## The outer lambda of for_each_vary_header, `[&](StringView value) -> IterationDecision`, over each
## `Vary` value; its context is the caller's callback.
func http_header_list_for_each_vary_header_value(context: void*?, value: ak.StringView) -> ak.IterationDecision:
let callback = (const ak.Function1[ak.StringView, ak.IterationDecision]*)(context else trap("for_each_vary_header: no callback"))
# C++ leaves `result` uninitialized when the value has no part; it is Continue here.
var split = HttpHeaderListForEachVaryHeaderSplit(callback = callback, result = ak.IterationDecision.continue_)
ak.string_view_for_each_split_view_string_view(&value, ak.sv(","), ak.SplitBehavior.nothing, &split) else trap("for_each_split_view: the callback does not fail")
return split.result
## Ported from Libraries/LibHTTP/HeaderList.h:80 HTTP::HeaderList::for_each_vary_header.
pub func http_header_list_for_each_vary_header(this: const HttpHeaderList*, callback: ak.Function1[ak.StringView, ak.IterationDecision]):
http_header_list_for_each_header_value(this, ak.sv("Vary"), ak.Function1[ak.StringView, ak.IterationDecision](call = http_header_list_for_each_vary_header_value, context = (void*)&callback))