client/Response: add method Fmt() based on libfmt

This commit is contained in:
Max Kellermann
2021-05-21 20:35:29 +02:00
parent a9c704b76e
commit 0440c41cba
27 changed files with 241 additions and 195 deletions

View File

@@ -22,6 +22,8 @@
#include "Response.hxx"
#include "Idle.hxx"
#include <fmt/format.h>
#include <cassert>
static void
@@ -30,7 +32,7 @@ WriteIdleResponse(Response &r, unsigned flags) noexcept
const char *const*idle_names = idle_get_names();
for (unsigned i = 0; idle_names[i]; ++i) {
if (flags & (1 << i))
r.Format("changed: %s\n", idle_names[i]);
r.Fmt(FMT_STRING("changed: {}\n"), idle_names[i]);
}
r.Write("OK\n");

View File

@@ -22,6 +22,8 @@
#include "util/FormatString.hxx"
#include "util/AllocatedString.hxx"
#include <fmt/format.h>
TagMask
Response::GetTagMask() const noexcept
{
@@ -56,17 +58,21 @@ Response::Format(const char *fmt, ...) noexcept
return success;
}
bool
Response::VFmt(fmt::string_view format_str, fmt::format_args args) noexcept
{
fmt::memory_buffer buffer;
fmt::vformat_to(buffer, format_str, args);
return Write(buffer.data(), buffer.size());
}
bool
Response::WriteBinary(ConstBuffer<void> payload) noexcept
{
assert(payload.size <= client.binary_limit);
return
#ifdef _WIN32
Format("binary: %lu\n", (unsigned long)payload.size) &&
#else
Format("binary: %zu\n", payload.size) &&
#endif
Fmt("binary: {}\n", payload.size) &&
Write(payload.data, payload.size) &&
Write("\n");
}

View File

@@ -23,6 +23,11 @@
#include "protocol/Ack.hxx"
#include "util/Compiler.h"
#include <fmt/core.h>
#if FMT_VERSION < 70000
#include <fmt/format.h>
#endif
#include <cstdarg>
#include <cstddef>
@@ -79,6 +84,21 @@ public:
gcc_printf(2,3)
bool Format(const char *fmt, ...) noexcept;
bool VFmt(fmt::string_view format_str, fmt::format_args args) noexcept;
template<typename S, typename... Args>
bool Fmt(const S &format_str, Args&&... args) noexcept {
#if FMT_VERSION >= 70000
return VFmt(fmt::to_string_view(format_str),
fmt::make_args_checked<Args...>(format_str,
args...));
#else
/* expensive fallback for older libfmt versions */
const auto result = fmt::format(format_str, args...);
return Write(result.data(), result.size());
#endif
}
/**
* Write a binary chunk; this writes the "binary" line, the
* given chunk and the trailing newline.