scl_core/
password.rs

1//! 一个密码类,String 的壳子,用来在调试输出时挡住真实密码,防止泄露
2
3use std::{
4    fmt::{Debug, Display},
5    ops::Deref,
6};
7
8use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
9
10/// 一个密码类,String 的壳子,用来在调试输出时挡住真实密码,防止泄露
11#[derive(Clone, PartialEq, Eq, Default)]
12pub struct Password(String);
13
14impl Serialize for Password {
15    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
16    where
17        S: serde::Serializer,
18    {
19        serializer.serialize_str(&self.0)
20    }
21}
22
23impl<'de> Deserialize<'de> for Password {
24    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
25    where
26        D: Deserializer<'de>,
27    {
28        struct PasswordVisitor;
29        impl<'de> Visitor<'de> for PasswordVisitor {
30            type Value = Password;
31            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
32                formatter.write_str("a password as string")
33            }
34
35            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
36            where
37                E: serde::de::Error,
38            {
39                Ok(Password(v.to_string()))
40            }
41
42            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
43            where
44                E: serde::de::Error,
45            {
46                Ok(Password(v.to_string()))
47            }
48
49            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
50            where
51                E: serde::de::Error,
52            {
53                Ok(Password(v.to_string()))
54            }
55        }
56        deserializer.deserialize_str(PasswordVisitor)
57    }
58}
59
60impl Password {
61    /// 从密码类中拿出原始字符串,请注意保护密码安全
62    pub fn take_string(self) -> String {
63        self.0
64    }
65
66    /// 从密码类中复制出原始字符串,请注意保护密码安全
67    pub fn to_owned_string(&self) -> String {
68        self.0.to_owned()
69    }
70
71    /// 从密码类中借出原始字符串,请注意保护密码安全
72    pub fn as_string(&self) -> &String {
73        &self.0
74    }
75}
76
77impl Debug for Password {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str("***Password***")
80    }
81}
82
83impl Display for Password {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.write_str("***Password***")
86    }
87}
88
89impl Deref for Password {
90    type Target = String;
91    fn deref(&self) -> &String {
92        &self.0
93    }
94}
95
96impl From<Password> for String {
97    fn from(a: Password) -> Self {
98        a.0
99    }
100}
101
102impl From<String> for Password {
103    fn from(a: String) -> Self {
104        Self(a)
105    }
106}
107
108impl From<&str> for Password {
109    fn from(a: &str) -> Self {
110        Self(a.to_owned())
111    }
112}