diff --git a/CHANGELOG.md b/CHANGELOG.md index 408392d..699c557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +### Added + +- Added `Token::into_encoded`, which consumes the `Token` and returns its + encoded string representation as a `Cow<'a, str>` without allocating. + Resolves [#115](https://github.com/chanced/jsonptr/issues/115). + ### Changed - Resolved all `clippy` (`clippy::all` + `clippy::pedantic`) and `rustc` lint diff --git a/src/token.rs b/src/token.rs index 2a4f801..5d68f34 100644 --- a/src/token.rs +++ b/src/token.rs @@ -197,6 +197,22 @@ impl<'a> Token<'a> { &self.inner } + /// Converts this `Token` into the encoded string representation, as a + /// `Cow<'a, str>`. + /// + /// This is like [`Self::encoded`], except it consumes the `Token` and, + /// since the token is already encoded internally, does not allocate. + /// + /// # Examples + /// + /// ``` + /// # use jsonptr::Token; + /// assert_eq!(Token::new("~bar").into_encoded(), "~0bar"); + /// ``` + pub fn into_encoded(self) -> Cow<'a, str> { + self.inner + } + /// Returns the decoded string representation of the `Token`. /// /// # Examples @@ -589,6 +605,15 @@ mod tests { ); } + #[test] + fn into_encoded() { + let token = Token::from_encoded("foo~0").unwrap(); + assert_eq!(token.into_encoded(), "foo~0"); + + let token = Token::new("~bar"); + assert_eq!(token.into_encoded(), "~0bar"); + } + #[test] fn into_owned() { let token = Token::from_encoded("foo~0").unwrap().into_owned();