55 lines
1.9 KiB
C++
55 lines
1.9 KiB
C++
//---------------------------------------------------------------------------//
|
|
// 1100101 |_ mov #0, r4 __ //
|
|
// 11 |_ <0xb380 %5c4> / _|_ _____ ___ //
|
|
// 0110 |_ 3.50 -> 3.60 | _\ \ / _ (_-< //
|
|
// |_ base# + offset |_| /_\_\___/__/ //
|
|
//---------------------------------------------------------------------------//
|
|
// fxos/util/format: printf()-style format for std::string
|
|
//
|
|
// This header provides the format() function which is essentially sprintf()
|
|
// returning std::string and converting std::string arguments to char *.
|
|
//---
|
|
|
|
#ifndef FXOS_UTIL_FORMAT_H
|
|
#define FXOS_UTIL_FORMAT_H
|
|
|
|
#include <memory>
|
|
#include <iostream>
|
|
#include <string>
|
|
#include <memory>
|
|
#include <cstdio>
|
|
|
|
/* Format a string with printf() syntax */
|
|
template<typename... Args>
|
|
std::string _format_do(std::string const &format, Args &&...args)
|
|
{
|
|
/* Reserve space for snprintf() to put its NUL */
|
|
size_t size = snprintf(nullptr, 0, format.c_str(), args...) + 1;
|
|
|
|
std::unique_ptr<char[]> buf(new char[size]);
|
|
snprintf(buf.get(), size, format.c_str(), args...);
|
|
|
|
/* Remove the NUL from the string */
|
|
return std::string(buf.get(), buf.get() + size - 1);
|
|
}
|
|
|
|
/* Convert std::string to char * when printing (by @Zitrax on Github) */
|
|
template<typename T>
|
|
auto _format_convert(T &&t)
|
|
{
|
|
if constexpr(std::is_same<std::remove_cv_t<std::remove_reference_t<T>>,
|
|
std::string>::value)
|
|
return std::forward<T>(t).c_str();
|
|
else
|
|
return std::forward<T>(t);
|
|
}
|
|
|
|
/* String formatting with std::string support in %s */
|
|
template<typename... Args>
|
|
std::string format(std::string const &format, Args &&...args)
|
|
{
|
|
return _format_do(format, _format_convert(std::forward<Args>(args))...);
|
|
}
|
|
|
|
#endif /* FXOS_UTIL_FORMAT_H */
|