Virtual Testbed
Ship dynamics simulator for extreme conditions
cache.hh
1 #ifndef VTESTBED_CACHE_CACHE_HH
2 #define VTESTBED_CACHE_CACHE_HH
3 
4 #include <fstream>
5 #include <ios>
6 #include <sstream>
7 #include <string>
8 
9 namespace vtb {
10 
12  namespace cache {
13 
15  cache_directory();
16 
18  cache_file(std::string key, std::string subkey);
19 
20  void
21  make_directory(const std::string& dir);
22 
23  void
24  print_cache(
25  const std::string& tag,
26  const std::string& filename,
27  const std::string& subkey
28  );
29 
30  template <class T>
31  class cache_guard {
32 
33  private:
34  T& _object;
35  std::string _filename;
36  std::string _subkey;
37  std::ios::openmode _mode;
38  bool _hit = false;
39 
40  public:
41 
42  inline explicit
44  T& object,
45  std::string key,
46  std::string subkey,
47  std::ios::openmode mode=std::ios::openmode{}
48  ):
49  _object{object},
50  _filename{cache_file(key, subkey)},
51  _subkey(subkey),
52  _mode{mode} {
53  std::ifstream in{this->_filename, this->_mode | std::ios::in};
54  std::string tag = "miss";
55  if (in.is_open()) {
56  tag = "hit";
57  this->_hit = true;
58  in >> _object;
59  }
60  print_cache(tag, this->_filename, subkey);
61  }
62 
63  inline explicit
65 
66  inline
67  ~cache_guard() {
68  if (!this->_hit) {
70  this->_filename,
71  this->_mode | std::ios::out
72  } << this->_object;
73  }
74  }
75 
76  inline bool
77  hit() const noexcept {
78  return this->_hit;
79  }
80 
81  inline void
82  invalidate() {
83  this->_hit = false;
84  print_cache("invalidate", this->_filename, this->_subkey);
85  }
86 
87  };
88 
89  }
90 
91 }
92 
93 #endif // vim:filetype=cpp
Main namespace.
Definition: convert.hh:9