use std::fmt;
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(String);
impl Secret {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn expose_secret(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<redacted>")
}
}
impl From<String> for Secret {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for Secret {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_output_is_redacted() {
let secret = Secret::new("super-sekret-value");
let debug = format!("{secret:?}");
assert_eq!(debug, "<redacted>");
assert!(!debug.contains("super-sekret-value"));
}
#[test]
fn debug_redacts_inside_derived_container() {
#[derive(Debug)]
struct Holder {
#[allow(dead_code)]
token: Secret,
}
let holder = Holder {
token: "super-sekret-value".into(),
};
let debug = format!("{holder:?}");
assert!(debug.contains("token: <redacted>"));
assert!(!debug.contains("super-sekret-value"));
}
#[test]
fn expose_secret_returns_the_wrapped_value() {
assert_eq!(Secret::new("v").expose_secret(), "v");
}
#[test]
fn from_string_and_str_compare_equal() {
let a: Secret = "tok".into();
let b: Secret = String::from("tok").into();
assert_eq!(a, b);
assert_eq!(a.clone(), a);
}
}