mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-09-11 13:36:13 +03:00
AK: Add an option to zero-fill ByteBuffer data upon growth
This is to avoid UB in cases where we need to be able to read from the buffer immediately after resizing it.
This commit is contained in:
parent
759c8ccc55
commit
507a5d8a07
Notes:
sideshowbarker
2024-07-17 01:27:18 +09:00
Author: https://github.com/trflynn89 Commit: https://github.com/SerenityOS/serenity/commit/507a5d8a07 Pull-request: https://github.com/SerenityOS/serenity/pull/22455 Reviewed-by: https://github.com/nico ✅
@ -163,9 +163,14 @@ public:
|
||||
m_size = 0;
|
||||
}
|
||||
|
||||
ALWAYS_INLINE void resize(size_t new_size)
|
||||
enum class ZeroFillNewElements {
|
||||
No,
|
||||
Yes,
|
||||
};
|
||||
|
||||
ALWAYS_INLINE void resize(size_t new_size, ZeroFillNewElements zero_fill_new_elements = ZeroFillNewElements::No)
|
||||
{
|
||||
MUST(try_resize(new_size));
|
||||
MUST(try_resize(new_size, zero_fill_new_elements));
|
||||
}
|
||||
|
||||
void trim(size_t size, bool may_discard_existing_data)
|
||||
@ -181,13 +186,18 @@ public:
|
||||
MUST(try_ensure_capacity(new_capacity));
|
||||
}
|
||||
|
||||
ErrorOr<void> try_resize(size_t new_size)
|
||||
ErrorOr<void> try_resize(size_t new_size, ZeroFillNewElements zero_fill_new_elements = ZeroFillNewElements::No)
|
||||
{
|
||||
if (new_size <= m_size) {
|
||||
trim(new_size, false);
|
||||
return {};
|
||||
}
|
||||
TRY(try_ensure_capacity(new_size));
|
||||
|
||||
if (zero_fill_new_elements == ZeroFillNewElements::Yes) {
|
||||
__builtin_memset(data() + m_size, 0, new_size - m_size);
|
||||
}
|
||||
|
||||
m_size = new_size;
|
||||
return {};
|
||||
}
|
||||
|
@ -46,6 +46,23 @@ TEST_CASE(byte_buffer_vector_contains_slow_bytes)
|
||||
EXPECT_EQ(vector.contains_slow(c), true);
|
||||
}
|
||||
|
||||
TEST_CASE(zero_fill_new_elements_on_growth)
|
||||
{
|
||||
auto buffer = MUST(ByteBuffer::create_uninitialized(5));
|
||||
|
||||
buffer.span().fill(1);
|
||||
EXPECT_EQ(buffer.span(), (Array<u8, 5> { 1, 1, 1, 1, 1 }));
|
||||
|
||||
buffer.resize(8, ByteBuffer::ZeroFillNewElements::Yes);
|
||||
EXPECT_EQ(buffer.span(), (Array<u8, 8> { 1, 1, 1, 1, 1, 0, 0, 0 }));
|
||||
|
||||
buffer.span().fill(2);
|
||||
EXPECT_EQ(buffer.span(), (Array<u8, 8> { 2, 2, 2, 2, 2, 2, 2, 2 }));
|
||||
|
||||
buffer.resize(10, ByteBuffer::ZeroFillNewElements::Yes);
|
||||
EXPECT_EQ(buffer.span(), (Array<u8, 10> { 2, 2, 2, 2, 2, 2, 2, 2, 0, 0 }));
|
||||
}
|
||||
|
||||
BENCHMARK_CASE(append)
|
||||
{
|
||||
ByteBuffer bb;
|
||||
|
Loading…
Reference in New Issue
Block a user