DISPLACE  1.0
A spatial model of fisheries to help sustainable fishing and maritime spatial planning
cacheddatastorage.h
Go to the documentation of this file.
1 #ifndef CACHEDDATASTORAGE_H
2 #define CACHEDDATASTORAGE_H
3 
4 #include <dbtypes.h>
5 #include <modeltypes.h>
6 
7 template <typename Data>
9 {
10 protected:
11  struct Record {
12  bool dirty = true;
14  std::shared_ptr<Data> data = nullptr;
15  };
16 
17  std::vector<Record> cachedData;
18 
20  while (cachedData.size() <= nodeId.toIndex())
21  cachedData.push_back(Record());
22  return cachedData.at(nodeId.toIndex());
23  }
24 
25  void updateData (types::tstep_t step, Data n) {
26  auto &d = getRecord(n.nodeId);
27  d.dirty = false;
28  d.cachedTstep = step;
29  d.data = std::make_shared<Data>(std::move(n));
30  }
31 
32 public:
34  virtual ~CachedDataStorage() noexcept = default;
35 
37  for(auto &e : cachedData) {
38  e.data.reset();
39  e.dirty = false;
40  e.cachedTstep = types::tstep_t(-1);
41  }
42  }
43 
44  virtual void queryAllData(types::tstep_t step) = 0;
45 
47  // Update all the cache with valid data, but null.
48  for(auto &e : cachedData) {
49  e.data.reset();
50  e.dirty = false;
51  e.cachedTstep = step;
52  }
53 
54  queryAllData(step);
55  }
56 
57  std::shared_ptr<Data> getData(types::NodeId nodeId, types::tstep_t tstep) {
58  auto &d = getRecord(nodeId);
59 
60  // it's clean. pass.
61  if (!d.dirty && d.cachedTstep == tstep)
62  return d.data;
63 
65  // the following code would be better but it's not optimal.
66  //p->refreshDataForNode(nodeId, tstep);
67 
68  return getRecord(nodeId).data;
69  }
70 };
71 
72 #endif // CACHEDDATASTORAGE_H
CachedDataStorage()
Definition: cacheddatastorage.h:33
std::vector< Record > cachedData
Definition: cacheddatastorage.h:17
utils::StrongType< uint16_t, TStepTag > tstep_t
Definition: modeltypes.h:12
virtual ~CachedDataStorage() noexcept=default
void updateData(types::tstep_t step, Data n)
Definition: cacheddatastorage.h:25
std::shared_ptr< Data > getData(types::NodeId nodeId, types::tstep_t tstep)
Definition: cacheddatastorage.h:57
Definition: idtypes.h:52
int tstep
Definition: main.cpp:205
bool dirty
Definition: cacheddatastorage.h:12
void invalidateAllCache()
Definition: cacheddatastorage.h:36
Definition: cacheddatastorage.h:8
std::shared_ptr< Data > data
Definition: cacheddatastorage.h:14
Definition: cacheddatastorage.h:11
C toIndex() const
Definition: idtypes.h:26
types::tstep_t cachedTstep
Definition: cacheddatastorage.h:13
Record & getRecord(types::NodeId nodeId)
Definition: cacheddatastorage.h:19
virtual void queryAllData(types::tstep_t step)=0
void refreshAllData(types::tstep_t step)
Definition: cacheddatastorage.h:46