1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::{Decoder, Encoder};

/// A codec for encoding JSON messages that relies on [`serde_json`].
///
/// Only available with the **`json_serde` feature** enabled.
///
/// ## Example
///
/// ```ignore
/// # use leptos::*;
/// # use leptos_use::storage::{StorageType, use_local_storage, use_session_storage, use_storage, UseStorageOptions};
/// # use serde::{Deserialize, Serialize};
/// # use codee::string::JsonSerdeCodec;
/// #
/// # #[component]
/// # pub fn Demo() -> impl IntoView {
/// // Primitive types:
/// let (get, set, remove) = use_local_storage::<i32, JsonSerdeCodec>("my-key");
///
/// // Structs:
/// #[derive(Serialize, Deserialize, Clone, Default, PartialEq)]
/// pub struct MyState {
///     pub hello: String,
/// }
/// let (get, set, remove) = use_local_storage::<MyState, JsonSerdeCodec>("my-struct-key");
/// #    view! { }
/// # }
/// ```
pub struct JsonSerdeCodec;

impl<T: serde::Serialize> Encoder<T> for JsonSerdeCodec {
    type Error = serde_json::Error;
    type Encoded = String;

    fn encode(val: &T) -> Result<Self::Encoded, Self::Error> {
        serde_json::to_string(val)
    }
}

impl<T: serde::de::DeserializeOwned> Decoder<T> for JsonSerdeCodec {
    type Error = serde_json::Error;
    type Encoded = str;

    fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
        serde_json::from_str(val)
    }
}

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

    #[test]
    fn test_json_codec() {
        #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        struct Test {
            s: String,
            i: i32,
        }
        let t = Test {
            s: String::from("party time 🎉"),
            i: 42,
        };
        let enc = JsonSerdeCodec::encode(&t).unwrap();
        let dec: Test = JsonSerdeCodec::decode(&enc).unwrap();
        assert_eq!(dec, t);
    }
}