base64url/lib.rs
1/*
2 Copyright © 2023, ParallelChain Lab
3 Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
4*/
5
6//! Implementation of the encode and decode operations on base64url (as defined in IETF RFC 4648) String.
7//! The encoded string restricted to containing the 2^6 UTF-8 code points without padding.
8//!
9//! In general, we use `-` and `_` instead of `+` and `/`, without paddings.
10
11use base64::{Engine as _, engine::{self, general_purpose}, alphabet};
12const ENGINE: engine::GeneralPurpose = engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
13
14/// encode takes in a slice of bytes and returns the bytes encoded as a base64url String.
15pub fn encode<T: AsRef<[u8]>>(bytes: T) -> String {
16 ENGINE.encode(bytes)
17}
18
19/// decode takes in a string and tries to decode it into a Vector of bytes. It returns a base64::DecodeError if `string`
20/// is not valid Base64URL.
21pub fn decode<T: ?Sized + AsRef<[u8]>>(base64_url: &T) -> Result<Vec<u8>, base64::DecodeError> {
22 ENGINE.decode(base64_url)
23}
24