From d9d556fbabd58cac630cd2e28c77f499460fb724 Mon Sep 17 00:00:00 2001 From: Luke Wilde Date: Fri, 10 Feb 2023 19:12:10 +0000 Subject: [PATCH] AK: Allow Vector::contains_slow to accept (Readonly)Bytes This is done by providing Traits::equals functions for (Readonly)Bytes, as the base GenericTraits::equals is unable to convert the ByteBuffer to (Readonly)Bytes to then use Span::operator== This allows us to check if a Vector contains a (Readonly)Bytes without having to making a copy of it into a ByteBuffer first. The initial use of this is in LibWeb with CORS-preflight, where we check the split contents of the Access-Control headers with Fetch::Infrastructure::Request::method() and static StringViews such as "*"sv.bytes(). --- AK/ByteBuffer.h | 8 ++++++++ Tests/AK/TestByteBuffer.cpp | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/AK/ByteBuffer.h b/AK/ByteBuffer.h index 7f24872cad..61ebf051a6 100644 --- a/AK/ByteBuffer.h +++ b/AK/ByteBuffer.h @@ -332,6 +332,14 @@ struct Traits : public GenericTraits { { return Traits::hash(byte_buffer.span()); } + static bool equals(ByteBuffer const& byte_buffer, Bytes const& other) + { + return byte_buffer.bytes() == other; + } + static bool equals(ByteBuffer const& byte_buffer, ReadonlyBytes const& other) + { + return byte_buffer.bytes() == other; + } }; } diff --git a/Tests/AK/TestByteBuffer.cpp b/Tests/AK/TestByteBuffer.cpp index 29ed85d32f..7122b3264a 100644 --- a/Tests/AK/TestByteBuffer.cpp +++ b/Tests/AK/TestByteBuffer.cpp @@ -7,6 +7,7 @@ #include #include +#include TEST_CASE(equality_operator) { @@ -33,6 +34,18 @@ TEST_CASE(equality_operator) EXPECT_EQ(d == d, true); } +TEST_CASE(byte_buffer_vector_contains_slow_bytes) +{ + Vector vector; + ByteBuffer a = ByteBuffer::copy("Hello, friend", 13).release_value(); + vector.append(a); + + ReadonlyBytes b = "Hello, friend"sv.bytes(); + Bytes c = a.bytes(); + EXPECT_EQ(vector.contains_slow(b), true); + EXPECT_EQ(vector.contains_slow(c), true); +} + BENCHMARK_CASE(append) { ByteBuffer bb;