macro_toolset/
base64.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//! Base64 related macros

pub use base64::*;

#[macro_export]
/// Base64 encode
///
/// # Param:
///  + `data`: impl [`AsRef`]<[u8]>
///  + `padding`: `base64::engine::general_purpose::{}`, `STANDARD`(default) /
///    `STANDARD_NO_PAD` / `URL_SAFE` / `URL_SAFE_NO_PAD`
///
/// # Example:
///
/// ```rust
/// # use macro_toolset::b64_encode;
/// # let example =
/// b64_encode!(b"hello world");
/// # assert_eq!(example, "aGVsbG8gd29ybGQ=");
/// ```
macro_rules! b64_encode {
    ($data:expr) => {
        $crate::b64_encode!($data, $crate::base64::engine::general_purpose::STANDARD)
    };
    ($data:expr, $padding:path) => {{
        let mut string_buf = String::with_capacity(256);
        $crate::base64::Engine::encode_string(&$padding, $data, &mut string_buf);
        string_buf
    }};
}

#[macro_export]
/// Base64 encode with [`bytes::Bytes`] returned
///
/// Param:
///  + `data`: impl [`AsRef`]<[u8]>
///  + `padding`: `base64::engine::general_purpose::{}`, `STANDARD`(default) /
///    `STANDARD_NO_PAD` / `URL_SAFE` / `URL_SAFE_NO_PAD`
///
/// # Example:
///
/// ```rust
/// # use macro_toolset::b64_encode_bytes;
/// # let example =
/// b64_encode_bytes!(b"hello world");
/// # assert_eq!(&example[..], &b"aGVsbG8gd29ybGQ="[..]);
/// ```
macro_rules! b64_encode_bytes {
    ($data:expr) => {
        b64_encode_bytes!($data, $crate::base64::engine::general_purpose::STANDARD)
    };
    ($data:expr, $padding:path) => {{
        let data = $data.as_ref();
        let target_len = data.len() * 4 / 3 + 4;
        let mut bytes_buf = bytes::BytesMut::with_capacity(target_len + 64);
        #[allow(unsafe_code)]
        // Safety: `target_len` is the exact length of the base64 string.
        unsafe {
            bytes_buf.set_len(target_len)
        };
        let bytes_written =
            $crate::base64::Engine::encode_slice(&$padding, $data, bytes_buf.as_mut()).unwrap_or(0);
        bytes_buf.truncate(bytes_written);
        bytes_buf.freeze()
    }};
}

#[macro_export]
/// Base64 decode
///
/// # Param:
///  + `data`
///  + `padding`: `base64::engine::general_purpose::{}`, `STANDARD`(default) /
///    `STANDARD_NO_PAD` / `URL_SAFE` / `URL_SAFE_NO_PAD`
///
/// # Example:
/// ```
/// # use macro_toolset::b64_decode;
/// // "hello world"
/// # let example =
/// b64_decode!("aGVsbG8gd29ybGQ=")
/// # .unwrap();
/// # assert_eq!(example, b"hello world");
/// ```
macro_rules! b64_decode {
    ($data:expr) => {
        b64_decode!($data, $crate::base64::engine::general_purpose::STANDARD)
    };
    ($data:expr, $padding:path) => {
        $crate::base64::Engine::decode(&$padding, $data)
    };
}