-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathleaf.cpp
50 lines (44 loc) · 1.61 KB
/
leaf.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
#include "thirdparty/leaf/leaf.hpp"
#include <cmath>
#include <span>
namespace leaf = boost::leaf;
struct InvalidValue {};
static leaf::result<void> doSqrt(std::span<double> values) noexcept __attribute__((noinline));
static leaf::result<void> doSqrt(std::span<double> values) noexcept {
for (auto& v : values) {
if (v < 0) return leaf::new_error(InvalidValue{});
v = sqrt(v);
}
return {};
}
unsigned leafResultSqrt(std::span<double> values, unsigned repeat) noexcept {
unsigned failures = 0;
for (unsigned index = 0; index != repeat; ++index) {
leaf::try_handle_some([&]() -> leaf::result<void> {
BOOST_LEAF_CHECK(doSqrt(values));
return {}; },
[&](InvalidValue) {
++failures;
});
}
return failures;
}
static leaf::result<unsigned> doFib(unsigned n, unsigned maxDepth) noexcept __attribute((noinline, optimize("no-optimize-sibling-calls")));
static leaf::result<unsigned> doFib(unsigned n, unsigned maxDepth) noexcept {
if (!maxDepth) return leaf::new_error(InvalidValue{});
if (n <= 2) return 1;
BOOST_LEAF_AUTO(n2, doFib(n - 2, maxDepth - 1));
BOOST_LEAF_AUTO(n1, doFib(n - 1, maxDepth - 1));
return n2 + n1;
}
unsigned leafResultFib(unsigned n, unsigned maxDepth) noexcept {
unsigned result = ~0u;
leaf::try_handle_some([&]() -> leaf::result<void> {
BOOST_LEAF_AUTO(v, doFib(n, maxDepth));
result = v;
return {}; },
[&](InvalidValue) {
result = 0;
});
return result;
}