use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use zeroize::Zeroizing; /// A string that is wiped from memory when dropped and never printed. /// `Debug` and `Display` give `[redacted]`; read it with [`SecretString::expose`]. #[derive(Clone, Default, PartialEq, Eq)] pub struct SecretString(Zeroizing); impl SecretString { pub fn new(s: String) -> Self { Self(Zeroizing::new(s)) } /// The plaintext. Keep the borrow short and do not copy it into ordinary `String`s. pub fn expose(&self) -> &str { &self.0 } pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl From<&str> for SecretString { fn from(s: &str) -> Self { Self::new(s.to_owned()) } } impl From for SecretString { fn from(s: String) -> Self { Self::new(s) } } impl fmt::Debug for SecretString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("[redacted]") } } impl fmt::Display for SecretString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("[redacted]") } } impl Serialize for SecretString { fn serialize(&self, s: S) -> Result { s.serialize_str(&self.0) } } impl<'de> Deserialize<'de> for SecretString { fn deserialize>(d: D) -> Result { String::deserialize(d).map(Self::new) } }