GCC Code Coverage Report


Directory: ./
File: Utils/include/Utils/Json.hpp
Date: 2022-10-15 05:10:18
Exec Total Coverage
Lines: 18 18 100.0%
Functions: 5 5 100.0%
Branches: 7 10 70.0%
Decisions: 4 4 100.0%

Line Branch Decision Exec Source
1 // Copyright 2019-2022 Cambridge Quantum Computing
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #pragma once
16
17 #include <complex>
18 #include <exception>
19 #include <optional>
20
21 // Workaround for Windows madness.
22 // See: https://github.com/nlohmann/json/issues/1408
23 #undef snprintf
24 #include <nlohmann/json.hpp>
25
26 // macro for type T serialization and deserialization declarations
27 #define JSON_DECL(T) \
28 void to_json(nlohmann::json& j, const T& type); \
29 void from_json(const nlohmann::json& j, T& type);
30
31 namespace tket {
32
33 class JsonError : public std::logic_error {
34 public:
35 1 explicit JsonError(const std::string& message) : std::logic_error(message) {}
36 };
37
38 } // namespace tket
39
40 // no default serialization for complex types
41 namespace std {
42
43 template <class T>
44 100 void to_json(nlohmann::json& j, const std::complex<T>& p) {
45
3/6
✓ Branch 5 taken 100 times.
✗ Branch 6 not taken.
✓ Branch 9 taken 200 times.
✓ Branch 10 taken 100 times.
✗ Branch 12 not taken.
✗ Branch 13 not taken.
300 j = nlohmann::json{p.real(), p.imag()};
46 100 }
47
48 template <class T>
49 100 void from_json(const nlohmann::json& j, std::complex<T>& p) {
50 100 p.real(j.at(0));
51 100 p.imag(j.at(1));
52 100 }
53
54 // no default serialization for std::optional types
55 template <class T>
56 4 void to_json(nlohmann::json& j, const std::optional<T>& v) {
57
2/2
✓ Branch 1 taken 2 times.
✓ Branch 2 taken 2 times.
2/2
✓ Decision 'true' taken 2 times.
✓ Decision 'false' taken 2 times.
4 if (v.has_value())
58 2 j = *v;
59 else
60 2 j = nullptr;
61 4 }
62
63 template <class T>
64 2 void from_json(const nlohmann::json& j, std::optional<T>& v) {
65
2/2
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 1 times.
2/2
✓ Decision 'true' taken 1 times.
✓ Decision 'false' taken 1 times.
2 if (j.is_null())
66 1 v = std::nullopt;
67 else
68 1 v = j.get<T>();
69 2 }
70
71 } // namespace std
72