hifitime icon indicating copy to clipboard operation
hifitime copied to clipboard

Duration and Epoch serde to be human readable

Open ChristopherRabotin opened this issue 3 years ago • 1 comments

At the moment, the serde of a Duration exposes its internal representation, and is not very convenient for a human to read. In Nyx, I had to resort to adding the following methods to serde Epoch and Duration to be human readable:

pub(crate) fn duration_to_str<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(&format!("{duration}"))
}

/// A deserializer from Duration string
pub(crate) fn duration_from_str<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    // implementation of the custom deserialization function
    let s = String::deserialize(deserializer)?;
    Duration::from_str(&s).map_err(serde::de::Error::custom)
}

This should be the default behavior of serde for Duration and Epoch.

This is a breaking change because it will break the current serde users.

ChristopherRabotin avatar Apr 08 '23 17:04 ChristopherRabotin

The serde capability should be kept with a crate feature like serde-3.9 or something making it clear which version introduced the change.

ChristopherRabotin avatar Jan 13 '24 18:01 ChristopherRabotin