From 6f6d6c654d13c5a1dec6122592e6874bc1a833f5 Mon Sep 17 00:00:00 2001 From: Peter Brottveit Bock Date: Sat, 22 Apr 2023 17:21:31 +0200 Subject: [PATCH] AK: Implement Stream::format(fmtstr, args...) Based on `out()` and `vout()` from AK/Format.h. As opposed to those, this propagates errors. As `Core::File` extends `AK::Stream`, this allows formatted printing directly on `Core::File`s. --- AK/Stream.cpp | 11 +++++++++++ AK/Stream.h | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/AK/Stream.cpp b/AK/Stream.cpp index 76217ea5fb..8ea84d84a7 100644 --- a/AK/Stream.cpp +++ b/AK/Stream.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace AK { @@ -97,6 +98,16 @@ ErrorOr Stream::write_until_depleted(ReadonlyBytes buffer) return {}; } +ErrorOr Stream::format_impl(StringView fmtstr, TypeErasedFormatParams& parameters) +{ + StringBuilder builder; + TRY(vformat(builder, fmtstr, parameters)); + + auto const string = builder.string_view(); + TRY(write_until_depleted(string.bytes())); + return {}; +} + ErrorOr SeekableStream::tell() const { // Seek with 0 and SEEK_CUR does not modify anything despite the const_cast, diff --git a/AK/Stream.h b/AK/Stream.h index 559ce31194..b821a10ea6 100644 --- a/AK/Stream.h +++ b/AK/Stream.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include @@ -76,6 +77,16 @@ public: return write_until_depleted({ &value, sizeof(value) }); } + virtual ErrorOr format_impl(StringView, TypeErasedFormatParams&); + + template + ErrorOr format(CheckedFormatString&& fmtstr, Parameters const&... parameters) + { + VariadicFormatParams variadic_format_params { parameters... }; + TRY(format_impl(fmtstr.view(), variadic_format_params)); + return {}; + } + /// Returns whether the stream has reached the end of file. For sockets, /// this most likely means that the protocol has disconnected (in the case /// of TCP). For seekable streams, this means the end of the file. Note that