From 356e58332cbee3629a31109efa075af85d1a350c Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Sat, 7 Jan 2023 14:29:07 -0500 Subject: [PATCH] LibJS: Add and begin using a completion-compatible string formatter The `deprecated_format` helper is a thin wrapper to map results from AK::vformat to a throw completion. This will let us try to throw on OOM conditions rather than just blowing up. Note it's called `deprecated_format` as we will likely end up adding a method named just `format` to return `ThrowCompletionOr`, when we begin the migration from DeprecatedString->String for LibJS. --- .../LibJS/Runtime/StringPrototype.cpp | 5 ++-- .../Libraries/LibJS/Runtime/ThrowableFormat.h | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 Userland/Libraries/LibJS/Runtime/ThrowableFormat.h diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp index be8d5b8f6d..30d3d4a40e 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -536,8 +537,8 @@ static ThrowCompletionOr pad_string(VM& vm, Utf16String string, PadPlacem auto filler = filler_builder.build(); auto formatted = placement == PadPlacement::Start - ? DeprecatedString::formatted("{}{}", filler, string.view()) - : DeprecatedString::formatted("{}{}", string.view(), filler); + ? TRY(deprecated_format(vm, "{}{}", filler, string.view())) + : TRY(deprecated_format(vm, "{}{}", string.view(), filler)); return PrimitiveString::create(vm, move(formatted)); } diff --git a/Userland/Libraries/LibJS/Runtime/ThrowableFormat.h b/Userland/Libraries/LibJS/Runtime/ThrowableFormat.h new file mode 100644 index 0000000000..ec4d21f6de --- /dev/null +++ b/Userland/Libraries/LibJS/Runtime/ThrowableFormat.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023, Tim Flynn + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace JS { + +template +ThrowCompletionOr deprecated_format(VM& vm, CheckedFormatString&& fmtstr, Args const&... args) +{ + StringBuilder builder; + AK::VariadicFormatParams parameters { args... }; + + TRY_OR_THROW_OOM(vm, vformat(builder, fmtstr.view(), parameters)); + return builder.to_deprecated_string(); +} + +}