1use std::fmt::{Display, Formatter};
3
4const ENV_KEY: &str = "SAFE_LOGGING";
5const ENV_VALUE: &str = "true";
6const SAFE_PRINT: &str = "[REDACTED]";
7
8pub struct Sens<'a,T>(pub &'a T);
28#[cfg(color)]
29impl<T> Display for Sens<'_, T> where T: Display {
30 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31 if self.is_safe() {
32 SAFE_PRINT.black().fmt(f)
33 } else {
34 self.0.fmt(f)
35 }
36 }
37}
38
39#[cfg(not(color))]
40impl<T> Display for Sens<'_, T> where T: Display {
41 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42 if self.is_safe() {
43 SAFE_PRINT.fmt(f)
44 } else {
45 self.0.fmt(f)
46 }
47 }
48}
49
50impl<T> Sens<'_, T> {
51 fn is_safe(&self) -> bool {
52 std::env::var(ENV_KEY).is_ok_and(|t| { t.eq(ENV_VALUE) })
53 }
54}
55
56
57#[cfg(test)]
58mod tests {
59 #[cfg(color)]
60 use colored::Colorize;
61
62 use crate::sensitive::{ENV_KEY, Sens};
63
64 #[test]
65 fn test_sens_mode() {
66 std::env::set_var(ENV_KEY, "");
67 assert_eq!(Sens(&1).to_string(), "1");
68 }
69 #[cfg(color)]
70 #[test]
71 fn test_sens_mode_redacted() {
72 std::env::set_var(ENV_KEY, ENV_VALUE);
73 assert_eq!(Sens(&1).to_string(), SAFE_PRINT.black().to_string());
74 }
75}