securer_string/secure_types/
string.rs1use core::fmt;
2use std::str::FromStr;
3
4use crate::SecureVec;
5use crate::secure_utils::memlock;
6
7#[derive(Clone)]
9pub struct SecureString(SecureVec<u8>);
10
11impl SecureString {
12 pub fn unsecure(&self) -> &str {
14 unsafe { std::str::from_utf8_unchecked(self.0.unsecure()) }
18 }
19
20 pub fn unsecure_mut(&mut self) -> &mut str {
22 unsafe { std::str::from_utf8_unchecked_mut(self.0.unsecure_mut()) }
24 }
25
26 pub fn into_unsecure(mut self) -> String {
28 memlock::munlock(self.0.content.as_mut_ptr(), self.0.content.capacity());
29 let content = std::mem::take(&mut self.0.content);
30 std::mem::forget(self);
31 unsafe { String::from_utf8_unchecked(content) }
33 }
34
35 pub fn zero_out(&mut self) {
40 self.0.zero_out()
41 }
42}
43
44impl PartialEq for SecureString {
45 fn eq(&self, other: &SecureString) -> bool {
46 self.0 == other.0
48 }
49}
50
51impl Eq for SecureString {}
52
53impl fmt::Debug for SecureString {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 f.write_str("***SECRET***").map_err(|_| fmt::Error)
56 }
57}
58
59impl fmt::Display for SecureString {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 f.write_str("***SECRET***").map_err(|_| fmt::Error)
62 }
63}
64
65impl<U> From<U> for SecureString
66where
67 U: Into<String>,
68{
69 fn from(s: U) -> SecureString {
70 SecureString(SecureVec::new(s.into().into_bytes()))
71 }
72}
73
74impl FromStr for SecureString {
75 type Err = std::convert::Infallible;
76
77 fn from_str(s: &str) -> Result<Self, Self::Err> {
78 Ok(SecureString(SecureVec::new(s.into())))
79 }
80}
81
82#[cfg(feature = "serde")]
83impl serde::Serialize for SecureString {
84 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
85 where
86 S: serde::Serializer,
87 {
88 serializer.serialize_str(self.unsecure())
89 }
90}
91
92#[cfg(feature = "serde")]
93impl<'de> serde::Deserialize<'de> for SecureString {
94 fn deserialize<D>(deserializer: D) -> Result<SecureString, D::Error>
95 where
96 D: serde::Deserializer<'de>,
97 {
98 struct SecureStringVisitor;
99 impl<'de> serde::de::Visitor<'de> for SecureStringVisitor {
100 type Value = SecureString;
101 fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
102 write!(formatter, "an utf-8 encoded string")
103 }
104 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
105 where
106 E: serde::de::Error,
107 {
108 Ok(SecureString::from(v.to_string()))
109 }
110 }
111 deserializer.deserialize_string(SecureStringVisitor)
112 }
113}