Skip to content

Instantly share code, notes, and snippets.

class StringFormatState {
public:
using value_type = wchar_t;
StringFormatState() : m_debug(&m_result) {
m_debug = m_debug.nospace();
}
void append(wchar_t character) {
/* Surrogates are not supported. */
template<class T>
concept debug_streamable = requires (QDebug a, T b) { a << b; };
template<class T> requires debug_streamable<T> && std::is_class_v<std::remove_cvref_t<T>>
struct std::formatter<T, wchar_t> : public formatter<QStringView, wchar_t> {
using base_type = formatter<QStringView, wchar_t>;
template <typename FormatContext>
auto format(const T& value, FormatContext& ctx) {
QString buffer;
template<>
struct std::formatter<QStringView, wchar_t> : public formatter<std::wstring_view, wchar_t> {
using base_type = formatter<std::wstring_view, wchar_t>;
template <class FormatContext>
auto format(QStringView value, FormatContext& ctx) {
QStringToWcharConversionBuffer buffer(value);
return base_type::format(buffer.view(), ctx);
}
};
class QStringToWcharConversionBuffer {
public:
QStringToWcharConversionBuffer(QStringView source) {
if (sizeof(wchar_t) == sizeof(QChar)) {
const wchar_t* data = reinterpret_cast<const wchar_t*>(source.data());
m_view = std::wstring_view(data, data + source.size());
} else {
m_buffer.reserve(source.size());
qsizetype size = source.toWCharArray(m_buffer.data());
m_view = std::wstring_view(m_buffer.data(), size);
template<class... Args>
QString sformat(std::wstring_view formatString, Args&&... args) {
QString result;
QStringBackInsertConvertingProxy resultProxy(&result);
std::format_to(std::back_inserter(resultProxy), formatString, std::forward<Args>(args)...);
return result;
}
// Then this works:
QString s = sformat(L"X = {:#x}", 123);
struct QStringBackInsertConvertingProxy {
public:
using value_type = wchar_t;
QStringBackInsertConvertingProxy(QString* target) : m_target(target) {}
void push_back(wchar_t character) {
/* Surrogates are not supported. */
assert(sizeof(wchar_t) == sizeof(char16_t) || !QChar::requiresSurrogates(static_cast<char32_t>(character)));
return BadCastException::tr("Could not deserialize value '%1' as %3").arg("x").arg("int");
return BadCastException::tr("Could not deserialize value '%1' as %2").arg("x").arg("int");