HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
format.hpp
1// Copyright Take Vos 2019-2020.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7namespace tt {
8namespace detail {
9template<typename Arg>
10auto u8format_argument_cast(Arg const &arg) noexcept -> std::
11 conditional_t<std::is_same_v<Arg, std::u8string_view> || std::is_same_v<Arg, std::u8string>, std::string_view, Arg const &>
12{
13 if constexpr (std::is_same_v<Arg, std::u8string_view> || std::is_same_v<Arg, std::u8string>) {
14 return std::string_view{reinterpret_cast<char const *>(arg.data()), arg.size()};
15 } else {
16 return arg;
17 }
18}
19
20} // namespace tt
21
22template<typename... Args>
23std::u8string format(const std::locale &loc, std::u8string_view fmt, const Args &... args)
24{
25 // The current implementation assumes that `std::format()` is 8-bit clean and therefor compatible with UTF-8.
26 auto r = std::format(detail::u8format_argument_cast(fmt), detail::u8format_argument_cast(args)...);
27
28 // The following will need to allocate a copy of the formatted string.
29 // XXX sanitize the UTF-8 string here.
30 return std::u8string(reinterpret_cast<char8_t *>(r.data()), r.size());
31}
32
33template<typename... Args>
34std::u8string format(std::u8string_view fmt, const Args &... args)
35{
36 return format(std::locale::classic(), fmt, args...);
37}
38
39constexpr inline bool format_uses_arg_ids(const char *fmt)
40{
41 bool start_placeholder = false;
42
43 while (true) {
44 ttlet c = *(fmt++);
45 if (c == 0) {
46 return false;
47 } else if (c == '{') {
48 start_placeholder = true;
49 } else if (start_placeholder && c >= '0' && c <= '9') {
50 return true;
51 } else {
52 start_placeholder = false;
53 }
54 }
55}
56
57}
T classic(T... args)