Skip to content

Commit

Permalink
Create header name/value from String without reallocating
Browse files Browse the repository at this point in the history
  • Loading branch information
jaumelopez authored and Jarema committed Aug 5, 2024
1 parent bfaaf5d commit 966df7c
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion async-nats/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,12 @@ impl From<&str> for HeaderValue {
}
}

impl From<String> for HeaderValue {
fn from(inner: String) -> Self {
Self { inner }
}
}

impl HeaderValue {
pub fn new() -> Self {
HeaderValue::default()
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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());
}
}

0 comments on commit 966df7c

Please sign in to comment.