-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathecmcCppPersist.hpp
More file actions
97 lines (77 loc) · 2.08 KB
/
Copy pathecmcCppPersist.hpp
File metadata and controls
97 lines (77 loc) · 2.08 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*************************************************************************\
* Copyright (c) 2026 Paul Scherrer Institute
* ecmc is distributed subject to a Software License Agreement found
* in file LICENSE that is included with this distribution.
*
* ecmcCppPersist.hpp
*
\*************************************************************************/
#pragma once
#include <fstream>
#include <string>
#include <type_traits>
#include <utility>
namespace ecmcCpp {
template <typename T>
class RetainedValue {
static_assert(std::is_trivially_copyable<T>::value,
"RetainedValue requires a trivially copyable type");
public:
T Value {};
bool Loaded {false};
bool SaveOk {false};
bool LoadOk {false};
RetainedValue() = default;
explicit RetainedValue(std::string path) : path_(std::move(path)) {}
void setPath(std::string path) { path_ = std::move(path); }
const std::string& path() const { return path_; }
bool load() { return load(path_); }
bool load(const std::string& path) {
Loaded = false;
LoadOk = false;
if (path.empty()) {
return false;
}
std::ifstream stream(path, std::ios::binary);
if (!stream.is_open()) {
return false;
}
T temp {};
stream.read(reinterpret_cast<char*>(&temp), sizeof(T));
if (!stream.good() && !stream.eof()) {
return false;
}
if (stream.gcount() != static_cast<std::streamsize>(sizeof(T))) {
return false;
}
Value = temp;
Loaded = true;
LoadOk = true;
path_ = path;
return true;
}
bool save() const { return save(path_); }
bool save(const std::string& path) const {
if (path.empty()) {
return false;
}
std::ofstream stream(path, std::ios::binary | std::ios::trunc);
if (!stream.is_open()) {
return false;
}
stream.write(reinterpret_cast<const char*>(&Value), sizeof(T));
return stream.good();
}
bool store() {
SaveOk = save(path_);
return SaveOk;
}
bool restore() {
const bool ok = load(path_);
LoadOk = ok;
return ok;
}
private:
std::string path_;
};
} // namespace ecmcCpp