1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-08-02 02:35:04 +00:00

impl From<Cow<'static, [u8]>> for Binary (#611)

impl `From` for `Cow<'static, [u8]>`  and `From<Cow<'static, str>>` for `Binary`
This commit is contained in:
vemoo 2018-12-02 06:32:55 +01:00 committed by Douman
parent c386353337
commit 68c5d6e6d6

View file

@ -1,5 +1,6 @@
use bytes::{Bytes, BytesMut};
use futures::Stream;
use std::borrow::Cow;
use std::sync::Arc;
use std::{fmt, mem};
@ -194,12 +195,30 @@ impl From<Vec<u8>> for Binary {
}
}
impl From<Cow<'static, [u8]>> for Binary {
fn from(b: Cow<'static, [u8]>) -> Binary {
match b {
Cow::Borrowed(s) => Binary::Slice(s),
Cow::Owned(vec) => Binary::Bytes(Bytes::from(vec)),
}
}
}
impl From<String> for Binary {
fn from(s: String) -> Binary {
Binary::Bytes(Bytes::from(s))
}
}
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 {
fn from(s: &'a String) -> Binary {
Binary::Bytes(Bytes::from(AsRef::<[u8]>::as_ref(&s)))
@ -287,6 +306,16 @@ mod tests {
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]
fn test_static_bytes() {
assert_eq!(Binary::from(b"test".as_ref()).len(), 4);
@ -307,6 +336,16 @@ mod tests {
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]
fn test_arc_string() {
let b = Arc::new("test".to_owned());