summaryrefslogtreecommitdiff
path: root/deimos/core/format.h
blob: 8a2c850fd302de74a3533c12a0b7ed0d386e1d69 (plain)
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
#pragma once

#include "deimos/core/base.h"

namespace deimos
{

class IWriter;

struct CustomFormatter
{
    using Callback = void (*)(IWriter*, const void* payload);
    
    const void* payload;
    Callback    callback;
};

template<typename T>
concept CustomFormattable = requires(IWriter* writer, const T& value)
{
    DeimosFormat(writer, value);
};

struct FormatArg
{
    enum Type : uint8_t
    {
        kInteger,
        kUnsignedInteger,
        kString,
        kCustom,
    };

    Type type;

    union
    {
        int64_t         integer;
        uint64_t        unsigned_integer;
        StringView      string;
        CustomFormatter custom;
    };

    constexpr explicit FormatArg(std::signed_integral auto value) :
        type{kInteger},
        integer{value}
    {}

    constexpr explicit FormatArg(std::unsigned_integral auto value) :
        type{kUnsignedInteger},
        unsigned_integer{value}
    {}

    constexpr explicit FormatArg(StringView value) :
        type{kString},
        string{value}
    {}

    template<CustomFormattable T>
    constexpr explicit FormatArg(const T& payload) :
        type{kCustom},
        custom{CustomFormatter{&payload, [](IWriter* writer, const void* raw)
        {
            DeimosFormat(writer, *(const T*)raw);
        }}}
    {
    }
};

template<typename T>
concept Formattable = std::is_constructible_v<FormatArg, T>;

void FormatVa(IWriter*, gsl::czstring fmt, Span<const FormatArg>);

template<Formattable... Args>
void Format(IWriter* writer, gsl::czstring fmt, Args&&... args)
{
    FormatVa(writer, fmt, { FormatArg(std::forward<Args>(args))... });
}

} // namespace deimos