blob: 7d0b10ef1b7705cb6529680511ebc9c4f9664b03 [file] [log] [blame]
Deepak Kodihalli6620e982017-08-05 13:09:54 -05001#pragma once
2
3#include <cereal/archives/json.hpp>
4#include <experimental/filesystem>
5#include <fstream>
6#include "config.h"
7
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -05008#include <phosphor-logging/log.hpp>
9
Deepak Kodihalli6620e982017-08-05 13:09:54 -050010namespace cereal
11{
12
13namespace fs = std::experimental::filesystem;
14
15using Path = std::string;
16using Interface = std::string;
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050017using namespace phosphor::logging;
Deepak Kodihalli6620e982017-08-05 13:09:54 -050018
19/** @brief Serialize inventory item
20 *
21 * @param[in] path - DBus object path
22 * @param[in] iface - Inventory interface name
23 * @param[in] object - Object to be serialized
24 */
25template <typename T>
26inline void serialize(const Path& path, const Interface& iface, const T& object)
27{
28 fs::path p(PIM_PERSIST_PATH);
29 p /= path;
30 fs::create_directories(p);
31 p /= iface;
32 std::ofstream os(p, std::ios::binary);
33 cereal::JSONOutputArchive oarchive(os);
34 oarchive(object);
35}
36
Deepak Kodihallib28990f2017-08-08 07:19:34 -050037/** @brief Deserialize inventory item
38 *
39 * @param[in] path - DBus object path
40 * @param[in] iface - Inventory interface name
41 * @param[in] object - Object to be serialized
42 */
43template <typename T>
44inline void deserialize(
45 const Path& path, const Interface& iface, T& object)
46{
47 fs::path p(PIM_PERSIST_PATH);
48 p /= path;
49 p /= iface;
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050050 try
Deepak Kodihallib28990f2017-08-08 07:19:34 -050051 {
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050052 if (fs::exists(p))
53 {
54 std::ifstream is(p, std::ios::in | std::ios::binary);
55 cereal::JSONInputArchive iarchive(is);
56 iarchive(object);
57 }
58 }
59 catch(cereal::Exception& e)
60 {
61 log<level::ERR>(e.what());
62 fs::remove(p);
Deepak Kodihallib28990f2017-08-08 07:19:34 -050063 }
64}
65
Deepak Kodihalli6620e982017-08-05 13:09:54 -050066} // namespace cereal