dotenv_typed/secret/impl.rs
1use super::*;
2
3/// Constructors and explicit accessors for [`SecretString`].
4impl SecretString {
5 /// Wraps a secret string.
6 ///
7 /// # Arguments
8 ///
9 /// - `S` - Sensitive string value.
10 ///
11 /// # Returns
12 ///
13 /// - `Self` - Redacting secret wrapper.
14 pub fn new<S>(value: S) -> Self
15 where
16 S: Into<String>,
17 {
18 Self {
19 inner: value.into(),
20 }
21 }
22
23 /// Explicitly exposes the underlying secret string slice.
24 ///
25 /// # Returns
26 ///
27 /// - `&str` - Secret string value.
28 #[inline(always)]
29 pub fn expose(&self) -> &str {
30 let Self { inner } = self;
31 inner.as_str()
32 }
33
34 /// Returns the byte length of the underlying secret.
35 ///
36 /// # Returns
37 ///
38 /// - `usize` - Secret byte length.
39 #[inline(always)]
40 pub fn len(&self) -> usize {
41 let Self { inner } = self;
42 inner.len()
43 }
44
45 /// Returns whether the secret is empty.
46 ///
47 /// # Returns
48 ///
49 /// - `bool` - `true` when empty.
50 #[inline(always)]
51 pub fn is_empty(&self) -> bool {
52 self.len() == 0
53 }
54}
55
56/// Redacts [`SecretString`] in `Debug` output.
57impl fmt::Debug for SecretString {
58 /// Writes `[REDACTED]` instead of the secret bytes.
59 ///
60 /// # Arguments
61 ///
62 /// - `&mut fmt::Formatter<'_>` - Destination formatter.
63 ///
64 /// # Returns
65 ///
66 /// - `fmt::Result` - Formatting outcome.
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str(REDACTED_MARKER)
69 }
70}
71
72/// Redacts [`SecretString`] in `Display` output.
73impl fmt::Display for SecretString {
74 /// Writes `[REDACTED]` instead of the secret bytes.
75 ///
76 /// # Arguments
77 ///
78 /// - `&mut fmt::Formatter<'_>` - Destination formatter.
79 ///
80 /// # Returns
81 ///
82 /// - `fmt::Result` - Formatting outcome.
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(REDACTED_MARKER)
85 }
86}