#serialize_with help

2 messages · Page 1 of 1 (latest)

serene junco
#

trying to truncate a decimal at 3 places and then parse it as an a f64, but i run into the following issue:

with code:

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Dummy(#[serde(serialize_with = "trunc")] f64);

#[test]
fn test() {
    use serde_test::{assert_tokens, Token};

    let dummy = Dummy(2.819281);

    assert_tokens(&dummy, &[Token::NewtypeStruct { name: "Dummy" }, Token::F64(2.819)]);
}

fn trunc<S: Serializer>(x: &f64, s: S) -> Result<S::Ok, S::Error> {
    let y = format!("{x:.3}").parse::<f64>().unwrap();
    eprintln!("{y}");
    s.serialize_f64(y)
}

i get error:

running 1 test
2.819
thread 'math::gex::test' panicked at 'assertion failed: `(left == right)`
  left: `Dummy(2.819)`,
 right: `Dummy(2.819281)`', 

clearly, the custom serializer is getting called and working (due to the eprintln), but somehow the f64 is still getting serialized as the whole thing?

charred light
#

I think you're looking for assert_ser_tokens instead of assert_tokens which runs both ways. You're only changing the serialization, not deserialization.