Skip to main content

nexus_toolkit/
serde_tracked.rs

1use serde::{
2    de::{DeserializeOwned, Deserializer},
3    Deserialize,
4    Serialize,
5    Serializer,
6};
7
8/// A generic wrapper type that transparently serializes and deserializes the inner type `T`.
9/// Deserialization uses `serde_path_to_error` to track errors and report the exact JSON path.
10#[derive(Debug)]
11pub struct WithSerdeErrorPath<T>(pub T);
12
13impl<'de, T> Deserialize<'de> for WithSerdeErrorPath<T>
14where
15    T: DeserializeOwned,
16{
17    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
18    where
19        D: Deserializer<'de>,
20    {
21        // Create a mutable tracker.
22        let mut track = serde_path_to_error::Track::new();
23        // Wrap the deserializer with our tracker.
24        let d = serde_path_to_error::Deserializer::new(deserializer, &mut track);
25        let t = T::deserialize(d)?;
26        Ok(WithSerdeErrorPath(t))
27    }
28}
29
30impl<T> Serialize for WithSerdeErrorPath<T>
31where
32    T: Serialize,
33{
34    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
35    where
36        S: Serializer,
37    {
38        serde_path_to_error::serialize(&self.0, serializer).map_err(|e| e.into_inner())
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use {
45        super::*,
46        serde::{Deserialize, Serialize},
47        std::cell::RefCell,
48    };
49    // A dummy type for testing.
50    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
51    struct Dummy {
52        foo: String,
53        bar: i32,
54    }
55
56    #[test]
57    fn test_deserialize_valid() {
58        let json_str = r#"{"foo": "hello", "bar": 42}"#;
59        // Deserialize using our WithSerdeErrorPath wrapper.
60        let wrapped: WithSerdeErrorPath<Dummy> =
61            serde_json::from_str(json_str).expect("Deserialization should succeed");
62        let dummy: Dummy = wrapped.0;
63        assert_eq!(dummy.foo, "hello");
64        assert_eq!(dummy.bar, 42);
65    }
66
67    #[test]
68    fn test_serialize() {
69        let dummy = Dummy {
70            foo: "world".to_string(),
71            bar: 100,
72        };
73        let wrapped = WithSerdeErrorPath(dummy);
74        let json_str = serde_json::to_string(&wrapped).expect("Serialization should succeed");
75
76        // Parse back into a serde_json::Value to avoid ordering issues.
77        let value: serde_json::Value =
78            serde_json::from_str(&json_str).expect("Parsing serialized JSON should succeed");
79        let expected = serde_json::json!({
80            "foo": "world",
81            "bar": 100
82        });
83        assert_eq!(value, expected);
84    }
85
86    #[derive(Serialize)]
87    struct Outer<'a> {
88        inner: Inner<'a>,
89    }
90
91    #[derive(Serialize)]
92    struct Inner<'a> {
93        refcell: &'a RefCell<String>,
94    }
95
96    #[test]
97    fn test_serialize_failure_with_path() {
98        let refcell = RefCell::new(String::new());
99        let outer = Outer {
100            inner: Inner { refcell: &refcell },
101        };
102
103        // Force an error by borrowing mutably.
104        let _borrow = refcell.borrow_mut();
105
106        let wrapped = WithSerdeErrorPath(outer);
107        let result = serde_json::to_string(&wrapped);
108
109        assert!(result.is_err(), "Expected serialization to fail");
110
111        let error_message = result.err().unwrap().to_string();
112        assert!(
113            error_message.contains("already mutably borrowed"),
114            "Expected error message to mention 'inner.refcell', got: {}",
115            error_message
116        );
117    }
118
119    #[test]
120    fn test_deserialize_error_path() {
121        // Create invalid JSON: missing the "bar" field.
122        let json_str = r#"{"foo": "oops"}"#;
123        let err = serde_json::from_str::<WithSerdeErrorPath<Dummy>>(json_str)
124            .expect_err("Deserialization should fail due to missing field");
125        let error_str = err.to_string();
126
127        // The error message should contain a hint about the missing "bar" field.
128        // Depending on serde_path_to_error's formatting, the error should mention "bar".
129        assert!(
130            error_str.contains("bar"),
131            "Error should indicate that the `bar` field is missing: {}",
132            error_str
133        );
134    }
135}