forked from BowenFu/matchit.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPredicate-based-Discriminator.cpp
79 lines (68 loc) · 1.47 KB
/
Predicate-based-Discriminator.cpp
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
#include "matchit.h"
#include <iostream>
struct String
{
enum Storage
{
Local,
Remote
};
size_t size;
struct Rm
{
char *ptr;
int unused_allocated_space;
};
union
{
char local[32];
Rm remote;
};
// Predicate-based discriminator derived from `size`.
Storage index() const { return size > sizeof(local) ? Remote : Local; }
// Opt into Variant-Like protocol.
template <Storage S>
auto get_if();
char *data();
};
bool operator==(String::Rm const &lhs, String::Rm const &rhs)
{
return lhs.ptr == rhs.ptr &&
lhs.unused_allocated_space == rhs.unused_allocated_space;
}
// Opt into Variant-Like protocol.
template <String::Storage S>
auto String::get_if()
{
if constexpr (S == Local)
return index() == Local ? &local : nullptr;
else if constexpr (S == Remote)
return index() == Remote ? &remote : nullptr;
}
template <String::Storage S, typename Pat>
auto asEnum(Pat &&pat)
{
using namespace matchit;
return app([](auto &&x)
{ return x.template get_if<S>(); },
some(pat));
}
char *String::data()
{
using namespace matchit;
Id<char *> l;
Id<std::decay_t<decltype(remote)>> r;
return match(*this)(
pattern | asEnum<Local>(l) = expr(l),
pattern | asEnum<Remote>(r) = [&]
{ return (*r).ptr; });
}
int32_t main()
{
std::string rm = "long string.";
String x{};
x.size = 100;
x.remote = String::Rm{rm.data(), 100};
std::cout << x.data() << std::endl;
return 0;
}