Skip to content

Commit 475df22

Browse files
committed
Use std::format in multiple places
1 parent c0cded0 commit 475df22

34 files changed

+140
-180
lines changed

common/include/common/config/RegKey.h

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#pragma once
22

33
#include <utility>
4+
#include <cstdint>
45
#include <windows.h>
56
#include <common/error/Win32Error.h>
67

common/include/common/error/Exception.h

+5-20
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
#pragma once
22

3-
#include <cstdarg>
4-
#include <cstdio>
53
#include <exception>
64
#include <string>
7-
#include <memory>
5+
#include <format>
86

97
#define THROW_EXCEPTION(...) throw Exception({__FILE__, __LINE__}, __VA_ARGS__)
108

@@ -17,24 +15,11 @@ class Exception : public std::exception
1715
int line;
1816
};
1917

20-
Exception(SourceLocation loc, const char* format, ...)
18+
template<typename... Args>
19+
Exception(SourceLocation loc, std::format_string<Args...> fmt, Args&&... args)
2120
{
22-
va_list args;
23-
va_start(args, format);
24-
int size = 1;
25-
size += std::vsnprintf(nullptr, 0, format, args);
26-
size += std::snprintf(nullptr, 0, " in %s:%u", loc.file, loc.line);
27-
va_end(args);
28-
29-
std::unique_ptr<char[]> buf(new char[size]);
30-
31-
va_start(args, format);
32-
int pos = 0;
33-
pos += std::vsnprintf(buf.get() + pos, size - pos, format, args);
34-
std::snprintf(buf.get() + pos, size - pos, " in %s:%u", loc.file, loc.line);
35-
va_end(args);
36-
37-
m_what = buf.get();
21+
m_what = std::format(fmt, std::forward<Args>(args)...);
22+
std::format_to(std::back_inserter(m_what), " in {}:{}", loc.file, loc.line);
3823
}
3924

4025
[[nodiscard]] const char* what() const noexcept override

common/include/common/utils/string-utils.h

-16
Original file line numberDiff line numberDiff line change
@@ -164,22 +164,6 @@ struct StringMatcher
164164
}
165165
};
166166

167-
PRINTF_FMT_ATTRIBUTE(1, 2)
168-
inline std::string string_format(const char* format, ...)
169-
{
170-
std::va_list args;
171-
va_start(args, format);
172-
int size = vsnprintf(nullptr, 0, format, args) + 1; // Extra space for '\0'
173-
va_end(args);
174-
std::string str;
175-
str.resize(size);
176-
va_start(args, format);
177-
vsnprintf(str.data(), size, format, args);
178-
va_end(args);
179-
str.resize(size - 1); // We don't want the '\0' inside
180-
return str;
181-
}
182-
183167
inline std::string_view get_filename_without_ext(std::string_view filename)
184168
{
185169
auto dot_pos = filename.rfind('.');

common/src/HttpRequest.cpp

+7-11
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#include <common/error/Win32Error.h>
33
#include <string>
44
#include <string_view>
5-
#include <sstream>
5+
#include <format>
66
#include <cassert>
77
#include <cctype>
88

@@ -19,11 +19,11 @@ static ParsedUrl parse_http_url(std::string_view url)
1919
std::string_view http = "http://";
2020
std::string_view https = "https://";
2121
size_t host_pos = 0;
22-
if (url.substr(0, https.size()) == https) {
22+
if (url.starts_with(https)) {
2323
result.ssl = true;
2424
host_pos = https.size();
2525
}
26-
else if (url.substr(0, http.size()) == http) {
26+
else if (url.starts_with(http)) {
2727
result.ssl = false;
2828
host_pos = http.size();
2929
}
@@ -95,9 +95,7 @@ HttpRequest::HttpRequest(std::string_view url, const char* method, HttpSession&
9595

9696
void HttpRequest::add_header(std::string_view name, std::string_view value)
9797
{
98-
std::stringstream sstream;
99-
sstream << name << ": " << value << "\r\n";
100-
auto str = sstream.str();
98+
auto str = std::format("{}: {}", name, value);
10199
add_raw_headers(str);
102100
}
103101

@@ -124,7 +122,7 @@ void HttpRequest::write(const void* data, size_t len)
124122
if (!InternetWriteFile(m_req, data, len, &written))
125123
THROW_WIN32_ERROR();
126124
if (!written)
127-
THROW_EXCEPTION("Unable to write %lu request body bytes", len);
125+
THROW_EXCEPTION("Unable to write {} request body bytes", len);
128126
data = static_cast<const std::byte*>(data) + written;
129127
len -= written;
130128
}
@@ -150,7 +148,7 @@ void HttpRequest::send(std::string_view body)
150148
}
151149

152150
if (status_code != 200) {
153-
throw std::runtime_error(std::string("Invalid HTTP status code: ") + std::to_string(status_code));
151+
throw std::runtime_error(std::format("Invalid HTTP status code: {}", status_code));
154152
}
155153
}
156154

@@ -200,13 +198,11 @@ static bool is_uri_reserved_char(char c)
200198

201199
std::string encode_uri_component(std::string_view value)
202200
{
203-
char buf[8];
204201
std::string result;
205202
result.reserve(value.size());
206203
for (char c : value) {
207204
if (is_uri_reserved_char(c)) {
208-
sprintf(buf, "%%%02X", static_cast<unsigned char>(c));
209-
result += buf;
205+
std::format_to(std::back_inserter(result), "%{:02X}", static_cast<unsigned char>(c));
210206
} else {
211207
result += c;
212208
}

common/src/utils/os-utils.cpp

+4-8
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
#include <common/utils/os-utils.h>
2-
#include <common/utils/string-utils.h>
32
#include <xlog/xlog.h>
4-
#include <iomanip>
53
#include <common/error/Exception.h>
64
#include <common/error/Win32Error.h>
75
#include <cstring>
6+
#include <format>
87

98
#ifdef __GNUC__
109
#ifndef __cpuid
@@ -21,7 +20,7 @@ std::string get_os_version()
2120
if (!GetVersionEx(&ver_info))
2221
THROW_WIN32_ERROR("GetVersionEx failed");
2322

24-
return string_format("%lu.%lu.%lu", ver_info.dwMajorVersion, ver_info.dwMinorVersion, ver_info.dwBuildNumber);
23+
return std::format("{}.{}.{}", ver_info.dwMajorVersion, ver_info.dwMinorVersion, ver_info.dwBuildNumber);
2524
}
2625

2726
std::string get_real_os_version()
@@ -50,7 +49,7 @@ std::string get_real_os_version()
5049
THROW_WIN32_ERROR("VerQueryValueA returned unknown block");
5150
auto* file_info = static_cast<VS_FIXEDFILEINFO*>(block);
5251

53-
return string_format("%d.%d.%d",
52+
return std::format("{}.{}.{}",
5453
HIWORD(file_info->dwProductVersionMS),
5554
LOWORD(file_info->dwProductVersionMS),
5655
HIWORD(file_info->dwProductVersionLS));
@@ -119,15 +118,12 @@ const char* get_process_elevation_type()
119118
std::string get_cpu_id()
120119
{
121120
int cpu_info[4] = {0};
122-
std::stringstream ss;
123121
#ifndef __GNUC__
124122
__cpuid(cpu_info, 1);
125123
#else
126124
__cpuid(1, cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]);
127125
#endif
128-
ss << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << cpu_info[0] << ' ' << cpu_info[1] << ' '
129-
<< cpu_info[2] << ' ' << cpu_info[3];
130-
return ss.str();
126+
return std::format("{:08X} {:08X} {:08X} {:08X}", cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]);
131127
}
132128

133129
std::string get_cpu_brand()

crash_handler/MiniDumpHelper.cpp

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "MiniDumpHelper.h"
2+
#include <format>
23

34
#define CRASHHANDLER_ERR(msg) MessageBox(nullptr, TEXT(msg), 0, MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TASKMODAL)
45

@@ -75,9 +76,8 @@ bool MiniDumpHelper::write_dump(const char* path, PEXCEPTION_POINTERS exception_
7576
nullptr);
7677

7778
if (INVALID_HANDLE_VALUE == file) {
78-
char buf[256];
79-
sprintf(buf, "Error %lu! CreateFile failed when writing a Minidump.", GetLastError());
80-
CRASHHANDLER_ERR(buf);
79+
std::string s = std::format("Error {}! CreateFile failed when writing a Minidump.", GetLastError());
80+
CRASHHANDLER_ERR(s.c_str());
8181
return false;
8282
}
8383

@@ -119,9 +119,8 @@ bool MiniDumpHelper::write_dump(const char* path, PEXCEPTION_POINTERS exception_
119119
auto process_id = GetProcessId(process);
120120
BOOL result = m_MiniDumpWriteDump(process, process_id, file, dump_type, &exc_info, nullptr, callback_info_ptr);
121121
if (!result) {
122-
char buf[256];
123-
sprintf(buf, "MiniDumpWriteDump %lu %lu %p failed with error %lu", process_id, thread_id, file, GetLastError());
124-
CRASHHANDLER_ERR(buf); // ERROR_INVALID_PARAMETER?
122+
std::string s = std::format("MiniDumpWriteDump {} {} {} failed with error {}", process_id, thread_id, file, GetLastError());
123+
CRASHHANDLER_ERR(s.c_str()); // ERROR_INVALID_PARAMETER?
125124
}
126125

127126
CloseHandle(file);

crash_handler/TextDumpHelper.h

+19-32
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#include <windows.h>
22
#include <psapi.h>
33
#include <common/error/Win32Error.h>
4-
#include <ostream>
54
#include <fstream>
5+
#include <format>
66
#include <ctime>
77
#include <cassert>
88
#include <cstring>
@@ -12,19 +12,6 @@
1212
#include <cstddef>
1313
#include "ProcessMemoryCache.h"
1414

15-
inline std::string StringFormat(const char* format, ...)
16-
{
17-
va_list args;
18-
va_start(args, format);
19-
int size = vsnprintf(nullptr, 0, format, args) + 1;// Extra space for '\0'
20-
va_end(args);
21-
std::unique_ptr<char[]> buf(new char[size]);
22-
va_start(args, format);
23-
vsnprintf(buf.get(), size, format, args);
24-
va_end(args);
25-
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
26-
}
27-
2815
class TextDumpHelper {
2916
private:
3017
SYSTEM_INFO m_sys_info;
@@ -70,7 +57,7 @@ class TextDumpHelper {
7057
}
7158
if (prefix) {
7259
auto addr = exc_rec.ExceptionInformation[1];
73-
out << prefix << StringFormat(" location %08X caused an access violation.\n", addr);
60+
out << prefix << std::format(" location {:08X} caused an access violation.\n", addr);
7461
}
7562
}
7663
out << std::endl;
@@ -125,20 +112,20 @@ class TextDumpHelper {
125112
void write_exception_info(std::ostream& out, const EXCEPTION_RECORD& exc_rec)
126113
{
127114
out << "Exception Record:\n";
128-
out << " ExceptionCode = " << StringFormat("%08X", exc_rec.ExceptionCode) << "\n";
129-
out << " ExceptionFlags = " << StringFormat("%08X", exc_rec.ExceptionFlags) << "\n";
130-
out << " ExceptionAddress = " << StringFormat("%08X", exc_rec.ExceptionAddress) << "\n";
115+
out << " ExceptionCode = " << std::format("{:08X}", exc_rec.ExceptionCode) << "\n";
116+
out << " ExceptionFlags = " << std::format("{:08X}", exc_rec.ExceptionFlags) << "\n";
117+
out << " ExceptionAddress = " << std::format("{}", exc_rec.ExceptionAddress) << "\n";
131118
for (unsigned i = 0; i < exc_rec.NumberParameters; ++i)
132-
out << " ExceptionInformation[" << i << "] = " << StringFormat("%08X", exc_rec.ExceptionInformation[i]) << "\n";
119+
out << " ExceptionInformation[" << i << "] = " << std::format("{:08X}", exc_rec.ExceptionInformation[i]) << "\n";
133120
out << std::endl;
134121
}
135122

136123
void write_context(std::ostream& out, const CONTEXT& ctx)
137124
{
138125
out << "Context:\n";
139-
out << StringFormat("EIP=%08X EFLAGS=%08X\n", ctx.Eip, ctx.EFlags);
140-
out << StringFormat("EAX=%08X EBX=%08X ECX=%08X EDX=%08X\n", ctx.Eax, ctx.Ebx, ctx.Ecx, ctx.Edx);
141-
out << StringFormat("ESP=%08X EBP=%08X ESI=%08X EDI=%08X\n", ctx.Esp, ctx.Ebp, ctx.Esi, ctx.Edi);
126+
out << std::format("EIP={:08X} EFLAGS={:08X}\n", ctx.Eip, ctx.EFlags);
127+
out << std::format("EAX={:08X} EBX={:08X} ECX={:08X} EDX={:08X}\n", ctx.Eax, ctx.Ebx, ctx.Ecx, ctx.Edx);
128+
out << std::format("ESP={:08X} EBP={:08X} ESI={:08X} EDI={:08X}\n", ctx.Esp, ctx.Ebp, ctx.Esi, ctx.Edi);
142129
out << std::endl;
143130
}
144131

@@ -158,9 +145,9 @@ class TextDumpHelper {
158145
{
159146
out << "Memory map:\n";
160147
for (auto& mbi: m_memory_map) {
161-
out << StringFormat("%08X: State %08X Protect %08X Type %08X RegionSize %08X\n",
148+
out << std::format("{}: State {:08X} Protect {:08X} Type {:08X} RegionSize {:08X}\n",
162149
mbi.BaseAddress, mbi.State, mbi.Protect, mbi.Type, mbi.RegionSize);
163-
//out << StringFormat(" AllocBase %x AllocProtect %x\n", mbi.AllocationBase, mbi.AllocationProtect);
150+
//out << std::format(" AllocBase {:x} AllocProtect {:x}\n", mbi.AllocationBase, mbi.AllocationProtect);
164151
}
165152
out << std::endl;
166153
}
@@ -357,15 +344,15 @@ class TextDumpHelper {
357344
{
358345
constexpr size_t num_cols = 8;
359346
for (unsigned i = 0; i < num_dwords; i += num_cols) {
360-
out << StringFormat("%08X:", base_addr + i * 4);
347+
out << std::format("{:08X}:", base_addr + i * 4);
361348
for (size_t j = 0; j < num_cols && i + j < num_dwords; ++j) {
362-
out << StringFormat(" %08X", data[i + j]);
349+
out << std::format(" {:08X}", data[i + j]);
363350
}
364351
out << " ";
365352
for (size_t j = 0; j < num_cols && i + j < num_dwords; ++j) {
366353
const char* as_chars = reinterpret_cast<const char*>(&data[i + j]);
367354
for (size_t k = 0; k < 4; ++k) {
368-
out << StringFormat("%c", std::isprint(as_chars[k]) ? as_chars[k] : '.');
355+
out << (std::isprint(as_chars[k]) ? as_chars[k] : '.');
369356
}
370357
}
371358
out << '\n';
@@ -403,21 +390,21 @@ class TextDumpHelper {
403390
{
404391
out << "Modules:\n";
405392
for (auto& mod_info : m_modules) {
406-
out << StringFormat("%08X - %08X: %s\n", mod_info.start_addr, mod_info.end_addr, mod_info.path.c_str());
393+
out << std::format("{:08X} - {:08X}: {}\n", mod_info.start_addr, mod_info.end_addr, mod_info.path);
407394
}
408395
out << std::endl;
409396
}
410397

411398
std::string format_module_relative_address(uintptr_t addr)
412399
{
413-
std::stringstream ss;
414-
ss << StringFormat("%08X", addr);
400+
std::string buf;
401+
std::format_to(std::back_inserter(buf), "{:08X}", addr);
415402
for (auto& mod_info : m_modules) {
416403
if (addr >= mod_info.start_addr && addr < mod_info.end_addr) {
417-
ss << StringFormat(" (%s+%X)", mod_info.name.c_str(), addr - mod_info.start_addr);
404+
std::format_to(std::back_inserter(buf), " ({}+{:X})", mod_info.name, addr - mod_info.start_addr);
418405
break;
419406
}
420407
}
421-
return ss.str();
408+
return buf;
422409
}
423410
};

crash_handler/ZipHelper.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class ZipHelper
4040

4141
std::ifstream file(path, std::ios_base::in | std::ios_base::binary);
4242
if (!file)
43-
THROW_EXCEPTION("cannot open %s", path);
43+
THROW_EXCEPTION("cannot open {}", path);
4444

4545
char buf[4096];
4646
while (!file.eof()) {

crash_handler/main.cpp

+3-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include "CrashReportApp.h"
22
#include <common/error/error-utils.h>
3+
#include <format>
34

45
int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) try
56
{
@@ -13,17 +14,13 @@ int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) try
1314
catch (const Win32xx::CException &e)
1415
{
1516
// Display the exception and quit
16-
std::ostringstream ss;
17-
ss << e.GetText() << "\nerror " << e.GetError() << ": " << e.GetErrorString();
18-
auto msg = ss.str();
17+
std::string msg = std::format("{}\nerror {}: {}", e.GetText(), e.GetError(), e.GetErrorString());
1918
MessageBox(nullptr, msg.c_str(), nullptr, MB_ICONERROR | MB_OK);
20-
2119
return -1;
2220
}
2321
// catch all unhandled std::exception types
2422
catch (const std::exception& e) {
25-
std::string msg = "Fatal error: ";
26-
msg += generate_message_for_exception(e);
23+
std::string msg = std::format("Fatal error: {}", generate_message_for_exception(e));
2724
MessageBox(nullptr, msg.c_str(), nullptr, MB_ICONERROR | MB_OK);
2825
return -1;
2926
}

editor_patch/main.cpp

-2
Original file line numberDiff line numberDiff line change
@@ -287,14 +287,12 @@ void CMainFrame_InvertSelection(CWnd* this_)
287287

288288
BOOL __fastcall CMainFrame_OnCmdMsg(CWnd* this_, int, UINT nID, int nCode, void* pExtra, void* pHandlerInfo)
289289
{
290-
char buf[256];
291290
constexpr int CN_COMMAND = 0;
292291

293292
if (nCode == CN_COMMAND) {
294293
std::function<void()> handler;
295294
switch (nID) {
296295
case ID_WIKI_EDITING_MAIN_PAGE:
297-
sprintf(buf, "ID_WIKI_EDITING_MAIN_PAGE %p", pHandlerInfo);
298296
handler = std::bind(CMainFrame_OpenHelp, this_);
299297
break;
300298
case ID_WIKI_HOTKEYS:

0 commit comments

Comments
 (0)