Canop / deser-hjson

A Serde 1.0 compatible Rust deserializer for Hjson

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Lifetime issues

VorpalBlade opened this issue · comments

The following example works with serde_json, but not deser_hjson

#[cfg(test)]
mod tests {
    const JSON_TEST: &str = r#"{"a": "b"}"#;

    #[derive(Debug, Deserialize)]
    struct A<'a> {
        a: &'a str,
    }

    #[test]
    fn lifetime_issue() {
        let a: A<'_> = deser_hjson::from_str(JSON_TEST).unwrap();
    }
}

Results in this message:

implementation of `config::_::_serde::Deserialize` is not general enough
`A<'_>` must implement `config::_::_serde::Deserialize<'0>`, for any lifetime `'0`...
...but `A<'_>` actually implements `config::_::_serde::Deserialize<'1>`, for some specific lifetime `'1`

As I said initially, with serde_json this compiles and tests fine, so I expect this to be a bug.

This is by design. deser-hjson favors reliability and the code you wrote is a foot-gun.

Try it, with serde_json, with this string:

 const JSON_TEST: &str = r#"{"a": "quoted \"word\""}"#;

You'd get a runtime error because the code can't be escaped and be borrowed.

Ah okay, so with Cow it will do the right thing (i.e. Borrow where possible)?

Also (as a side thought, but maybe too much of a pain to express with the borrow checker), shouldn't it be possible to take an owned string (or &mut str) and always return references to the input data? Since the unescaped string will always be shorter than the original escaped string, it should be possible to reuse the input buffer.

shouldn't it be possible to take an owned string (or &mut str) and always return references to the input data

Theoretically yes, but why ? Be careful not to overestimate the cost of allocating, it's most often negligible compared to computationally expansive tricks trying to avoid it.

Thanks for answering that, closing the issue as there is no change needed.