core-adapters 0.1.2
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
time_json.hpp File Reference

nlohmann/json hooks for snicholls::utc<D>: a canonical RFC 3339 string. More...

#include <string>
#include <system_error>
#include <snicholls/core_adapters/nlohmann/json.hpp>
#include <snicholls/core/time/rfc3339.hpp>
#include <snicholls/core/time/utc.hpp>

Go to the source code of this file.

Functions

template<utc_duration D>
void snicholls::to_json (nlohmann::json &j, const utc< D > &t)
 Writes t as its canonical RFC 3339 string.
 
template<utc_duration D>
void snicholls::from_json (const nlohmann::json &j, utc< D > &t)
 Reads an RFC 3339 string (strict: snicholls::parse_utc<D> with default options).
 

Detailed Description

nlohmann/json hooks for snicholls::utc<D>: a canonical RFC 3339 string.

Overview
nlohmann::json j = t; writes "2024-04-30T14:23:05.123456789Z": snicholls::to_text(t), with exactly the resolution's fraction digits (9 for utc<>, 3 for utc_ms, none for utc_s). j.get<snicholls::utc<D>>() reads it back with snicholls::parse_utc<D> and default (strict) options: an offset is required and applied, digits finer than D are an error, a leap second is an error. A JSON number is not accepted, since its unit would be a guess; parse Unix numbers explicitly with snicholls::parse_unix<Unit, D>.
const auto t = snicholls::utc_ms::from_unix_millis(1714486985123);
const nlohmann::json j = {{"as_of", t}}; // {"as_of":"2024-04-30T14:23:05.123Z"}
std::printf("%s\n", j.dump().c_str());
const auto back = j.at("as_of").get<snicholls::utc_ms>(); // strict RFC 3339, offset applied
const auto ny = nlohmann::json("2024-04-30T10:23:05.123-04:00").get<snicholls::utc_ms>();
Relationships
Guarantees and contracts
  • Round trip: j.get<utc<D>>() == t for every t in years 0000..9999, and the text is identical on every platform (see "Portability" in time/utc.hpp).
  • to_json throws only for a year outside 0000..9999 (possible for utc_us and coarser), and std::bad_alloc.
Errors
snicholls::json_error: not a string; not RFC 3339; out of range or too precise for D; a year outside 0000..9999 on output.
Performance
Not benchmarked: to_text / parse_utc (see time/rfc3339.hpp) plus one std::string.
Tests and demos
  • Tests: tests/nlohmann/time_json_test.cpp.
  • Demo: demos/nlohmann/time_json_demo.cpp.
Dependencies
CMake target snicholls::core_json.
Known issues and gotchas
  • None known.
Status
Experimental, pre-1.0.

Definition in file time_json.hpp.