Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected behaviour with untagged enums and numeric keys #2724

Open
jsouto18 opened this issue Apr 2, 2024 · 0 comments
Open

Unexpected behaviour with untagged enums and numeric keys #2724

jsouto18 opened this issue Apr 2, 2024 · 0 comments

Comments

@jsouto18
Copy link

jsouto18 commented Apr 2, 2024

When using an untagged enum to handle generic Serialization + Deserialization the deserialization will always fail and the cause seems to be the numeric keys of BTreeMap. If using the struct directly everything works as expected.

Can this be related to #1183?
Also not sure if this is a serde or serde_json issue so apologies if this is the wrong repo.

Minimum Reproducible Example:

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "form", content = "data")]
enum StoredSerializationForm<'a, T> {
    Compressed(Vec<u8>),
    #[serde(untagged)]
    #[serde(bound(deserialize = "Ptr<'a,T>: Deserialize<'de>"))]
    Uncompressed(Ptr<'a, T>),
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
enum Ptr<'a, T> {
    Ref(&'a T),
    Owned(T),
}

impl<'de, 'a, T> Deserialize<'de> for Ptr<'a, T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> std::prelude::v1::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Deserialize::deserialize(deserializer).map(Ptr::Owned)
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct TestStruct {
    ctx: BTreeMap<u64, u64>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fails() {
        let mut ctx = BTreeMap::new();
        ctx.insert(1, 42);
        ctx.insert(2, 42);
        let test_struct = TestStruct { ctx };

        let data = StoredSerializationForm::Uncompressed(Ptr::Ref(&test_struct));
        let serialized = serde_json::to_vec(&data).unwrap();

        let _: StoredSerializationForm<TestStruct> = serde_json::from_slice(&serialized).unwrap();
    }

    #[test]
    fn test_works() {
        let mut ctx = BTreeMap::new();
        ctx.insert(1, 42);
        ctx.insert(2, 42);
        let test_struct = TestStruct { ctx };

        let serialized = serde_json::to_vec(&test_struct).unwrap();

        let _: TestStruct = serde_json::from_slice(&serialized).unwrap();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant