AK: Allow Vector<ByteBuffer>::contains_slow to accept (Readonly)Bytes

This is done by providing Traits<ByteBuffer>::equals functions for
(Readonly)Bytes, as the base GenericTraits<T>::equals is unable to
convert the ByteBuffer to (Readonly)Bytes to then use Span::operator==

This allows us to check if a Vector<ByteBuffer> 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().
This commit is contained in:
Luke Wilde 2023-02-10 19:12:10 +00:00 committed by Linus Groh
parent 237df9df5c
commit d9d556fbab
2 changed files with 21 additions and 0 deletions

View file

@ -332,6 +332,14 @@ struct Traits<ByteBuffer> : public GenericTraits<ByteBuffer> {
{
return Traits<ReadonlyBytes>::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;
}
};
}

View file

@ -7,6 +7,7 @@
#include <LibTest/TestCase.h>
#include <AK/ByteBuffer.h>
#include <AK/Vector.h>
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<ByteBuffer> 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;