blob: e0fc89a42657be844a3d1ff0cf74854ad7792c7a [file] [log] [blame]
Deepak Kodihalli6620e982017-08-05 13:09:54 -05001#pragma once
2
Patrick Venturea680d1e2018-10-14 13:34:26 -07003#include "config.h"
4
Deepak Kodihalli6620e982017-08-05 13:09:54 -05005#include <cereal/archives/json.hpp>
6#include <experimental/filesystem>
7#include <fstream>
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>
Brad Bishop615b2a82018-03-29 10:32:41 -040059inline void deserialize(const Path& path, const Interface& iface, T& object)
Deepak Kodihallib28990f2017-08-08 07:19:34 -050060{
61 fs::path p(PIM_PERSIST_PATH);
62 p /= path;
63 p /= iface;
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050064 try
Deepak Kodihallib28990f2017-08-08 07:19:34 -050065 {
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050066 if (fs::exists(p))
67 {
68 std::ifstream is(p, std::ios::in | std::ios::binary);
69 cereal::JSONInputArchive iarchive(is);
70 iarchive(object);
71 }
72 }
Brad Bishop615b2a82018-03-29 10:32:41 -040073 catch (cereal::Exception& e)
Jayanth Othayoth86ad3c62017-09-19 22:18:45 -050074 {
75 log<level::ERR>(e.what());
76 fs::remove(p);
Deepak Kodihallib28990f2017-08-08 07:19:34 -050077 }
78}
79
Deepak Kodihalli6620e982017-08-05 13:09:54 -050080} // namespace cereal