AK: Add ByteBuffer::{must_,}get_bytes_for_writing()

This is useful for writing new data at the end of a ByteBuffer. For
instance, with the Stream API:

    auto pending_bytes = TRY(stream.pending_bytes());
    auto receive_buffer = TRY(buffer.get_bytes_for_writing(
        pending_bytes));
    TRY(stream.read(receive_buffer));
This commit is contained in:
sin-ack 2021-12-18 11:29:51 +00:00 committed by Ali Mohammad Pur
parent 9569841589
commit 28063de488

View file

@ -182,6 +182,20 @@ public:
return try_ensure_capacity_slowpath(new_capacity);
}
/// Return a span of bytes past the end of this ByteBuffer for writing.
/// Ensures that the required space is available.
ErrorOr<Bytes> get_bytes_for_writing(size_t length)
{
TRY(try_ensure_capacity(size() + length));
return Bytes { data() + size(), length };
}
/// Like get_bytes_for_writing, but crashes if allocation fails.
Bytes must_get_bytes_for_writing(size_t length)
{
return MUST(get_bytes_for_writing(length));
}
void append(char byte)
{
MUST(try_append(byte));