Skip to main content

braid_types/
timestamp_f64.rs

1// Copyright (C) The Strand-Braid Authors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4/// serde helpers for `FlydraFloatTimestampLocal` to store as f64
5///
6/// attempting to load a NaN will result in an error
7use crate::*;
8
9struct FlydraF64TimestampLocalVisitor;
10
11impl serde::de::Visitor<'_> for FlydraF64TimestampLocalVisitor {
12    type Value = f64;
13
14    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
15        formatter.write_str("a double precision float")
16    }
17
18    fn visit_f64<E>(self, value: f64) -> std::result::Result<Self::Value, E>
19    where
20        E: serde::de::Error,
21    {
22        Ok(value)
23    }
24}
25
26/// serialize to f64 when annotating a field with this for serde auto derive
27pub fn serialize<S, CLK>(
28    orig: &FlydraFloatTimestampLocal<CLK>,
29    serializer: S,
30) -> std::result::Result<S::Ok, S::Error>
31where
32    S: serde::Serializer,
33    CLK: Source,
34{
35    serializer.serialize_f64(orig.as_f64())
36}
37
38/// deserialize from f64 when annotating a field with this for serde auto derive
39pub fn deserialize<'de, D, S>(de: D) -> std::result::Result<FlydraFloatTimestampLocal<S>, D::Error>
40where
41    D: serde::de::Deserializer<'de>,
42    S: Source,
43{
44    let val: f64 = de.deserialize_f64(FlydraF64TimestampLocalVisitor)?;
45    if val.is_nan() {
46        use serde::de::Error;
47        return Err(D::Error::custom(
48            "cannot convert f64 NaN into FlydraFloatTimestampLocal",
49        ));
50    }
51    Ok(FlydraFloatTimestampLocal::from_notnan_f64(
52        val.try_into().unwrap(),
53    ))
54}