-
Notifications
You must be signed in to change notification settings - Fork 1
/
func.hpp
115 lines (100 loc) · 2.39 KB
/
func.hpp
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
108
109
110
111
112
113
114
115
#pragma once
#include "file.hpp"
#include "mem_db.hpp"
#include "osal.hpp"
#include <iostream>
#include <utility>
template <typename Arg, typename... Args>
void serArgs(OStrm &ost, Arg &&arg, Args &&... args)
{
ser(ost, arg);
serArgs(ost, std::forward<Args>(args)...);
}
void serArgs(OStrm &) {}
class Val
{
public:
template <typename T>
constexpr auto operator()(const char *, const T &value) -> void
{
if constexpr (internal::IsSerializableClassV<T>)
value.ser(*this);
else
serVal(value);
}
auto operator()(const char *, const File &value) -> void
{
isValid = isValid && (getFileModification(value.name) == value.modifTime);
}
template <typename T>
constexpr auto serVal(const T &) noexcept
-> std::enable_if_t<std::is_arithmetic_v<T> || std::is_enum_v<T>>
{
}
auto serVal(const std::string &) noexcept -> void {}
template <typename T>
constexpr auto serVal(const std::vector<T> &value) -> void
{
for (auto &&v : value)
{
operator()("v", v);
if (!isValid)
return;
}
}
template <typename T>
constexpr auto serVal(const std::unique_ptr<T> &value) -> void
{
if (!value)
return;
isValid = isValid && operator()("*value", *value);
}
template <typename T>
constexpr auto serVal(const std::optional<T> &value) -> void
{
if (!value)
return;
operator()("*value", *value);
}
bool isValid = true;
};
template <typename T>
constexpr auto validate(const T &value) -> bool
{
Val v;
if constexpr (internal::IsSerializableClassV<T>)
value.ser(v);
else
v("value", value);
return v.isValid;
}
auto validate(const File &value) -> bool
{
return getFileModification(value.name) == value.modifTime;
}
template <typename R, typename... Args, typename... ArgsU>
R func(R(f)(ArgsU...), Args &&... args)
{
auto &db = MemDb::instance();
OStrm ost;
ser(ost, typeid(f).name());
serArgs(ost, std::forward<Args>(args)...);
uint32_t hash;
MurmurHash3_x86_32(ost.str().data(), ost.str().size(), 0, &hash);
auto serRet = db.lookup(hash);
auto execAndCache = [&]() {
const auto ret = f(args...);
OStrm ost;
ser(ost, ret);
db.insert(hash, ost.str());
return ret;
};
if (!serRet)
return execAndCache();
IStrm istrm(serRet->data(), serRet->data() + serRet->size());
R ret;
deser(istrm, ret);
if (!validate(ret))
return execAndCache();
return ret;
}