OXYGENHUB
◆ main openmsx / src / utils / format.hh
952 B · C++ · last changed chore(): initial commit 1 month ago source blame history raw
1
#ifndef FORMAT_HH
2
#define FORMAT_HH
3
4
#include "zstring_view.hh"
5
6
#include <cassert>
7
#include <format>
8
#include <span>
9
#include <string_view>
10
#include <utility>
11
12
// Utility functions related to std::format
13
14
template<typename... Args>
15
std::string_view format_to_buf(
16
	std::span<char> buf, std::format_string<Args...> fmt, Args&&... args)
17
{
18
	auto r = std::format_to_n(buf.begin(), buf.size(), fmt, std::forward<Args>(args)...);
19
	assert(size_t(r.size) <= buf.size()); // must fit
20
	return {buf.data(), size_t(r.size)};
21
}
22
23
template<typename... Args>
24
zstring_view format_to_zbuf(
25
	std::span<char> buf, std::format_string<Args...> fmt, Args&&... args)
26
{
27
	assert(!buf.empty());
28
	// Reserve 1 byte for the terminating '\0'
29
	auto r = std::format_to_n(buf.begin(), buf.size() - 1, fmt, std::forward<Args>(args)...);
30
	assert(size_t(r.size) < buf.size()); // must fit with spare location for '\0'
31
	buf[r.size] = '\0';
32
	return {buf.data(), size_t(r.size)};
33
}
34
35
#endif