Skip to content

Fix roundtrip of flatten externally tagged enum unit variant - #2786

Merged
oli-obk merged 1 commit into
serde-rs:masterfrom
Mingun:serialize-flatten-unit-variant
Dec 27, 2024
Merged

oli-obk merged 1 commit into
serde-rs:masterfrom
Mingun:serialize-flatten-unit-variant

Conversation

@Mingun

@Mingun Mingun commented Aug 3, 2024

Copy link
Copy Markdown
Contributor

Unit variant of externally tagged enum can be deserialized when enum is flatten, but cannot be serialized -- ser test failed:

#![cfg(test)]

use serde::{Deserialize, Serialize}; // 1.0.204;
use serde_json::{from_str, to_string}; // 1.0.121

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Flatten {
    #[serde(flatten)]
    data: Enum,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Enum {
    Unit,
}

const JSON: &str = r#"{"Unit":null}"#;

#[test]
fn de() {
    // ok
    assert_eq!(from_str::<Flatten>(JSON).unwrap(), Flatten { data: Enum::Unit });
}

#[test]
fn ser() {
    // called `Result::unwrap()` on an `Err` value: Error("can only flatten structs and maps (got an enum)", line: 0, column: 0)
    assert_eq!(to_string(&Flatten { data: Enum::Unit }).unwrap(), JSON);
}

This PR fixes this inconsistency

@Mingun
Mingun force-pushed the serialize-flatten-unit-variant branch from 87cf403 to 7fc1636 Compare August 3, 2024 12:04
@Mingun

Mingun commented Aug 4, 2024

Copy link
Copy Markdown
Contributor Author

This PR does not conflicts with #2608, because changed files not moved in #2608, it has pretty obvious test case and reproduction example, so is it seems it shouldn't take too much time for review.

- deserialization of flatten unit variant is possible
- serialization of such variant gives Err("can only flatten structs and maps (got an enum)")
@Mingun
Mingun force-pushed the serialize-flatten-unit-variant branch from 7fc1636 to c17b139 Compare October 25, 2024 15:59
Comment thread serde/src/private/ser.rs Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants