-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples_defer.cpp
75 lines (62 loc) · 1.72 KB
/
examples_defer.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
#include <dice/template-library/defer.hpp>
#include <cassert>
#include <cstdio>
#include <filesystem>
#include <random>
#include <string>
/**
* Some C Api File handling
*/
void write_to_file(std::filesystem::path const &p) {
FILE *f = fopen(p.c_str(), "w");
if (f == nullptr) {
return;
}
DICE_DEFER {
fclose(f);
};
std::string const s = "Spherical Cow";
fwrite(s.data(), 1, s.size(), f);
}
/**
* Copies a file from src to dst, will not overwrite dst
* if copying does not succeed
*
* @note Inspired by Andrei Alexandrescu's “Declarative Control Flow" presentation
*/
void copy_file_transact(std::filesystem::path const &src, std::filesystem::path const &dst) {
std::filesystem::path const dst2 = dst.string() + ".deleteme";
DICE_DEFER_TO_FAIL {
std::error_code ec;
std::filesystem::remove(dst2, ec);
};
std::filesystem::copy_file(src, dst2);
std::filesystem::rename(dst2, dst);
}
/**
* Converts a string to and int with a postcondition check
*
* @note Inspired by Andrei Alexandrescu's “Declarative Control Flow" presentation
*/
int string_to_int(std::string const &integer) {
int value = std::stoi(integer);
DICE_DEFER_TO_SUCCESS {
// check postcondition
assert(std::to_string(value) == integer);
};
return value;
}
int main() {
std::filesystem::path const p = "/tmp/dice-template-lib-defer-example1-" + std::to_string(std::random_device{}());
std::filesystem::path const p2 = "/tmp/dice-template-lib-defer-example2-" + std::to_string(std::random_device{}());
DICE_DEFER {
std::error_code ec;
std::filesystem::remove(p, ec);
std::filesystem::remove(p2, ec);
};
write_to_file(p);
copy_file_transact(p, p2);
std::string const i = "42";
int const j = 10 + string_to_int(i);
assert(j == 52);
}