Libftpp
A modern C++ library
memento.hpp
Go to the documentation of this file.
1 #ifndef MEMENTO_HPP
2 #define MEMENTO_HPP
3 
4 #include <stddef.h>
5 #include <string.h>
6 
7 #include <stdexcept>
8 #include <vector>
9 
48 class Memento
49 {
50 
51 public:
52  class Snapshot
53  {
54  private:
55  std::vector<unsigned char> _buffer;
56  size_t _cursor = 0;
57 
58  public:
59  template <typename T>
60  Snapshot& operator<<(const T& value)
61  {
62  const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&value);
63  _buffer.insert(_buffer.end(), ptr, ptr + sizeof(T));
64  return *this;
65  }
66 
67  // LECTURE
68  template <typename T>
69  Snapshot operator>>(T& value)
70  {
71  if (sizeof(T) + _cursor > _buffer.size())
72  throw std::out_of_range("Buffer overflow on read");
73 
74  memcpy(&value, _buffer.data() + _cursor, sizeof(T));
75  _cursor += sizeof(T);
76  return *this;
77  }
78 
79  Snapshot& operator<<(const std::string& value);
80  Snapshot& operator>>(std::string& value);
81 
82  void reset();
83  };
84 
85  Snapshot save();
86  void load(const Memento::Snapshot& state);
87 
88 private:
89  virtual void _saveToSnapshot(Memento::Snapshot& snapshot) const = 0;
90  virtual void _loadFromSnapshot(Memento::Snapshot& snapshot) = 0;
91 };
92 
93 #endif
Snapshot operator>>(T &value)
Definition: memento.hpp:69
Snapshot & operator<<(const T &value)
Definition: memento.hpp:60
Memento Design Pattern.
Definition: memento.hpp:49
void load(const Memento::Snapshot &state)
Definition: memento.cpp:15
Snapshot save()
Definition: memento.cpp:3