codee/string/
from_to_string.rs

1use crate::{Decoder, Encoder};
2use std::str::FromStr;
3
4/// A string codec that relies on [`FromStr`] and [`ToString`]. It can encode anything that
5/// implements [`ToString`] and decode anything that implements [`FromStr`].
6///
7/// This makes simple key / value easy to use for primitive types. It is also useful for encoding
8/// simply data structures without depending on third party crates like serde and serde_json.
9///
10/// ## Example
11/// ```ignore
12/// # use leptos::*;
13/// # use leptos_use::storage::{StorageType, use_local_storage, use_session_storage, use_storage, UseStorageOptions};
14/// # use codee::string::FromToStringCodec;
15/// #
16/// # #[component]
17/// # pub fn Demo() -> impl IntoView {
18/// let (get, set, remove) = use_local_storage::<i32, FromToStringCodec>("my-key");
19/// #    view! { }
20/// # }
21/// ```
22pub struct FromToStringCodec;
23
24impl<T: ToString> Encoder<T> for FromToStringCodec {
25    type Error = ();
26    type Encoded = String;
27
28    fn encode(val: &T) -> Result<String, Self::Error> {
29        Ok(val.to_string())
30    }
31}
32
33impl<T: FromStr> Decoder<T> for FromToStringCodec {
34    type Error = T::Err;
35    type Encoded = str;
36
37    fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
38        T::from_str(val)
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn test_string_codec() {
48        let s = String::from("party time 🎉");
49        assert_eq!(FromToStringCodec::encode(&s), Ok(s.clone()));
50        assert_eq!(FromToStringCodec::decode(&s), Ok(s));
51    }
52}