From 99fef4f06bcd32fabf96fcfc5245cf2b4286a602 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sat, 7 Dec 2019 10:22:08 +0600 Subject: [PATCH] add helper conversions --- string/src/lib.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/string/src/lib.rs b/string/src/lib.rs index a8fab284..df7949a9 100644 --- a/string/src/lib.rs +++ b/string/src/lib.rs @@ -90,6 +90,24 @@ impl TryFrom> for ByteString { } } +impl TryFrom for ByteString { + type Error = str::Utf8Error; + + fn try_from(value: Bytes) -> Result { + let _ = str::from_utf8(value.as_ref())?; + Ok(ByteString(value)) + } +} + +impl TryFrom for ByteString { + type Error = str::Utf8Error; + + fn try_from(value: bytes::BytesMut) -> Result { + let _ = str::from_utf8(value.as_ref())?; + Ok(ByteString(value.freeze())) + } +} + macro_rules! array_impls { ($($len:expr)+) => { $( @@ -139,7 +157,17 @@ mod test { } #[test] - fn test_try_from_bytes() { + fn test_try_from_rbytes() { let _ = ByteString::try_from(b"nice bytes").unwrap(); } + + #[test] + fn test_try_from_bytes() { + let _ = ByteString::try_from(Bytes::from_static(b"nice bytes")).unwrap(); + } + + #[test] + fn test_try_from_bytesmut() { + let _ = ByteString::try_from(bytes::BytesMut::from(&b"nice bytes"[..])).unwrap(); + } }