added `From<Cow<'static, str>>` and tests

This commit is contained in:
Bernardo 2018-12-01 16:33:54 +01:00
parent f87ffa6016
commit f17a16a1a0
1 changed files with 29 additions and 0 deletions

View File

@ -210,6 +210,15 @@ impl From<String> for Binary {
} }
} }
impl From<Cow<'static, str>> for Binary {
fn from(s: Cow<'static, str>) -> Binary {
match s {
Cow::Borrowed(s) => Binary::Slice(s.as_ref()),
Cow::Owned(s) => Binary::Bytes(Bytes::from(s)),
}
}
}
impl<'a> From<&'a String> for Binary { impl<'a> From<&'a String> for Binary {
fn from(s: &'a String) -> Binary { fn from(s: &'a String) -> Binary {
Binary::Bytes(Bytes::from(AsRef::<[u8]>::as_ref(&s))) Binary::Bytes(Bytes::from(AsRef::<[u8]>::as_ref(&s)))
@ -297,6 +306,16 @@ mod tests {
assert_eq!(Binary::from("test").as_ref(), b"test"); assert_eq!(Binary::from("test").as_ref(), b"test");
} }
#[test]
fn test_cow_str() {
let cow: Cow<'static, str> = Cow::Borrowed("test");
assert_eq!(Binary::from(cow.clone()).len(), 4);
assert_eq!(Binary::from(cow.clone()).as_ref(), b"test");
let cow: Cow<'static, str> = Cow::Owned("test".to_owned());
assert_eq!(Binary::from(cow.clone()).len(), 4);
assert_eq!(Binary::from(cow.clone()).as_ref(), b"test");
}
#[test] #[test]
fn test_static_bytes() { fn test_static_bytes() {
assert_eq!(Binary::from(b"test".as_ref()).len(), 4); assert_eq!(Binary::from(b"test".as_ref()).len(), 4);
@ -317,6 +336,16 @@ mod tests {
assert_eq!(Binary::from(Bytes::from("test")).as_ref(), b"test"); assert_eq!(Binary::from(Bytes::from("test")).as_ref(), b"test");
} }
#[test]
fn test_cow_bytes() {
let cow: Cow<'static, [u8]> = Cow::Borrowed(b"test");
assert_eq!(Binary::from(cow.clone()).len(), 4);
assert_eq!(Binary::from(cow.clone()).as_ref(), b"test");
let cow: Cow<'static, [u8]> = Cow::Owned(Vec::from("test"));
assert_eq!(Binary::from(cow.clone()).len(), 4);
assert_eq!(Binary::from(cow.clone()).as_ref(), b"test");
}
#[test] #[test]
fn test_arc_string() { fn test_arc_string() {
let b = Arc::new("test".to_owned()); let b = Arc::new("test".to_owned());