summaryrefslogtreecommitdiff
path: root/deimos/core/format.h
blob: ba1a3e2f9735ea162eb9317be5b827e97bb7e706 (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
#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;
};

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<typename T>
    constexpr explicit FormatArg(const T& payload, CustomFormatter::Callback callback) :
        type{kCustom},
        custom{CustomFormatter{&payload, callback}}
    {}
};

template<typename T>
deimos::FormatArg DeimosMakeFormatArg(T&& value)
    requires std::is_constructible_v<deimos::FormatArg, T>
{
    return deimos::FormatArg(value);
}

template<typename T>
concept Formattable = std::same_as<deimos::FormatArg, decltype(DeimosMakeFormatArg(std::declval<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, { DeimosMakeFormatArg(std::forward<Args>(args))... });
}

} // namespace deimos