BurntSushi / jiff

A date-time library for Rust that encourages you to jump into the pit of success.
The Unlicense
1.77k stars 35 forks source link

fmt: add new `serde` sub-module for integer timestamp integration #119

Closed BurntSushi closed 2 months ago

BurntSushi commented 2 months ago

This adds a new jiff::fmt::serde sub-module that contains helper sub-modules that work with Serde's with attribute. For example:

use jiff::Timestamp;

struct Record {
    #[serde(with = "jiff::fmt::serde::timestamp::second::required")]
    timestamp: Timestamp,
}

let json = r#"{"timestamp":1517644800}"#;
let got: Record = serde_json::from_str(&json)?;
assert_eq!(got.timestamp, Timestamp::from_second(1517644800)?);
assert_eq!(serde_json::to_string(&got)?, json);

This is inspired in part by how Chrono supports a similar use case. It is expected that the behavior should be the same, although this implementation does support the full gamut of integer types (including a 128-bit integer number of nanoseconds). Moreover, the naming is different. Chrono uses a flatter namespace, where as here, we bury everything into sub-modules. The idea is to leave some room for future expansion, although I'm not sure there is much else to add. I also feel like spelling out timestamp instead of ts is a bit clearer.

The module paths are quite long, e.g., jiff::fmt::serde::timestamp::second::required and jiff::fmt::serde::timestamp::second::optional. But they are predictable. And to mitigate users needing to click around through a deep module tree, we include the full tree in the jiff::fmt::serde module documentation.

Ref #100, Closes #101

BurntSushi commented 2 months ago

This PR is on crates.io in jiff 0.1.11.

BurntSushi commented 2 months ago

Docs: https://docs.rs/jiff/0.1.11/jiff/fmt/serde/index.html