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
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! # Base64 URL
//!
//! Base64 encode, decode, escape and unescape for URL applications.
//!
//! ## Examples
//!
//! Encode data to a Base64-URL string.
//!
//! ```
//! extern crate base64_url;
//!
//! assert_eq!("SGVsbG8sIHdvcmxkIQ", base64_url::encode("Hello, world!"));
//! ```
//!
//! Decode a Base64-URL string to data.
//!
//! ```
//! extern crate base64_url;
//!
//! assert_eq!("Hello, world!".as_bytes().to_vec(), base64_url::decode("SGVsbG8sIHdvcmxkIQ").unwrap());
//! ```
//!
//! Escape a Base64 string to a Base64-URL string. It is unsafe because the conversion is not concerning with Base64 decoding. You need to make sure the input string is a correct Base64 string by yourself.
//!
//! ```
//! extern crate base64_url;
//!
//! assert_eq!("SGVsbG8sIHdvcmxkIQ", base64_url::unsafe_escape("SGVsbG8sIHdvcmxkIQ=="));
//! ```
//!
//! Unescape a Base64-URL string to a Base64-URL string. It is unsafe because the conversion is not concerning with Base64 decoding. You need to make sure the input string is a correct Base64-URL string by yourself.
//!
//! ```
//! extern crate base64_url;
//!
//! assert_eq!("SGVsbG8sIHdvcmxkIQ==", base64_url::unsafe_unescape("SGVsbG8sIHdvcmxkIQ"));
//! ```
//!
//! Besides, in order to reduce the copy times of strings, you can also use `encode_and_push_to_string`, `decode_and_push_to_vec`, `unsafe_escape_owned` and `unsafe_unescape_owned` associated functions to use the same memory space.

pub extern crate base64;

/// Encode data to a Base64-URL string.
pub fn encode<T: ?Sized + AsRef<[u8]>>(input: &T) -> String {
    base64::encode_config(input, base64::URL_SAFE_NO_PAD)
}

/// Encode data to a Base64-URL string into a slice.
pub fn encode_and_store_to_slice<T: ?Sized + AsRef<[u8]>>(input: &T, output: &mut [u8]) -> usize {
    base64::encode_config_slice(input, base64::URL_SAFE_NO_PAD, output)
}

/// Encode data to a Base64-URL string and directly store into a String instance by concatenating them. It is usually for generating a URL.
pub fn encode_and_push_to_string<T: ?Sized + AsRef<[u8]>>(input: &T, output: String) -> String {
    let bytes = input.as_ref();

    let mut buffer = output.into_bytes();

    let current_len = buffer.len();

    let base64_len = (bytes.len() * 4 + 2) / 3;

    let min_capacity = current_len + base64_len;

    let capacity = buffer.capacity();

    if capacity < min_capacity {
        buffer.reserve(min_capacity - capacity);
    }

    unsafe {
        buffer.set_len(min_capacity);
    }

    let base64_len = encode_and_store_to_slice(bytes, &mut buffer[current_len..min_capacity]);

    unsafe {
        buffer.set_len(current_len + base64_len);
    }

    String::from_utf8(buffer).unwrap()
}

/// Decode a Base64-URL string to data.
pub fn decode<T: ?Sized + AsRef<[u8]>>(input: &T) -> Result<Vec<u8>, base64::DecodeError> {
    base64::decode_config(input, base64::URL_SAFE_NO_PAD)
}

/// Decode a Base64-URL string to data into a slice.
pub fn decode_and_store_to_slice<T: ?Sized + AsRef<[u8]>>(input: &T, output: &mut [u8]) -> Result<usize, base64::DecodeError> {
    base64::decode_config_slice(input, base64::URL_SAFE_NO_PAD, output)
}

/// Decode a Base64-URL string to data and directly store into a Vec instance by concatenating them.
pub fn decode_and_push_to_vec<T: ?Sized + AsRef<[u8]>>(input: &T, mut output: Vec<u8>) -> Result<Vec<u8>, base64::DecodeError> {
    let bytes = input.as_ref();

    let current_len = output.len();

    let original_max_len = {
        let len = bytes.len();
        (len + 3 / 4) * 3
    };

    let min_capacity = current_len + original_max_len;

    let capacity = output.capacity();

    if capacity < min_capacity {
        output.reserve(min_capacity - capacity);
    }

    unsafe {
        output.set_len(min_capacity);
    }

    let original_len = decode_and_store_to_slice(bytes, &mut output[current_len..min_capacity])?;

    unsafe {
        output.set_len(current_len + original_len);
    }

    Ok(output)
}

/// Escape a Base64 string to a Base64-URL string. It is unsafe because the conversion is not concerning with Base64 decoding. You need to make sure the input string is a correct Base64 string by yourself.
pub fn unsafe_escape(base64_str: &str) -> String {
    let mut result = Vec::with_capacity(base64_str.len());

    for &n in base64_str.as_bytes() {
        if n == 43 {
            result.push(45);
        } else if n == 47 {
            result.push(95);
        } else if n == 61 {
            break;
        } else {
            result.push(n);
        }
    }

    String::from_utf8(result).unwrap()
}

/// Escape a Base64 string to a Base64-URL string. It is unsafe because the conversion is not concerning with Base64 decoding. You need to make sure the input string is a correct Base64 string by yourself.
pub fn unsafe_escape_owned(base64_str: String) -> String {
    let mut result = base64_str.into_bytes();

    let mut len = result.len();

    for (index, n) in result.iter_mut().enumerate() {
        match *n {
            43 => *n = 45,
            47 => *n = 95,
            61 => { len = index; }
            _ => ()
        }
    }

    unsafe {
        result.set_len(len);
    }

    String::from_utf8(result).unwrap()
}

/// Unescape a Base64-URL string to a Base64-URL string. It is unsafe because the conversion is not concerning with Base64 decoding. You need to make sure the input string is a correct Base64-URL string by yourself.
pub fn unsafe_unescape(base64_str: &str) -> String {
    let len = base64_str.len();

    let mut result = Vec::with_capacity(((len * 4 / 3) + 3) / 4 * 4);

    for &n in base64_str.as_bytes() {
        if n == 45 {
            result.push(43);
        } else if n == 95 {
            result.push(47);
        } else {
            result.push(n);
        }
    }

    let padding = len % 4;

    if padding > 0 {
        for _ in padding..4 {
            result.push(61);
        }
    }

    String::from_utf8(result).unwrap()
}

/// Unescape a Base64-URL string to a Base64-URL string. It is unsafe because the conversion is not concerning with Base64 decoding. You need to make sure the input string is a correct Base64-URL string by yourself.
pub fn unsafe_unescape_owned(base64_str: String) -> String {
    let mut result = base64_str.into_bytes();

    for n in result.iter_mut() {
        match *n {
            45 => *n = 43,
            95 => *n = 47,
            _ => ()
        }
    }

    let padding = result.len() % 4;

    if padding > 0 {
        for _ in padding..4 {
            result.push(61);
        }
    }

    String::from_utf8(result).unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode() {
        assert_eq!("aHR0cHM6Ly9tYWdpY2xlbi5vcmc", encode("https://magiclen.org"));
    }

    #[test]
    fn test_encode_and_push_to_string() {
        let url = "https://magiclen.org/".to_string();

        assert_eq!("https://magiclen.org/YXJ0aWNsZXM", encode_and_push_to_string("articles", url));
    }

    #[test]
    fn test_decode() {
        assert_eq!("https://magiclen.org".as_bytes().to_vec(), decode("aHR0cHM6Ly9tYWdpY2xlbi5vcmc").unwrap());
    }

    #[test]
    fn test_decode_and_push_to_vec() {
        let url = "https://magiclen.org/".as_bytes().to_vec();

        assert_eq!("https://magiclen.org/articles".as_bytes().to_vec(), decode_and_push_to_vec("YXJ0aWNsZXM", url).unwrap());
    }

    #[test]
    fn test_unsafe_escape() {
        assert_eq!("aHR0cHM6Ly9tYWdpY2xlbi5vcmc", unsafe_escape(&base64::encode("https://magiclen.org")));
    }

    #[test]
    fn test_unsafe_escape_owned() {
        assert_eq!("aHR0cHM6Ly9tYWdpY2xlbi5vcmc", unsafe_escape_owned(base64::encode("https://magiclen.org")));
    }

    #[test]
    fn test_unsafe_unescape() {
        assert_eq!("https://magiclen.org".as_bytes().to_vec(), base64::decode(&unsafe_unescape("aHR0cHM6Ly9tYWdpY2xlbi5vcmc")).unwrap());
    }

    #[test]
    fn test_unsafe_unescape_owned() {
        assert_eq!("https://magiclen.org".as_bytes().to_vec(), base64::decode(&unsafe_unescape_owned("aHR0cHM6Ly9tYWdpY2xlbi5vcmc".to_string())).unwrap());
    }
}