From 28063de488a8aa83de19cfb15b873ad943356838 Mon Sep 17 00:00:00 2001 From: sin-ack Date: Sat, 18 Dec 2021 11:29:51 +0000 Subject: [PATCH] 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)); --- AK/ByteBuffer.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/AK/ByteBuffer.h b/AK/ByteBuffer.h index 106f650841..abf4c9d53b 100644 --- a/AK/ByteBuffer.h +++ b/AK/ByteBuffer.h @@ -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 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));