From 054ee62e51cdafc209d3d12cdb51bb266f6b6811 Mon Sep 17 00:00:00 2001 From: Taylor Thomas Date: Mon, 13 Nov 2023 16:59:26 -0800 Subject: [PATCH] feat(subject): Adds `into_string` method to `Subject` This should allow for easier conversion back into a `String`, possibly without an allocation if the underlying data is already owned Signed-off-by: Taylor Thomas --- async-nats/src/subject.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/async-nats/src/subject.rs b/async-nats/src/subject.rs index a65d10a3f..c797f8f11 100644 --- a/async-nats/src/subject.rs +++ b/async-nats/src/subject.rs @@ -66,6 +66,25 @@ impl Subject { pub fn as_str(&self) -> &str { self } + + /// Turns the `Subject` into a `String`, consuming it. + /// + /// Note that this function is not implemented as `From for String` as the conversion + /// from the underlying type could involve an allocation. If the `Subject` is owned data, it + /// will not allocate, but if it was constructed from borrowed data, it will. + /// + /// # Examples + /// + /// ``` + /// use async_nats::Subject; + /// + /// let s = Subject::from("foo"); + /// let sub = s.into_string(); + /// ``` + pub fn into_string(self) -> String { + // SAFETY: We have guaranteed that the bytes in the `Subject` struct are valid UTF-8. + unsafe { String::from_utf8_unchecked(self.bytes.into()) } + } } impl<'a> From<&'a str> for Subject {