leptos-use/src/storage/codec_string.rs

45 lines
1.2 KiB
Rust
Raw Normal View History

use super::Codec;
2023-10-28 12:19:33 +01:00
use std::str::FromStr;
2023-10-29 11:41:59 +00:00
/// A codec for strings that relies on [`FromStr`] and [`ToString`] to parse.
///
/// This makes simple key / value easy to use for primitive types. It is also useful for encoding simple data structures without depending on serde.
///
/// ## Example
/// ```
/// # use leptos::*;
2023-11-12 22:50:59 +00:00
/// # use leptos_use::storage::{StorageType, use_local_storage, use_session_storage, use_storage, UseStorageOptions, StringCodec};
2023-10-29 11:41:59 +00:00
/// #
/// # pub fn Demo() -> impl IntoView {
/// let (get, set, remove) = use_local_storage::<i32, StringCodec>("my-key");
/// # view! { }
/// # }
/// ```
2023-10-28 12:19:33 +01:00
#[derive(Clone, Default, PartialEq)]
2023-11-13 00:20:58 +00:00
pub struct StringCodec;
2023-10-28 12:19:33 +01:00
impl<T: FromStr + ToString> Codec<T> for StringCodec {
type Error = T::Err;
fn encode(&self, val: &T) -> Result<String, Self::Error> {
Ok(val.to_string())
}
fn decode(&self, str: String) -> Result<T, Self::Error> {
T::from_str(&str)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_string_codec() {
let s = String::from("party time 🎉");
2023-11-13 00:20:58 +00:00
let codec = StringCodec;
2023-10-28 12:19:33 +01:00
assert_eq!(codec.encode(&s), Ok(s.clone()));
assert_eq!(codec.decode(s.clone()), Ok(s));
}
}