1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
#pragma once
#include "asl/integers.hpp"
#include "asl/meta.hpp"
#include "asl/io.hpp"
#include "asl/span.hpp"
#include "asl/string_view.hpp"
namespace asl
{
class Formatter;
template<typename T>
concept formattable = requires (Formatter& f, const T& value)
{
AslFormat(f, value);
};
namespace format_internals
{
struct type_erased_arg
{
const void* data;
void (*fn)(Formatter&, const void*);
template<formattable T>
static constexpr void erased_fn(Formatter& f, const void* data)
{
AslFormat(f, *reinterpret_cast<const T*>(data));
}
template<formattable T>
explicit constexpr type_erased_arg(const T& arg)
: data{&arg}
, fn{erased_fn<T>}
{}
};
void format(Writer*, string_view fmt, span<const type_erased_arg> args);
} // namespace internals
class Formatter
{
Writer* m_writer;
public:
explicit constexpr Formatter(Writer* writer)
: m_writer{writer}
{}
constexpr void write(string_view s)
{
m_writer->write(as_bytes(s.as_span()));
}
};
template<formattable... Args>
void format(Writer* w, string_view fmt, const Args&... args)
{
if constexpr (types_count<Args...> > 0)
{
format_internals::type_erased_arg type_erased_args[] = {
format_internals::type_erased_arg(args)...
};
format_internals::format(w, fmt, type_erased_args);
}
else
{
format_internals::format(w, fmt, {});
}
}
template<isize_t N>
void AslFormat(Formatter& f, const char (&str)[N])
{
f.write(string_view(str, N - 1));
}
void AslFormat(Formatter& f, const char* str);
inline void AslFormat(Formatter& f, string_view sv)
{
f.write(sv);
}
void AslFormat(Formatter& f, float);
void AslFormat(Formatter& f, double);
void AslFormat(Formatter& f, bool);
void AslFormat(Formatter& f, uint8_t);
void AslFormat(Formatter& f, uint16_t);
void AslFormat(Formatter& f, uint32_t);
void AslFormat(Formatter& f, uint64_t);
void AslFormat(Formatter& f, int8_t);
void AslFormat(Formatter& f, int16_t);
void AslFormat(Formatter& f, int32_t);
void AslFormat(Formatter& f, int64_t);
string_view format_uint64(uint64_t value, span<char, 20> buffer);
} // namespace asl
|