Skip to content

Commit a32cef9

Browse files
committed
improve docs for Secret<T>; add doctest to assert that inner val is hidden
1 parent 36cad92 commit a32cef9

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/cargo/util/auth.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ use super::config::CredentialCacheValue;
2626
///
2727
/// This type does not implement `Display`, and has a `Debug` impl that hides
2828
/// 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>`.
2939
#[derive(Clone, PartialEq, Eq)]
3040
pub struct Secret<T> {
3141
inner: T,
@@ -41,20 +51,24 @@ impl<T> Secret<T> {
4151
}
4252

4353
/// 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+
/// ```
4759
pub fn as_deref(&self) -> Secret<&<T as Deref>::Target>
4860
where
4961
T: Deref,
5062
{
5163
Secret::from(self.inner.deref())
5264
}
5365

66+
/// Converts a `Secret<T>` to a `Secret<&T>`.
5467
pub fn as_ref(&self) -> Secret<&T> {
5568
Secret::from(&self.inner)
5669
}
5770

71+
/// Converts a `Secret<T>` to a `Secret<U>` by applying `f` to the contained value.
5872
pub fn map<U, F>(self, f: F) -> Secret<U>
5973
where
6074
F: FnOnce(T) -> U,
@@ -66,21 +80,25 @@ impl<T> Secret<T> {
6680
impl<T: ToOwned + ?Sized> Secret<&T> {
6781
/// Converts a `Secret` containing a borrowed type to a `Secret` containing the
6882
/// 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+
/// ```
7288
pub fn owned(&self) -> Secret<<T as ToOwned>::Owned> {
7389
Secret::from(self.inner.to_owned())
7490
}
7591
}
7692

7793
impl<T, E> Secret<Result<T, E>> {
94+
/// Converts a `Secret<Result<T, E>>` to a `Result<Secret<T>, E>`.
7895
pub fn transpose(self) -> Result<Secret<T>, E> {
7996
self.inner.map(|v| Secret::from(v))
8097
}
8198
}
8299

83100
impl<T: AsRef<str>> Secret<T> {
101+
/// Checks if the contained value is empty.
84102
pub fn is_empty(&self) -> bool {
85103
self.inner.as_ref().is_empty()
86104
}

0 commit comments

Comments
 (0)