MCPcopy Create free account
hub / github.com/BowenFu/matchit.cpp / sample

Function sample

sample/Range-pattern.cpp:12–75  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10} // namespace binary
11
12void sample()
13{
14 constexpr auto c = 'f';
15 constexpr auto valid_variable = match(c)(
16 // clang-format off
17 pattern | ('a' <= _ && _ <= 'z') = expr(true),
18 pattern | ('A' <= _ && _ <= 'Z') = expr(true),
19 pattern | _ = expr(false)
20 // clang-format on
21 );
22 static_cast<void>(valid_variable);
23
24 constexpr auto ph = 10;
25 std::cout << match(ph)(
26 // clang-format off
27 pattern | (0 <= _ && _ <= 6 ) = expr("acid"),
28 pattern | (7 ) = expr("neutral"),
29 pattern | (8 <= _ && _ <= 14) = expr("base"),
30 pattern | (_ ) = [] { assert(false && "unreachable"); return ""; })
31 // clang-format on
32 << std::endl;
33
34 // using paths to constants:
35 constexpr uint8_t TROPOSPHERE_MIN = 6;
36 constexpr uint8_t TROPOSPHERE_MAX = 20;
37
38 constexpr uint8_t STRATOSPHERE_MIN = TROPOSPHERE_MAX + 1;
39 constexpr uint8_t STRATOSPHERE_MAX = 50;
40
41 constexpr uint8_t MESOSPHERE_MIN = STRATOSPHERE_MAX + 1;
42 constexpr uint8_t MESOSPHERE_MAX = 85;
43
44 constexpr auto altitude = 70;
45
46 std::cout << match(altitude)(
47 // clang-format off
48 pattern | (TROPOSPHERE_MIN <= _ && _ <= TROPOSPHERE_MAX ) = expr("troposphere"),
49 pattern | (STRATOSPHERE_MIN <= _ && _ <= STRATOSPHERE_MAX) = expr("stratosphere"),
50 pattern | (MESOSPHERE_MIN <= _ && _ <= MESOSPHERE_MAX ) = expr("mesosphere"),
51 pattern | (_ ) = expr("outer space, maybe"))
52 // clang-format on
53 << std::endl;
54
55 constexpr auto n_items = 20'832'425U;
56 constexpr auto bytes_per_item = 12U;
57
58 Id<uint64_t> size;
59 match(n_items * bytes_per_item)(
60 // clang-format off
61 pattern | size.at(binary::MEGA <= _ && _ <= binary::GIGA) = [&] { std::cout << "It fits and occupies " << *size << " bytes" << std::endl; }
62 // clang-format on
63 );
64
65 // using qualified paths:
66 std::cout
67 << match(static_cast<uint64_t>(0xfacade))(
68 // clang-format off
69 pattern | (0U <= _ && _ <= std::numeric_limits<uint8_t>::max()) = expr("fits in a u8"),

Callers 1

mainFunction · 0.70

Calls 3

matchFunction · 0.50
exprFunction · 0.50
atMethod · 0.45

Tested by

no test coverage detected