$darkmode
memory.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2023 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
25 #pragma once
26 
27 #include <memory> // for unique_ptr<>, shared_ptr<>, weak_ptr<>
28 
29 #include <nlohmann/json.hpp> // for adl_serializer<>, json
30 
31 /*
32  * In order to provide serialization for third-party types, we need to either
33  * use their namespace or provide a specialization in that of nlohmann. It is
34  * illegal to define anything in the std namespace, so we are left no choice in
35  * this regard.
36  *
37  * See: https://github.com/nlohmann/json
38  */
39 namespace nlohmann {
40 
41 template <typename T>
42 struct adl_serializer<std::unique_ptr<T>> {
43  static void to_json(json& j, const std::unique_ptr<T>& opt) {
44  if (opt) {
45  j = *opt;
46  } else {
47  j = nullptr;
48  }
49  }
50 };
51 
52 template <typename T>
53 struct adl_serializer<std::shared_ptr<T>> {
54  static void to_json(json& j, const std::shared_ptr<T>& opt) {
55  if (opt) {
56  j = *opt;
57  } else {
58  j = nullptr;
59  }
60  }
61 };
62 
63 template <typename T>
64 struct adl_serializer<std::weak_ptr<T>> {
65  static void to_json(json& j, const std::weak_ptr<T>& opt) {
66  auto ptr = opt.lock();
67  if (ptr) {
68  j = *ptr;
69  } else {
70  j = nullptr;
71  }
72  }
73 };
74 
75 } // namespace nlohmann