[ds_core] simplify MessageBuilder construction (#713)

* [ds_core] simplify MessageBuilder construction

* remove special handling of zero case

* select latest xcode
This commit is contained in:
Schrodinger ZHU Yifan
2024-12-18 10:18:04 -05:00
committed by GitHub
parent 6952683692
commit 141cdd9361
2 changed files with 33 additions and 53 deletions

View File

@@ -1,11 +1,10 @@
#pragma once
#include "bits.h"
#include "snmalloc/ds_core/defines.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <tuple>
#include <type_traits>
namespace snmalloc
@@ -156,26 +155,6 @@ namespace snmalloc
*/
size_t insert = 0;
/**
* Add argument `i` from the tuple `args` to the output. This is
* implemented recursively because the different tuple elements can have
* different types and so the code for dispatching will depend on the type
* at the index. The compiler will lower this to a jump table in optimised
* builds.
*/
template<size_t I, typename... Args>
void add_tuple_arg(size_t i, const std::tuple<Args...>& args)
{
if (i == I)
{
append(std::get<I>(args));
}
else if constexpr (I != 0)
{
add_tuple_arg<I - 1>(i, args);
}
}
/**
* Append a single character into the buffer. This is the single primitive
* operation permitted on the buffer and performs bounds checks to ensure
@@ -361,43 +340,41 @@ namespace snmalloc
append(static_cast<unsigned long long>(x));
}
/**
* Append with format string and arguments. Compiler
* is able to optimize the recursion into loops.
*/
template<typename Head, typename... Tail>
SNMALLOC_FAST_PATH_INLINE void
append(const char* fmt, Head&& head, Tail&&... tail)
{
for (;;)
{
if (fmt[0] == '\0')
{
error("Internal error: format string missing `{}`!");
}
if (fmt[0] == '{' && fmt[1] == '}')
{
append(std::forward<Head>(head));
return append(fmt + 2, std::forward<Tail>(tail)...);
}
append_char(*fmt);
fmt++;
}
}
public:
/**
* Constructor. Takes a format string and the arguments to output.
*/
template<typename... Args>
SNMALLOC_FAST_PATH MessageBuilder(const char* fmt, Args... args)
SNMALLOC_FAST_PATH MessageBuilder(const char* fmt, Args&&... args)
{
buffer[SafeLength] = 0;
size_t arg = 0;
auto args_tuple = std::forward_as_tuple(args...);
for (const char* s = fmt; *s != 0; ++s)
{
if (s[0] == '{' && s[1] == '}')
{
add_tuple_arg<sizeof...(Args) - 1>(arg++, args_tuple);
++s;
}
else
{
append_char(*s);
}
}
append_char('\0');
}
/**
* Constructor for trivial format strings (no arguments). This exists to
* allow `MessageBuilder` to be used with macros without special casing
* the single-argument version.
*/
SNMALLOC_FAST_PATH MessageBuilder(const char* fmt)
{
buffer[SafeLength] = 0;
for (const char* s = fmt; *s != 0; ++s)
{
append_char(*s);
}
append(fmt, std::forward<Args>(args)...);
append_char('\0');
}