From 5fefad8dd2081919f2484f5bc1561f86179b5b6b Mon Sep 17 00:00:00 2001 From: Artur Jurat Date: Fri, 11 Oct 2024 18:30:47 +0200 Subject: [PATCH] secrecy: Add FromStr impl for SecretString (#1240) --- secrecy/src/lib.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/secrecy/src/lib.rs b/secrecy/src/lib.rs index ecbe2297..d2390507 100644 --- a/secrecy/src/lib.rs +++ b/secrecy/src/lib.rs @@ -37,11 +37,12 @@ extern crate alloc; use alloc::{boxed::Box, string::String, vec::Vec}; +use core::convert::Infallible; +use core::str::FromStr; use core::{ any, fmt::{self, Debug}, }; - use zeroize::{Zeroize, ZeroizeOnDrop}; #[cfg(feature = "serde")] @@ -225,6 +226,14 @@ impl From<&str> for SecretString { } } +impl FromStr for SecretString { + type Err = Infallible; + + fn from_str(s: &str) -> Result { + Ok(Self::from(s)) + } +} + impl Clone for SecretString { fn clone(&self) -> Self { SecretBox { @@ -323,3 +332,15 @@ where self.expose_secret().serialize(serializer) } } + +#[cfg(test)] +mod tests { + use crate::{ExposeSecret, SecretString}; + use core::str::FromStr; + + #[test] + fn test_secret_string_from_str() { + let secret = SecretString::from_str("test").unwrap(); + assert_eq!(secret.expose_secret(), "test"); + } +}