@@ -26,6 +26,16 @@ use super::config::CredentialCacheValue;
26
26
///
27
27
/// This type does not implement `Display`, and has a `Debug` impl that hides
28
28
/// the contained value.
29
+ ///
30
+ /// ```
31
+ /// # use cargo::util::auth::Secret;
32
+ /// let token = Secret::from("super secret string");
33
+ /// assert_eq!(format!("{:?}", token), "Secret { inner: \"REDACTED\" }");
34
+ /// ```
35
+ ///
36
+ /// Currently, we write a borrowed `Secret<T>` as `Secret<&T>`.
37
+ /// The [`as_deref`](Secret::as_deref) and [`owned`](Secret::owned) methods can
38
+ /// be used to convert back and forth between `Secret<String>` and `Secret<&str>`.
29
39
#[ derive( Clone , PartialEq , Eq ) ]
30
40
pub struct Secret < T > {
31
41
inner : T ,
@@ -41,20 +51,24 @@ impl<T> Secret<T> {
41
51
}
42
52
43
53
/// Converts a `Secret<T>` to a `Secret<&T::Target>`.
44
- ///
45
- /// For example, this can be used to convert from `&Secret<String>` to
46
- /// `Secret<&str>`.
54
+ /// ```
55
+ /// # use cargo::util::auth::Secret;
56
+ /// let owned: Secret<String> = Secret::from(String::from("token"));
57
+ /// let borrowed: Secret<&str> = owned.as_deref();
58
+ /// ```
47
59
pub fn as_deref ( & self ) -> Secret < & <T as Deref >:: Target >
48
60
where
49
61
T : Deref ,
50
62
{
51
63
Secret :: from ( self . inner . deref ( ) )
52
64
}
53
65
66
+ /// Converts a `Secret<T>` to a `Secret<&T>`.
54
67
pub fn as_ref ( & self ) -> Secret < & T > {
55
68
Secret :: from ( & self . inner )
56
69
}
57
70
71
+ /// Converts a `Secret<T>` to a `Secret<U>` by applying `f` to the contained value.
58
72
pub fn map < U , F > ( self , f : F ) -> Secret < U >
59
73
where
60
74
F : FnOnce ( T ) -> U ,
@@ -66,21 +80,25 @@ impl<T> Secret<T> {
66
80
impl < T : ToOwned + ?Sized > Secret < & T > {
67
81
/// Converts a `Secret` containing a borrowed type to a `Secret` containing the
68
82
/// corresponding owned type.
69
- ///
70
- /// For example, this can be used to convert from `Secret<&str>` to
71
- /// `Secret<String>`.
83
+ /// ```
84
+ /// # use cargo::util::auth::Secret;
85
+ /// let borrowed: Secret<&str> = Secret::from("token");
86
+ /// let owned: Secret<String> = borrowed.owned();
87
+ /// ```
72
88
pub fn owned ( & self ) -> Secret < <T as ToOwned >:: Owned > {
73
89
Secret :: from ( self . inner . to_owned ( ) )
74
90
}
75
91
}
76
92
77
93
impl < T , E > Secret < Result < T , E > > {
94
+ /// Converts a `Secret<Result<T, E>>` to a `Result<Secret<T>, E>`.
78
95
pub fn transpose ( self ) -> Result < Secret < T > , E > {
79
96
self . inner . map ( |v| Secret :: from ( v) )
80
97
}
81
98
}
82
99
83
100
impl < T : AsRef < str > > Secret < T > {
101
+ /// Checks if the contained value is empty.
84
102
pub fn is_empty ( & self ) -> bool {
85
103
self . inner . as_ref ( ) . is_empty ( )
86
104
}
0 commit comments