From ee27d8cdfd747b482dd7379c8b2d4c7179c25e11 Mon Sep 17 00:00:00 2001 From: networkException Date: Sun, 23 Oct 2022 04:02:56 +0200 Subject: [PATCH] LibWeb: Add is_code_unit_prefix() function --- Userland/Libraries/LibWeb/Infra/Strings.cpp | 36 +++++++++++++++++++++ Userland/Libraries/LibWeb/Infra/Strings.h | 2 ++ 2 files changed, 38 insertions(+) diff --git a/Userland/Libraries/LibWeb/Infra/Strings.cpp b/Userland/Libraries/LibWeb/Infra/Strings.cpp index 3b415bd6d3..b881b753e5 100644 --- a/Userland/Libraries/LibWeb/Infra/Strings.cpp +++ b/Userland/Libraries/LibWeb/Infra/Strings.cpp @@ -1,10 +1,12 @@ /* * Copyright (c) 2022, Linus Groh + * Copyright (c) 2022, networkException * * SPDX-License-Identifier: BSD-2-Clause */ #include +#include #include #include #include @@ -29,4 +31,38 @@ String strip_and_collapse_whitespace(StringView string) return builder.string_view().trim(Infra::ASCII_WHITESPACE); } +// https://infra.spec.whatwg.org/#code-unit-prefix +bool is_code_unit_prefix(StringView potential_prefix, StringView input) +{ + auto potential_prefix_utf16 = utf8_to_utf16(potential_prefix); + auto input_utf16 = utf8_to_utf16(input); + + // 1. Let i be 0. + size_t i = 0; + + // 2. While true: + while (true) { + // 1. If i is greater than or equal to potentialPrefix’s length, then return true. + if (i >= potential_prefix.length()) + return true; + + // 2. If i is greater than or equal to input’s length, then return false. + if (i >= input.length()) + return false; + + // 3. Let potentialPrefixCodeUnit be the ith code unit of potentialPrefix. + auto potential_prefix_code_unit = Utf16View(potential_prefix_utf16).code_unit_at(i); + + // 4. Let inputCodeUnit be the ith code unit of input. + auto input_code_unit = Utf16View(input_utf16).code_unit_at(i); + + // 5. Return false if potentialPrefixCodeUnit is not inputCodeUnit. + if (potential_prefix_code_unit != input_code_unit) + return false; + + // 6. Set i to i + 1. + ++i; + } +} + } diff --git a/Userland/Libraries/LibWeb/Infra/Strings.h b/Userland/Libraries/LibWeb/Infra/Strings.h index f73b435519..aef8cf4b5c 100644 --- a/Userland/Libraries/LibWeb/Infra/Strings.h +++ b/Userland/Libraries/LibWeb/Infra/Strings.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2022, Linus Groh + * Copyright (c) 2022, networkException * * SPDX-License-Identifier: BSD-2-Clause */ @@ -11,5 +12,6 @@ namespace Web::Infra { String strip_and_collapse_whitespace(StringView string); +bool is_code_unit_prefix(StringView potential_prefix, StringView input); }