From 30aa0b7bb6c45ce5fa4305168ec4f5708fd133fc Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Mon, 30 Mar 2020 11:54:40 +0600 Subject: [PATCH] add serde support to bytestring --- string/CHANGES.md | 4 ++++ string/Cargo.toml | 6 +++++- string/src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/string/CHANGES.md b/string/CHANGES.md index 53ab9c7a..030c3cd5 100644 --- a/string/CHANGES.md +++ b/string/CHANGES.md @@ -1,5 +1,9 @@ # Changes +## [0.1.5] - 2020-03-30 + +* Serde support + ## [0.1.4] - 2020-01-14 * Fix `AsRef` impl diff --git a/string/Cargo.toml b/string/Cargo.toml index 0031ea5b..cafbaf80 100644 --- a/string/Cargo.toml +++ b/string/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bytestring" -version = "0.1.4" +version = "0.1.5" authors = ["Nikolay Kim "] description = "A UTF-8 encoded string with Bytes as a storage" keywords = ["actix"] @@ -16,3 +16,7 @@ path = "src/lib.rs" [dependencies] bytes = "0.5.3" +serde = { version = "1.0", optional = true } + +[dev-dependencies] +serde_json = "1.0" \ No newline at end of file diff --git a/string/src/lib.rs b/string/src/lib.rs index 2b600bde..fbc1bf4c 100644 --- a/string/src/lib.rs +++ b/string/src/lib.rs @@ -159,6 +159,34 @@ impl fmt::Display for ByteString { } } +#[cfg(feature = "serde")] +mod serde { + use serde::de::{Deserialize, Deserializer}; + use serde::ser::{Serialize, Serializer}; + + use super::ByteString; + + impl Serialize for ByteString { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(self.as_ref()) + } + } + + impl<'de> Deserialize<'de> for ByteString { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + String::deserialize(deserializer).map(ByteString::from) + } + } +} + #[cfg(test)] mod test { use super::*; @@ -222,4 +250,18 @@ mod test { fn test_try_from_bytesmut() { let _ = ByteString::try_from(bytes::BytesMut::from(&b"nice bytes"[..])).unwrap(); } + + #[cfg(feature = "serde")] + #[test] + fn test_serialize() { + let s: ByteString = serde_json::from_str(r#""nice bytes""#).unwrap(); + assert_eq!(s, "nice bytes"); + } + + #[cfg(feature = "serde")] + #[test] + fn test_deserialize() { + let s = serde_json::to_string(&ByteString::from_static("nice bytes")).unwrap(); + assert_eq!(s, r#""nice bytes""#); + } }