async_sevenz/encryption/
password.rs

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