codee/string/
json_serde.rs

1use crate::{Decoder, Encoder};
2use serde::{Deserialize, Serialize};
3
4/// A codec for encoding JSON messages that relies on [`serde_json`].
5///
6/// Only available with the **`json_serde` feature** enabled.
7///
8/// ## Example
9///
10/// ```ignore
11/// # use leptos::*;
12/// # use leptos_use::storage::{StorageType, use_local_storage, use_session_storage, use_storage, UseStorageOptions};
13/// # use serde::{Deserialize, Serialize};
14/// # use codee::string::JsonSerdeCodec;
15/// #
16/// # #[component]
17/// # pub fn Demo() -> impl IntoView {
18/// // Primitive types:
19/// let (get, set, remove) = use_local_storage::<i32, JsonSerdeCodec>("my-key");
20///
21/// // Structs:
22/// #[derive(Serialize, Deserialize, Clone, Default, PartialEq)]
23/// pub struct MyState {
24///     pub hello: String,
25/// }
26/// let (get, set, remove) = use_local_storage::<MyState, JsonSerdeCodec>("my-struct-key");
27/// #    view! { }
28/// # }
29/// ```
30pub struct JsonSerdeCodec;
31
32impl<T: Serialize> Encoder<T> for JsonSerdeCodec {
33    type Error = serde_json::Error;
34    type Encoded = String;
35
36    fn encode(val: &T) -> Result<Self::Encoded, Self::Error> {
37        serde_json::to_string(val)
38    }
39}
40
41impl<T> Decoder<T> for JsonSerdeCodec
42where
43    for<'de> T: Deserialize<'de>,
44{
45    type Error = serde_json::Error;
46    type Encoded = str;
47
48    fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
49        serde_json::from_str(val)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_json_codec() {
59        #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
60        struct Test {
61            s: String,
62            i: i32,
63        }
64        let t = Test {
65            s: String::from("party time 🎉"),
66            i: 42,
67        };
68        let enc = JsonSerdeCodec::encode(&t).unwrap();
69        let dec: Test = JsonSerdeCodec::decode(&enc).unwrap();
70        assert_eq!(dec, t);
71    }
72}