Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] add support for serde #67

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,10 @@ version_check = "0.9"

[features]
nightly = []
serde = ["dep:serde"]

[dependencies]
serde = { version = "1.0.210", optional = true }

[dev-dependencies]
serde_json = "1.0.128"
122 changes: 122 additions & 0 deletions src/ascii.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use alloc::borrow::Cow;
use alloc::string::String;
#[cfg(__unicase__iter_cmp)]
use core::cmp::Ordering;
Expand Down Expand Up @@ -43,6 +44,32 @@ impl<S> Ascii<S> {
}
}

#[cfg(feature = "serde")]
impl<'de, S> serde::Deserialize<'de> for Ascii<S>
where
S: serde::Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Ascii<S>, D::Error>
where
D: serde::Deserializer<'de>,
{
S::deserialize(deserializer).map(Ascii)
}
}

#[cfg(feature = "serde")]
impl<S> serde::Serialize for Ascii<S>
where
S: serde::Serialize,
{
fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error>
where
T: serde::Serializer,
{
self.0.serialize(serializer)
}
}

impl<S> Deref for Ascii<S> {
type Target = S;
#[inline]
Expand Down Expand Up @@ -120,6 +147,44 @@ impl<S: FromStr> FromStr for Ascii<S> {
}
}

macro_rules! from_impl {
($from:ty => $to:ty; $by:ident) => (
impl<'a> From<$from> for Ascii<$to> {
fn from(s: $from) -> Self {
Ascii(s.$by())
}
}
);
($from:ty => $to:ty) => ( from_impl!($from => $to; into); )
}

impl<S: AsRef<str>> From<S> for Ascii<S> {
#[inline]
fn from(s: S) -> Ascii<S> {
Ascii(s)
}
}

macro_rules! into_impl {
($to:ty) => {
impl<'a> Into<$to> for Ascii<$to> {
fn into(self) -> $to {
self.0.into()
}
}
};
}

from_impl!(&'a str => Cow<'a, str>);
from_impl!(String => Cow<'a, str>);
from_impl!(&'a str => String);
from_impl!(Cow<'a, str> => String; into_owned);
from_impl!(&'a String => &'a str; as_ref);

into_impl!(String);
into_impl!(alloc::borrow::Cow<'a, str>);
into_impl!(&'a str);

impl<S: AsRef<str>> Hash for Ascii<S> {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
Expand Down Expand Up @@ -158,13 +223,70 @@ mod tests {
assert_eq!(a, String::from("fooBar"));
}

#[test]
fn test_into_impls() {
let a = Ascii("foobar");
let b: &str = a.into();
assert_eq!(b, "foobar");

let c = Ascii("FOOBAR".to_string());
let d: String = c.into();
assert_eq!(d, "FOOBAR");

let view: Ascii<&'static str> = Ascii("foobar");
let _: &'static str = view.into();
let _: &str = view.into();

let owned: Ascii<String> = "foobar".into();
let _: String = owned.clone().into();
let _: &str = owned.as_ref();
}

#[cfg(feature = "nightly")]
#[bench]
fn bench_ascii_eq(b: &mut ::test::Bencher) {
b.bytes = b"foobar".len() as u64;
b.iter(|| assert_eq!(Ascii("foobar"), Ascii("FOOBAR")));
}

#[cfg(feature = "serde")]
#[test]
fn test_ascii_deserialize() {
let a = serde_json::from_str::<Ascii<String>>("\"foobar\"").unwrap();
assert_eq!(a, Ascii("foobar"));
let b = serde_json::from_str::<Ascii<String>>("\"FOOBAR\"").unwrap();
assert_eq!(b, Ascii("FOOBAR"));
assert_eq!(b, Ascii("foobar"));
assert_eq!(b, a);
assert_ne!(b, Ascii("baz"));

let c = serde_json::from_str::<Ascii<&str>>("\"baz\"").unwrap();
assert_eq!(c, Ascii("baz"));
assert_eq!(c, Ascii("Baz"));
assert_eq!(c, Ascii("Baz".to_string()));

let mut map = std::collections::HashMap::<Ascii<&str>, i32>::new();
map.insert("abc".into(), 2);
assert_eq!(map.get(&"abc".into()), Some(&2));
assert_eq!(map.get(&"ABC".into()), Some(&2));
assert_eq!(map.len(), 1);
// test if the value is updated correctly using a different cased key
let old = map.insert("ABC".into(), 3);
assert_eq!(old, Some(2));
assert_eq!(map.get(&"abc".into()), Some(&3));
assert_eq!(map.get(&"ABC".into()), Some(&3));
assert_eq!(map.len(), 1);
}

#[cfg(feature = "serde")]
#[test]
fn test_ascii_serialize() {
let a = serde_json::to_string(&Ascii("foobar")).unwrap();
assert_eq!(a, "\"foobar\"");
let b = serde_json::to_string(&Ascii("FOOBAR")).unwrap();
assert_eq!(b, "\"FOOBAR\"");
}

#[cfg(__unicase__iter_cmp)]
#[test]
fn test_case_cmp() {
Expand Down
51 changes: 51 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,32 @@ macro_rules! inner {
}};
}

#[cfg(feature = "serde")]
impl<'de, S> serde::Deserialize<'de> for UniCase<S>
where
S: serde::Deserialize<'de> + AsRef<str>,
{
fn deserialize<D>(deserializer: D) -> Result<UniCase<S>, D::Error>
where
D: serde::Deserializer<'de>,
{
S::deserialize(deserializer).map(UniCase::new)
}
}

#[cfg(feature = "serde")]
impl<S> serde::Serialize for UniCase<S>
where
S: serde::Serialize,
{
fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error>
where
T: serde::Serializer,
{
inner!(self.0).serialize(serializer)
}
}

impl<S: AsRef<str> + Default> Default for UniCase<S> {
fn default() -> Self {
Self::new(Default::default())
Expand Down Expand Up @@ -432,6 +458,31 @@ mod tests {
b.iter(|| assert!(::std::str::from_utf8(SUBJECT).is_ok()));
}

#[cfg(feature = "serde")]
#[test]
fn test_deserialize() {
let a = serde_json::from_str::<UniCase<String>>("\"foobar\"").unwrap();
assert_eq!(a, UniCase::new("foobar"));
let b = serde_json::from_str::<UniCase<String>>("\"FOOBAR\"").unwrap();
assert_eq!(b, UniCase::new("FOOBAR"));
assert_eq!(b, UniCase::new("foobar"));
assert_eq!(b, UniCase::new("foobar".to_string()));
assert_eq!(b, a);
assert_ne!(b, UniCase::new("baz"));
}

#[cfg(feature = "serde")]
#[test]
fn test_serialize() {
let a = UniCase::new("foobar");
let json = serde_json::to_string(&a).unwrap();
assert_eq!(json, "\"foobar\"");

let a = UniCase::new("FOOBAR");
let json = serde_json::to_string(&a).unwrap();
assert_eq!(json, "\"FOOBAR\"");
}

#[cfg(__unicase__iter_cmp)]
#[test]
fn test_case_cmp() {
Expand Down