Debian Codegraph @

terps/bocfel/stash.cpp

raw symbols SCIP
1 // Copyright 2021-2024 Chris Spiegel.
2 //
3 // SPDX-License-Identifier: MIT
4
5 #include <algorithm>
6 #include <memory>
7 #include <utility>
8 #include <vector>
9
10 #include "stash.h"
11 #include "types.h"
12
13 // Restoring (as in @restore) is done in-place, meaning that data
14 // structures used by the interpreter are updated during the restore. If
15 // any error is encountered during restore, the system could thus be in
16 // a state of partial update, preventing things from working properly.
17 // To avoid this, any structures which are updated in-place are first
18 // backed up. On restore failure, these will be restored. Anything can
19 // register functions to back up, restore, and free any particular piece
20 // of state that needs to be protected. The restore code will ensure
21 // these are all called appropriately.
22 //
23 // Required methods:
24 //
25 // void backup() - Stash away the current state for future restore.
26 // bool restore() - Restore the stashed state, returning true if it
27 // could successfully be restored, false otherwise.
28 // void free() - Free any resources that were allocated by
29 // backup(). This can be called at any time,
30 // including before any calls to backup(), and
31 // including multiple times in a row without any
32 // intervening call to backup().
33
34 static std::vector<std::unique_ptr<Stasher>> stashes;
35
36 void stash_register(std::unique_ptr<Stasher> stasher)
37 {
38 stashes.push_back(std::move(stasher));
39 }
40
41 Stash::~Stash()
42 {
43 free();
44 }
45
46 void Stash::backup()
47 {
48 for (const auto &stash : stashes) {
49 stash->backup();
50 }
51
52 m_have_stash = true;
53 }
54
55 bool Stash::restore()
56 {
57 bool success = std::all_of(stashes.begin(), stashes.end(), [](std::unique_ptr<Stasher> &stash) { return stash->restore(); });
58
59 free();
60
61 return success;
62 }
63
64 void Stash::free()
65 {
66 for (const auto &stash : stashes) {
67 stash->free();
68 }
69
70 m_have_stash = false;
71 }
72
73 bool Stash::exists() const
74 {
75 return m_have_stash;
76 }