blob: 84463b3b0ea0f7f0f5947b5a9867677fbcae12bc [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
Marri Devender Raofa23d702017-09-02 04:43:42 -050037/** @brief Serialize inventory item path
38 * Serializing only path for an empty interface to be consistent
39 * interfaces.
40 * @param[in] path - DBus object path
41 * @param[in] iface - Inventory interface name
42 */
43inline void serialize(const Path& path, const Interface& iface)
44{
45 fs::path p(PIM_PERSIST_PATH);
46 p /= path;
47 fs::create_directories(p);
48 p /= iface;
49 std::ofstream os(p, std::ios::binary);
50}
51
Deepak Kodihallib28990f2017-08-08 07:19:34 -050052/** @brief Deserialize inventory item
53 *
54 * @param[in] path - DBus object path
55 * @param[in] iface - Inventory interface name
56 * @param[in] object - Object to be serialized
57 */
58template <typename T>
59inline void deserialize(
60 const Path& path, const Interface& iface, T& object)
61{
62 fs::path p(PIM_PERSIST_PATH);
63 p /= path;
64 p /= iface;
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050065 try
Deepak Kodihallib28990f2017-08-08 07:19:34 -050066 {
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050067 if (fs::exists(p))
68 {
69 std::ifstream is(p, std::ios::in | std::ios::binary);
70 cereal::JSONInputArchive iarchive(is);
71 iarchive(object);
72 }
73 }
74 catch(cereal::Exception& e)
75 {
76 log<level::ERR>(e.what());
77 fs::remove(p);
Deepak Kodihallib28990f2017-08-08 07:19:34 -050078 }
79}
80
Deepak Kodihalli6620e982017-08-05 13:09:54 -050081} // namespace cereal