sevenz_rust2/encryption/
password.rs

1use crate::ByteWriter;
2
3/// A password used for password protected, encrypted files.
4///
5/// Use [`Password::empty()`] to create an empty password when no
6/// password is used.
7///
8/// You can convert strings easily into password using the Into/From traits:
9///
10/// ```rust
11/// use sevenz_rust2::Password;
12///
13/// let password: Password = "a password string".into();
14/// ```
15#[derive(Debug, Default, Clone, PartialEq)]
16pub struct Password(Vec<u8>);
17
18impl Password {
19    /// Creates a new [`Password`] from the given password string.
20    ///
21    /// Internally a password string is encoded as UTF-16.
22    pub fn new(password: &str) -> Self {
23        Self::from(password)
24    }
25
26    /// Creates a new [`Password`] from the given raw bytes.
27    pub fn from_raw(bytes: &[u8]) -> Self {
28        Self(bytes.to_vec())
29    }
30
31    /// Creates an empty password.
32    pub fn empty() -> Self {
33        Self(Default::default())
34    }
35
36    /// Returns the byte representation of the password.
37    pub fn as_slice(&self) -> &[u8] {
38        &self.0
39    }
40
41    /// Returns `true` if the password is empty.
42    pub fn is_empty(&self) -> bool {
43        self.0.is_empty()
44    }
45}
46
47impl AsRef<[u8]> for Password {
48    fn as_ref(&self) -> &[u8] {
49        &self.0
50    }
51}
52
53impl From<&str> for Password {
54    fn from(s: &str) -> Self {
55        let mut result = Vec::with_capacity(s.len() * 2);
56        let utf16 = s.encode_utf16();
57        for u in utf16 {
58            let _ = result.write_u16(u);
59        }
60        Self(result)
61    }
62}