libkazv
jsonwrap.hpp
Go to the documentation of this file.
1 /*
2  * This file is part of libkazv.
3  * SPDX-FileCopyrightText: 2020-2021 Tusooa Zhu <tusooa@kazv.moe>
4  * SPDX-License-Identifier: AGPL-3.0-or-later
5  */
6 
7 
8 #pragma once
9 #include "libkazv-config.hpp"
10 
11 #include <boost/serialization/version.hpp>
12 #include <boost/serialization/string.hpp>
13 #include <boost/serialization/split_member.hpp>
14 
15 #include <nlohmann/json.hpp>
16 #include <immer/box.hpp>
17 
18 namespace Kazv
19 {
21 
22  class JsonWrap
23  {
24  // Cannot directly use box here, because it causes the resulting json
25  // to be wrapped into an array.
26  // https://github.com/arximboldi/immer/issues/155
27  struct Private
28  {
29  json j;
30  };
31 
32  immer::box<Private> m_d;
33  public:
34  JsonWrap() : m_d(Private{json()}) {}
35  JsonWrap(json&& j) : m_d(Private{std::move(j)}) {}
36  JsonWrap(const json& j) : m_d(Private{j}) {}
37 
38  const json &get() const { return m_d.get().j; }
39  operator json() const { return m_d.get().j; }
40 
41  template <class Archive>
42  void save(Archive &ar, std::uint32_t const /*version*/) const {
43  ar << get().dump();
44  }
45 
46  template <class Archive>
47  void load(Archive &ar, std::uint32_t const /*version*/) {
48  std::string j;
49  ar >> j;
50  m_d = immer::box<Private>(Private{json::parse(std::move(j))});
51  }
52  BOOST_SERIALIZATION_SPLIT_MEMBER()
53  };
54 }
55 
56 BOOST_CLASS_VERSION(Kazv::JsonWrap, 0)
57 
58 namespace nlohmann
59 {
60  template <>
61  struct adl_serializer<Kazv::JsonWrap> {
62  static void to_json(json& j, Kazv::JsonWrap w) {
63  j = w.get();
64  }
65 
66  static void from_json(const json& j, Kazv::JsonWrap &w) {
67  w = Kazv::JsonWrap(j);
68  }
69  };
70 
71 }
72 
73 namespace Kazv
74 {
75  inline bool operator==(JsonWrap a, JsonWrap b)
76  {
77  return a.get() == b.get();
78  }
79 }
nlohmann
Definition: location.hpp:26
Kazv::Private
@ Private
Definition: client-model.hpp:41
Kazv::operator==
bool operator==(BaseJob a, BaseJob b)
Definition: basejob.cpp:280
Kazv
Definition: location.hpp:10
Kazv::JsonWrap::load
void load(Archive &ar, std::uint32_t const)
Definition: jsonwrap.hpp:47
Kazv::JsonWrap::JsonWrap
JsonWrap(const json &j)
Definition: jsonwrap.hpp:36
Kazv::JsonWrap::save
void save(Archive &ar, std::uint32_t const) const
Definition: jsonwrap.hpp:42
Kazv::json
nlohmann::json json
Definition: jsonwrap.hpp:20
nlohmann::adl_serializer< Kazv::JsonWrap >::from_json
static void from_json(const json &j, Kazv::JsonWrap &w)
Definition: jsonwrap.hpp:66
Kazv::JsonWrap::JsonWrap
JsonWrap(json &&j)
Definition: jsonwrap.hpp:35
Kazv::JsonWrap
Definition: jsonwrap.hpp:22
nlohmann::adl_serializer< Kazv::JsonWrap >::to_json
static void to_json(json &j, Kazv::JsonWrap w)
Definition: jsonwrap.hpp:62
Kazv::JsonWrap::get
const json & get() const
Definition: jsonwrap.hpp:38
Kazv::JsonWrap::JsonWrap
JsonWrap()
Definition: jsonwrap.hpp:34
libkazv-config.hpp