From 84b4f95d73da99368f6ab15493d03d392b2f8e5e Mon Sep 17 00:00:00 2001 From: ciffelia <15273128+ciffelia@users.noreply.github.com> Date: Sun, 14 Apr 2024 18:02:25 +0900 Subject: [PATCH] feat: add `Nanoid::as_str` --- src/lib.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0214bd4..f40b3ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -120,8 +120,12 @@ use alphabet::{Alphabet, AlphabetExt, Base64UrlAlphabet}; /// /// ``` /// use nid::Nanoid; +/// +/// // From &str /// let id: Nanoid = Nanoid::try_from_str("K8N4Q7MNmeHJ-OHHoVDcz")?; /// let id: Nanoid = "3hYR3muA_xvjMrrrqFWxF".parse()?; +/// +/// // From String /// let id: Nanoid = "iH26rJ8CpRz-gfIh7TSRu".to_string().try_into()?; /// # Ok::<(), Box>(()) /// ``` @@ -140,12 +144,17 @@ use alphabet::{Alphabet, AlphabetExt, Base64UrlAlphabet}; /// /// # Converting to a string /// -/// You can get the string representation of the Nano ID using the [`AsRef`] or [`Display`](std::fmt::Display) trait. +/// You can get the string representation of the Nano ID using [`Nanoid::as_str`], [`AsRef`] or [`Display`](std::fmt::Display). /// /// ``` /// use nid::Nanoid; /// let id: Nanoid = "Z9ifKfmBL7j69naN7hthu".parse()?; +/// +/// // Convert to &str +/// assert_eq!(id.as_str(), "Z9ifKfmBL7j69naN7hthu"); /// assert_eq!(id.as_ref(), "Z9ifKfmBL7j69naN7hthu"); +/// +/// // Convert to String /// assert_eq!(id.to_string(), "Z9ifKfmBL7j69naN7hthu"); /// # Ok::<(), Box>(()) /// ``` @@ -315,9 +324,18 @@ impl Nanoid { } /// Get the string representation of the [`Nanoid`]. + /// + /// # Examples + /// + /// ``` + /// use nid::Nanoid; + /// let id: Nanoid = "vsB2sq2PfhCdU6WCXk37s".parse()?; + /// assert_eq!(id.as_str(), "vsB2sq2PfhCdU6WCXk37s"); + /// # Ok::<(), Box>(()) + /// ``` #[must_use] #[inline] - const fn as_str(&self) -> &str { + pub const fn as_str(&self) -> &str { // SAFETY: all characters are ASCII. unsafe { std::str::from_utf8_unchecked(&self.inner) } } @@ -656,10 +674,13 @@ mod tests { fn inner(s: &str) { let id: Nanoid = s.parse().unwrap(); + // Test `as_str` method + assert_eq!(id.as_str(), s); + // Test `Display` trait assert_eq!(format!("{}", id), s); - // Test `From` trait + // Test `From` trait assert_eq!(String::from(id), s); // Test `AsRef` trait