Skip to main content

debug_issue_2020/
debug_issue_2020.rs

1//! Debug issue 2020: Arc deserialization bug
2use std::{collections::HashMap, sync::Arc};
3
4use facet::Facet;
5
6#[derive(Clone, Debug, Facet)]
7pub struct Inner {
8    pub x: Vec<f64>,
9    pub y: Vec<f64>,
10}
11
12#[derive(Clone, Debug, Facet)]
13#[facet(tag = "kind")]
14#[repr(C)]
15pub enum Tagged {
16    TypeA { value: f64, data: Arc<Inner> },
17}
18
19#[derive(Clone, Debug, Facet)]
20pub struct Item {
21    #[facet(flatten)]
22    pub tagged: Tagged,
23}
24
25#[derive(Clone, Debug, Facet)]
26pub struct Container {
27    pub items: Option<HashMap<String, Item>>,
28}
29
30#[derive(Clone, Debug, Facet)]
31pub struct Root {
32    pub container: Container,
33}
34
35fn main() {
36    let json = r#"{
37    "container": {
38      "items": {
39        "a": {
40          "kind": "TypeA",
41          "value": 42.0,
42          "data": {
43            "x": [1.0, 2.0],
44            "y": [100.0, 200.0]
45          }
46        }
47      }
48    }
49  }"#;
50
51    println!("Attempting to deserialize...");
52    match facet_json::from_str::<Root>(json) {
53        Ok(root) => {
54            if let Some(items) = &root.container.items
55                && let Some(item) = items.get("a")
56            {
57                match &item.tagged {
58                    Tagged::TypeA { value, data } => {
59                        println!("value: {}", value);
60                        println!("data.y[0]: {}", data.y.first().unwrap_or(&0.0));
61
62                        if data.y.is_empty() || *data.y.first().unwrap_or(&0.0) == 0.0 {
63                            println!("BUG: Arc<Inner> not deserialized correctly!");
64                        } else {
65                            println!("SUCCESS: Arc<Inner> deserialized correctly!");
66                        }
67                    }
68                }
69            }
70        }
71        Err(e) => {
72            println!("Failed: {:?}", e);
73        }
74    }
75
76    // This produces access violation (running on windows)
77    println!("Attempting second deserialization...");
78    match facet_json::from_str::<Root>(json) {
79        Ok(_) => println!("Second deserialization succeeded"),
80        Err(e) => println!("Second deserialization failed: {:?}", e),
81    }
82}