-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.h
97 lines (84 loc) · 2.29 KB
/
helpers.h
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
#ifndef HELPERS_H
#define HELPERS_H
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <algorithm>
using namespace std;
template<typename K, typename V, typename def>
V map_get(const map<K,V> &m, K key, def defaultValue)
{
auto iter = m.find(key);
if(iter != m.end())
return iter->second;
return defaultValue;
}
template<typename K, typename V, typename def>
V map_get(const unordered_map<K,V> &m, K key, def defaultValue)
{
auto iter = m.find(key);
if(iter != m.end())
return iter->second;
return defaultValue;
}
// Given an ordering, return a list of swaps to put a list in that order.
// This ordering can be applied with run_swaps.
void make_swaps(vector<int> order, vector<pair<int,int>> &swaps);
template<typename T>
void run_swaps(T data, const vector<pair<int,int>> &swaps)
{
for(const auto &s: swaps)
{
int src = s.first;
int dst = s.second;
swap(data[src], data[dst]);
}
}
string vssprintf(const char *fmt, va_list va);
string ssprintf(const char *fmt, ...);
string subst(string s, string from, string to);
string basename(const string &dir);
string getExtension(string path);
string setExtension(string path, const string &ext);
void split(const string &source, const string &delimitor, vector<string> &result, const bool ignoreEmpty=true);
float LinearToSRGB(float value);
float SRGBToLinear(float value);
// Convert a 0-1 float to a 0-255 int. The value must already be clamped.
inline uint8_t FloatToInt(float f)
{
union { float f; uint32_t i; } u;
u.f = 32768.0f + f * (255.0f / 256.0f);
return (uint8_t) u.i;
}
template<typename T>
T clamp(T value, T low, T high)
{
// If low and high are flipped, correct it. This happens for eg.
// scale_clamp(value, 0, 1, 1, 0).
T low1 = min(low, high);
T high1 = max(low, high);
return min(max(value, low1), high1);
}
template<typename T>
T scale(T value, T l1, T h1, T l2, T h2)
{
return (value - l1) * (h2 - l2) / (h1 - l1) + l2;
}
template<typename T>
T scale_clamp(T value, T l1, T h1, T l2, T h2)
{
return ::clamp(scale(value, l1, h1, l2, h2), l2, h2);
}
class StringException: public exception
{
public:
StringException(string s)
{
value = s;
}
const char *what() const { return value.c_str(); }
private:
string value;
};
#endif