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
use crate::{Decoder, Encoder};
use std::str::FromStr;
/// A string codec that relies on [`FromStr`] and [`ToString`]. It can encode anything that
/// implements [`ToString`] and decode anything that implements [`FromStr`].
///
/// This makes simple key / value easy to use for primitive types. It is also useful for encoding
/// simply data structures without depending on third party crates like serde and serde_json.
///
/// ## Example
/// ```ignore
/// # use leptos::*;
/// # use leptos_use::storage::{StorageType, use_local_storage, use_session_storage, use_storage, UseStorageOptions};
/// # use codee::string::FromToStringCodec;
/// #
/// # #[component]
/// # pub fn Demo() -> impl IntoView {
/// let (get, set, remove) = use_local_storage::<i32, FromToStringCodec>("my-key");
/// # view! { }
/// # }
/// ```
pub struct FromToStringCodec;
impl<T: ToString> Encoder<T> for FromToStringCodec {
type Error = ();
type Encoded = String;
fn encode(val: &T) -> Result<String, Self::Error> {
Ok(val.to_string())
}
}
impl<T: FromStr> Decoder<T> for FromToStringCodec {
type Error = T::Err;
type Encoded = str;
fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
T::from_str(val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_string_codec() {
let s = String::from("party time 🎉");
assert_eq!(FromToStringCodec::encode(&s), Ok(s.clone()));
assert_eq!(FromToStringCodec::decode(&s), Ok(s));
}
}