Added support for std::chrono::duration; fixes #399

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-04-14 00:15:26 +08:00
committed by GitHub
parent 15742a8739
commit ef0b0b4729
7 changed files with 232 additions and 5 deletions
+1
View File
@@ -488,6 +488,7 @@ reflect-cpp supports the following containers from the C++ standard library:
- `std::array`
- `std::deque`
- `std::chrono::duration`
- `std::filesystem::path`
- `std::forward_list`
- `std::map`
+1 -1
View File
@@ -20,7 +20,7 @@
[rfl::Box and rfl::Ref](rfl_ref.md) - For defining recursive structures.
[rfl::Timestamp](timestamps.md) - For serializing and deserializing timestamps.
[rfl::Timestamp and std::chrono::duration](timestamps.md) - For serializing and deserializing timestamps and durations.
[rfl::Skip](rfl_skip.md) - For skipping fields during serialization and/or deserialization.
+43 -4
View File
@@ -1,4 +1,6 @@
# `rfl::Timestamp`
# `rfl::Timestamp` and `std::chrono::duration`
## `rfl::Timestamp`
`rfl::Timestamp` is a simple wrapper around `std::tm` (https://en.cppreference.com/w/cpp/chrono/c/tm).
@@ -14,7 +16,7 @@ They can be used in your struct like this:
```cpp
struct Person {
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
rfl::Timestamp<"%Y-%m-%d"> birthday;
};
```
@@ -29,8 +31,8 @@ You can access the underlying `std::tm` struct using the `.tm()` method and you
the string representation using the `.str()` method.
```cpp
const std::tm birthday = person1.birthday().tm();
std::cout << person1.birthday().str() << std::endl;
const std::tm birthday = person1.birthday.tm();
std::cout << person1.birthday.str() << std::endl;
```
Note that constructing `rfl::Timestamp` from a string is convenient, but it might result in
@@ -43,3 +45,40 @@ return an `rfl::Result<Timestamp<...>>` or `rfl::Error`.
const rfl::Result<rfl::Timestamp<"%Y-%m-%d">> result = rfl::Timestamp<"%Y-%m-%d">::from_string("1970-01-01");
const rfl::Result<rfl::Timestamp<"%Y-%m-%d">> error = rfl::Timestamp<"%Y-%m-%d">::from_string("not a proper time format");
```
## `std::chrono::duration`
`std::chrono::duration` types are serialized as an object with the count and unit as fields:
```cpp
struct MyStruct {
std::chrono::seconds duration;
};
rfl::json::write(MyStruct{.duration = std::chrono::seconds(10)});
```
This results in the following JSON:
```json
{"duration":{"count":10,"unit":"seconds"}}
```
Units are automatically transformed upon reading. For instance,
both of the JSON snippets below can be read into `MyStruct`, and both
yield equivalent results:
```json
{"duration":{"count":600,"unit":"seconds"}}
```
```json
{"duration":{"count":10,"unit":"minutes"}}
```
The second JSON snippet, encoded in minutes, will be transformed to
seconds.
The following units are supported: `std::chrono::nanoseconds`, `std::chrono::microseconds`,
`std::chrono::milliseconds`, `std::chrono::seconds`,
`std::chrono::minutes`, `std::chrono::hours`, `std::chrono::days`,
`std::chrono::weeks`, `std::chrono::months`, and `std::chrono::years`.
+1
View File
@@ -6,6 +6,7 @@
#include "Parser_box.hpp"
#include "Parser_c_array.hpp"
#include "Parser_default.hpp"
#include "Parser_duration.hpp"
#include "Parser_filepath.hpp"
#include "Parser_map_like.hpp"
#include "Parser_named_tuple.hpp"
+142
View File
@@ -0,0 +1,142 @@
#ifndef RFL_PARSING_PARSER_DURATION_HPP_
#define RFL_PARSING_PARSER_DURATION_HPP_
#include <chrono>
#include <map>
#include <optional>
#include <type_traits>
#include "../Literal.hpp"
#include "../Variant.hpp"
#include "../always_false.hpp"
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
namespace rfl ::parsing {
template <class R, class W, class Rep, class Period, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::chrono::duration<Rep, Period>>
struct Parser<R, W, std::chrono::duration<Rep, Period>, ProcessorsType> {
public:
using InputVarType = typename R::InputVarType;
using ParentType = Parent<W>;
using DurationType = std::chrono::duration<Rep, Period>;
using Unit = Literal<"nanoseconds", "microseconds", "milliseconds", "seconds",
"minutes", "hours", "days", "weeks", "months", "years">;
using SupportedTypes =
Variant<std::chrono::nanoseconds, std::chrono::microseconds,
std::chrono::milliseconds, std::chrono::seconds,
std::chrono::minutes, std::chrono::hours, std::chrono::days,
std::chrono::weeks, std::chrono::months, std::chrono::years>;
struct RType {
int64_t count;
Unit unit;
};
static Result<DurationType> read(const R& _r,
const InputVarType& _var) noexcept {
return Parser<R, W, RType, ProcessorsType>::read(_r, _var)
.and_then(to_duration)
.transform([](auto&& _duration) {
return _duration.visit([](auto&& _d) -> DurationType {
return std::chrono::duration_cast<DurationType>(std::move(_d));
});
});
}
template <class P>
static void write(const W& _w, const DurationType& _d,
const P& _parent) noexcept {
const auto r =
RType{.count = static_cast<int64_t>(_d.count()), .unit = make_unit()};
return Parser<R, W, RType, ProcessorsType>::write(_w, r, _parent);
}
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
return Parser<R, W, RType, ProcessorsType>::to_schema(_definitions);
}
private:
static Result<SupportedTypes> to_duration(const RType& _r) {
switch (_r.unit.value()) {
case Unit::value_of<"nanoseconds">():
return SupportedTypes(std::chrono::nanoseconds(_r.count));
case Unit::value_of<"microseconds">():
return SupportedTypes(std::chrono::microseconds(_r.count));
case Unit::value_of<"milliseconds">():
return SupportedTypes(std::chrono::milliseconds(_r.count));
case Unit::value_of<"seconds">():
return SupportedTypes(std::chrono::seconds(_r.count));
case Unit::value_of<"minutes">():
return SupportedTypes(std::chrono::minutes(_r.count));
case Unit::value_of<"days">():
return SupportedTypes(std::chrono::days(_r.count));
case Unit::value_of<"weeks">():
return SupportedTypes(std::chrono::weeks(_r.count));
case Unit::value_of<"months">():
return SupportedTypes(std::chrono::months(_r.count));
case Unit::value_of<"years">():
return SupportedTypes(std::chrono::years(_r.count));
default:
return error("Unsupported unit.");
}
}
static auto make_unit() noexcept {
if constexpr (std::is_same_v<DurationType, std::chrono::nanoseconds>) {
return Unit::make<"nanoseconds">();
} else if constexpr (std::is_same_v<DurationType,
std::chrono::microseconds>) {
return Unit::make<"microseconds">();
} else if constexpr (std::is_same_v<DurationType,
std::chrono::milliseconds>) {
return Unit::make<"milliseconds">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::seconds>) {
return Unit::make<"seconds">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::minutes>) {
return Unit::make<"minutes">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::hours>) {
return Unit::make<"hours">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::days>) {
return Unit::make<"days">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::weeks>) {
return Unit::make<"weeks">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::months>) {
return Unit::make<"months">();
} else if constexpr (std::is_same_v<DurationType, std::chrono::years>) {
return Unit::make<"years">();
} else {
static_assert(always_false_v<DurationType>, "Unsupported type.");
}
};
};
} // namespace rfl::parsing
#endif
+19
View File
@@ -0,0 +1,19 @@
#include <chrono>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <vector>
#include "write_and_read.hpp"
namespace test_duration {
struct TestStruct {
std::chrono::seconds duration;
};
TEST(json, test_duration) {
const auto test = TestStruct{.duration = std::chrono::seconds(10)};
write_and_read(test, R"({"duration":{"count":10,"unit":"seconds"}})");
}
} // namespace test_duration
+25
View File
@@ -0,0 +1,25 @@
#include <chrono>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <vector>
#include "write_and_read.hpp"
namespace test_duration_conversion {
struct TestStruct1 {
std::chrono::minutes duration;
};
struct TestStruct2 {
std::chrono::seconds duration;
};
TEST(json, test_duration_conversion) {
const auto test1 = TestStruct1{.duration = std::chrono::minutes(10)};
const auto test2 =
rfl::json::read<TestStruct2>(rfl::json::write(test1)).value();
write_and_read(test2, R"({"duration":{"count":600,"unit":"seconds"}})");
}
} // namespace test_duration_conversion