$darkmode
chrono.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  */
22 #pragma once
23 
24 #include <chrono>
25 #include <string>
26 
27 #include <nlohmann/json.hpp>
28 
29 namespace fable {
30 
31 std::chrono::nanoseconds parse_duration_to_nanoseconds(const std::string& s);
32 
55 template <typename Duration>
56 Duration parse_duration(const std::string& s) {
57  return std::chrono::duration_cast<Duration>(parse_duration_to_nanoseconds(s));
58 }
59 
60 template <typename Duration>
61 std::string to_string(const Duration& d) {
62  return to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(d));
63 }
64 
65 template <>
66 std::string to_string(const std::chrono::nanoseconds& d);
67 
68 } // namespace fable
69 
70 namespace nlohmann {
71 
72 template <typename Rep, typename Period>
73 struct adl_serializer<std::chrono::duration<Rep, Period>> {
74  using Duration = std::chrono::duration<Rep, Period>;
75 
76  static void to_json(json& j, const Duration& d) {
77  j = ::fable::to_string(d);
78  }
79 
80  static void from_json(const json& j, Duration& d) {
81  std::string s = j.get<std::string>();
82  d = ::fable::parse_duration<Duration>(s);
83  }
84 };
85 
86 } // namespace nlohmann
Duration parse_duration(const std::string &s)
Definition: chrono.hpp:56