libsubconverter/utils/
base64.rs

1use base64::{
2    engine::{general_purpose, DecodePaddingMode},
3    Engine as _,
4};
5
6/// Encodes a string to Base64 format.
7pub fn base64_encode(input: &str) -> String {
8    general_purpose::STANDARD.encode(input)
9}
10
11/// Decodes a Base64 string to its original form.
12///
13/// # Arguments
14/// * `input` - The Base64 encoded string.
15/// * `accept_urlsafe` - A boolean indicating whether to accept URL-safe Base64 encoding.
16///
17/// # Returns
18/// The decoded string, or an empty string if the input is invalid.
19fn base64_decode(input: &str, accept_urlsafe: bool) -> Option<String> {
20    let purpose_config = general_purpose::GeneralPurposeConfig::new()
21        .with_decode_padding_mode(DecodePaddingMode::Indifferent);
22    let engine = general_purpose::GeneralPurpose::new(
23        if accept_urlsafe {
24            &base64::alphabet::URL_SAFE
25        } else {
26            &base64::alphabet::STANDARD
27        },
28        purpose_config,
29    );
30    match engine.decode(input) {
31        Ok(decoded) => Some(String::from_utf8_lossy(&decoded).to_string()),
32        Err(e) => {
33            log::warn!("Failed to decode base64: {}", e);
34            None
35        } // Handle invalid Base64 input
36    }
37}
38
39/// Reverses a URL-safe Base64 string to standard Base64 format.
40pub fn url_safe_base64_reverse(input: &str) -> String {
41    input.replace('-', "+").replace('_', "/")
42}
43
44/// Converts a Base64 string to URL-safe Base64 format by replacing specific characters.
45pub fn url_safe_base64_apply(input: &str) -> String {
46    input.replace('+', "-").replace('/', "_").replace('=', "") // Remove padding
47}
48
49/// Decodes a URL-safe Base64 string to its original form.
50pub fn url_safe_base64_decode(input: &str) -> String {
51    match base64_decode(&url_safe_base64_reverse(input), false) {
52        Some(decoded) => decoded,
53        None => input.to_string(),
54    }
55}
56
57/// Encodes a string to URL-safe Base64 format.
58pub fn url_safe_base64_encode(input: &str) -> String {
59    url_safe_base64_apply(&base64_encode(input))
60}