libdisplaydevice master
C++ library to modify display devices.
persistent_state_utils.h
Go to the documentation of this file.
1
5#pragma once
6
7// system includes
8#include <cstdint>
9#include <iterator>
10#include <optional>
11#include <string_view>
12#include <vector>
13
14// local includes
17
18namespace display_device::detail {
30 template<typename State, typename SerializeFn>
31 [[nodiscard]] bool persistState(
32 SettingsPersistenceInterface &settings_persistence_api,
33 std::optional<State> &cached_state,
34 const std::optional<State> &state,
35 const SerializeFn &serialize_state,
36 const std::string_view serialize_error_message
37 ) {
38 if (cached_state == state) {
39 return true;
40 }
41
42 if (!state) {
43 if (!settings_persistence_api.clear()) {
44 return false;
45 }
46
47 cached_state = std::nullopt;
48 return true;
49 }
50
51 bool success {false};
52 const auto serialized_state {serialize_state(*state, success)};
53 if (!success) {
54 DD_LOG(error) << serialize_error_message << "\n"
55 << serialized_state;
56 return false;
57 }
58
59 if (!settings_persistence_api.store({std::begin(serialized_state), std::end(serialized_state)})) {
60 return false;
61 }
62
63 cached_state = *state;
64 return true;
65 }
66} // namespace display_device::detail
A class for storing and loading settings data from a persistent medium.
Definition settings_persistence_interface.h:16
virtual bool clear()=0
Clear the persistent settings data.
virtual bool store(const std::vector< std::uint8_t > &data)=0
Store the provided data.
Declarations for the logging utility.
#define DD_LOG(level)
Helper MACRO that disables output string computation if log level is not enabled.
Definition logging.h:153
bool persistState(SettingsPersistenceInterface &settings_persistence_api, std::optional< State > &cached_state, const std::optional< State > &state, const SerializeFn &serialize_state, const std::string_view serialize_error_message)
Persist state and update the cached copy after a successful write.
Definition persistent_state_utils.h:31
Declarations for the SettingsPersistenceInterface.