From 966df7c09be088db02a23ad7e570022d6e1becf6 Mon Sep 17 00:00:00 2001 From: jaumelopez Date: Sat, 3 Aug 2024 15:46:17 +0200 Subject: [PATCH] Create header name/value from String without reallocating --- async-nats/src/header.rs | 48 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/async-nats/src/header.rs b/async-nats/src/header.rs index f4d3f9a8f..2dec615ed 100644 --- a/async-nats/src/header.rs +++ b/async-nats/src/header.rs @@ -346,6 +346,12 @@ impl From<&str> for HeaderValue { } } +impl From for HeaderValue { + fn from(inner: String) -> Self { + Self { inner } + } +} + impl HeaderValue { pub fn new() -> Self { HeaderValue::default() @@ -382,6 +388,14 @@ impl IntoHeaderName for &str { } } +impl IntoHeaderName for String { + fn into_header_name(self) -> HeaderName { + HeaderName { + inner: HeaderRepr::Custom(self.into()), + } + } +} + impl IntoHeaderName for HeaderName { fn into_header_name(self) -> HeaderName { self @@ -400,6 +414,12 @@ impl IntoHeaderValue for &str { } } +impl IntoHeaderValue for String { + fn into_header_value(self) -> HeaderValue { + HeaderValue { inner: self } + } +} + impl IntoHeaderValue for HeaderValue { fn into_header_value(self) -> HeaderValue { self @@ -650,7 +670,7 @@ impl std::error::Error for ParseHeaderNameError {} #[cfg(test)] mod tests { - use super::{HeaderMap, HeaderName, HeaderValue}; + use super::{HeaderMap, HeaderName, HeaderValue, IntoHeaderName, IntoHeaderValue}; use std::str::{from_utf8, FromStr}; #[test] @@ -814,4 +834,30 @@ mod tests { header ); } + + #[test] + fn header_name_from_string() { + let string = "NATS-Stream".to_string(); + let name = string.into_header_name(); + + assert_eq!("NATS-Stream", name.as_str()); + } + + #[test] + fn header_value_from_string_with_trait() { + let string = "some value".to_string(); + + let value = string.into_header_value(); + + assert_eq!("some value", value.as_str()); + } + + #[test] + fn header_value_from_string() { + let string = "some value".to_string(); + + let value: HeaderValue = string.into(); + + assert_eq!("some value", value.as_str()); + } }