summaryrefslogtreecommitdiffhomepage
path: root/compat/util.hpp
blob: 59c270ed461d36e58204011b02a919b75804f38d (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
83
84
85
86
87
#pragma once

#include "ndebug-guard.hpp"
#include "run-in-thread.hpp"
#include "meta.hpp"
#include "functional.hpp"
#include "macros.hpp"

#include <memory>
#include <cmath>
#include <utility>

#include <QSharedPointer>
#include <QDebug>

#define progn(...) (([&]() { __VA_ARGS__ })())
#define prog1(x, ...) (([&]() { auto _ret1324 = (x); do { __VA_ARGS__; } while (0); return _ret1324; })())

#define once_only(...) progn(static bool once = false; if (!once) { once = true; __VA_ARGS__; })
#define load_time_value(x) \
    progn( \
        static const auto _value132((x)); \
        return static_cast<decltype(_value132)&>(value132); \
    )

template<typename t> using mem = std::shared_ptr<t>;
template<typename t> using ptr = std::unique_ptr<t>;

template<typename t>
inline int iround(const t& val)
{
    return int(std::round(val));
}

template<typename t>
inline unsigned uround(const t& val)
{
    return std::round(std::fmax(t(0), val));
}

namespace util_detail {

template<typename n>
inline auto clamp_float(n val, n min, n max)
{
    return std::fmin(std::fmax(val, min), max);
}

template<typename n>
struct clamp final
{
    static inline auto clamp_(const n& val, const n& min, const n& max)
    {
        if (unlikely(val > max))
            return max;
        if (unlikely(val < min))
            return min;
        return val;
    }
};

template<>
struct clamp<float>
{
    static inline auto clamp_(float val, float min, float max)
    {
        return clamp_float(val, min, max);
    }
};

template<>
struct clamp<double>
{
    static inline auto clamp_(double val, double min, double max)
    {
        return clamp_float(val, min, max);
    }
};

} // ns util_detail

template<typename t, typename u, typename w>
inline auto clamp(const t& val, const u& min, const w& max)
{
    using tp = decltype(val + min + max);
    return ::util_detail::clamp<tp>::clamp_(val, min, max);
}