Skip to content

Commit

Permalink
feat(subject): Adds into_string method to Subject
Browse files Browse the repository at this point in the history
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 <taylor@cosmonic.com>
  • Loading branch information
thomastaylor312 committed Nov 14, 2023
1 parent 1dbe9c3 commit 054ee62
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions async-nats/src/subject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Subject> 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 {
Expand Down

0 comments on commit 054ee62

Please sign in to comment.