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.
This commit is contained in:
Peter Brottveit Bock 2023-04-22 17:21:31 +02:00 committed by Andreas Kling
parent ab1244a160
commit 6f6d6c654d
Notes: sideshowbarker 2024-07-17 03:10:07 +09:00
2 changed files with 22 additions and 0 deletions

View File

@ -8,6 +8,7 @@
#include <AK/ByteBuffer.h>
#include <AK/Format.h>
#include <AK/Stream.h>
#include <AK/StringBuilder.h>
namespace AK {
@ -97,6 +98,16 @@ ErrorOr<void> Stream::write_until_depleted(ReadonlyBytes buffer)
return {};
}
ErrorOr<void> 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<size_t> SeekableStream::tell() const
{
// Seek with 0 and SEEK_CUR does not modify anything despite the const_cast,

View File

@ -8,6 +8,7 @@
#pragma once
#include <AK/Error.h>
#include <AK/Format.h>
#include <AK/Forward.h>
#include <AK/Traits.h>
@ -76,6 +77,16 @@ public:
return write_until_depleted({ &value, sizeof(value) });
}
virtual ErrorOr<void> format_impl(StringView, TypeErasedFormatParams&);
template<typename... Parameters>
ErrorOr<void> format(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
{
VariadicFormatParams<AllowDebugOnlyFormatters::No, Parameters...> 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