1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-01-18 14:11:49 +01:00

add serde support to bytestring

This commit is contained in:
Nikolay Kim 2020-03-30 11:54:40 +06:00
parent e775d08d76
commit 30aa0b7bb6
3 changed files with 51 additions and 1 deletions

View File

@ -1,5 +1,9 @@
# Changes
## [0.1.5] - 2020-03-30
* Serde support
## [0.1.4] - 2020-01-14
* Fix `AsRef<str>` impl

View File

@ -1,6 +1,6 @@
[package]
name = "bytestring"
version = "0.1.4"
version = "0.1.5"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
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"

View File

@ -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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
impl<'de> Deserialize<'de> for ByteString {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
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""#);
}
}