From 4f981adb97b24fd5a8d2b39341e3897654d661c7 Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Thu, 13 Mar 2025 08:55:10 +0100 Subject: [PATCH] lib/fmt/Unsafe: new library --- src/lib/fmt/Unsafe.hxx | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/lib/fmt/Unsafe.hxx diff --git a/src/lib/fmt/Unsafe.hxx b/src/lib/fmt/Unsafe.hxx new file mode 100644 index 000000000..373b39e7b --- /dev/null +++ b/src/lib/fmt/Unsafe.hxx @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +#include + +/** + * Format without bounds checking and return a C string. + */ +[[nodiscard]] +inline const char * +VFmtUnsafeC(char *dest, fmt::string_view format_str, fmt::format_args args) noexcept +{ + *fmt::vformat_to(dest, format_str, args) = '\0'; + return dest; +} + +template +[[nodiscard]] +constexpr const char * +FmtUnsafeC(char *dest, const S &format_str, Args&&... args) noexcept +{ + return VFmtUnsafeC(dest, format_str, fmt::make_format_args(args...)); +} + +/** + * Format without bounds checking and return a std::string_view. + */ +[[nodiscard]] +inline std::string_view +VFmtUnsafeSV(char *dest, fmt::string_view format_str, fmt::format_args args) noexcept +{ + return {dest, fmt::vformat_to(dest, format_str, args)}; +} + +template +[[nodiscard]] +std::string_view +FmtUnsafeSV(char *dest, const S &format_str, Args&&... args) noexcept +{ + return VFmtUnsafeSV(dest, format_str, fmt::make_format_args(args...)); +}