/rust/registry/src/index.crates.io-1949cf8c6b5b557f/password-hash-0.4.2/src/encoding.rs
Line | Count | Source |
1 | | //! Base64 encoding variants. |
2 | | |
3 | | use base64ct::{ |
4 | | Base64Bcrypt, Base64Crypt, Base64Unpadded as B64, Encoding as _, Error as B64Error, |
5 | | }; |
6 | | |
7 | | /// Base64 encoding variants. |
8 | | #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] |
9 | | pub enum Encoding { |
10 | | /// "B64" encoding: standard Base64 without padding. |
11 | | /// |
12 | | /// ```text |
13 | | /// [A-Z] [a-z] [0-9] + / |
14 | | /// 0x41-0x5a, 0x61-0x7a, 0x30-0x39, 0x2b, 0x2f |
15 | | /// ``` |
16 | | /// <https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#b64> |
17 | | B64, |
18 | | |
19 | | /// bcrypt encoding. |
20 | | /// |
21 | | /// ```text |
22 | | /// ./ [A-Z] [a-z] [0-9] |
23 | | /// 0x2e-0x2f, 0x41-0x5a, 0x61-0x7a, 0x30-0x39 |
24 | | /// ``` |
25 | | Bcrypt, |
26 | | |
27 | | /// `crypt(3)` encoding. |
28 | | /// |
29 | | /// ```text |
30 | | /// [.-9] [A-Z] [a-z] |
31 | | /// 0x2e-0x39, 0x41-0x5a, 0x61-0x7a |
32 | | /// ``` |
33 | | Crypt, |
34 | | } |
35 | | |
36 | | impl Default for Encoding { |
37 | 0 | fn default() -> Self { |
38 | 0 | Self::B64 |
39 | 0 | } |
40 | | } |
41 | | |
42 | | impl Encoding { |
43 | | /// Decode a Base64 string into the provided destination buffer. |
44 | 0 | pub fn decode(self, src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], B64Error> { |
45 | 0 | match self { |
46 | 0 | Self::B64 => B64::decode(src, dst), |
47 | 0 | Self::Bcrypt => Base64Bcrypt::decode(src, dst), |
48 | 0 | Self::Crypt => Base64Crypt::decode(src, dst), |
49 | | } |
50 | 0 | } |
51 | | |
52 | | /// Encode the input byte slice as Base64. |
53 | | /// |
54 | | /// Writes the result into the provided destination slice, returning an |
55 | | /// ASCII-encoded Base64 string value. |
56 | 0 | pub fn encode<'a>(self, src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, B64Error> { |
57 | 0 | match self { |
58 | 0 | Self::B64 => B64::encode(src, dst), |
59 | 0 | Self::Bcrypt => Base64Bcrypt::encode(src, dst), |
60 | 0 | Self::Crypt => Base64Crypt::encode(src, dst), |
61 | | } |
62 | 0 | .map_err(Into::into) |
63 | 0 | } |
64 | | |
65 | | /// Get the length of Base64 produced by encoding the given bytes. |
66 | 0 | pub fn encoded_len(self, bytes: &[u8]) -> usize { |
67 | 0 | match self { |
68 | 0 | Self::B64 => B64::encoded_len(bytes), |
69 | 0 | Self::Bcrypt => Base64Bcrypt::encoded_len(bytes), |
70 | 0 | Self::Crypt => Base64Crypt::encoded_len(bytes), |
71 | | } |
72 | 0 | } |
73 | | } |