ctb_formats_base64/
base64.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Base64 encoding, decoding, and conversion helpers.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::{Result, anyhow};
30use base64::Engine;
31use base64::prelude::BASE64_STANDARD;
32use std::collections::HashMap;
33
34use crate::bail_if_none;
35
36/// Converts bytes to standard RFC 4648 base64 representation.
37/// <https://datatracker.ietf.org/doc/html/rfc4648#section-4>
38pub fn bytes_to_standard_base64(bytes: &[u8]) -> String {
39    BASE64_STANDARD.encode(bytes)
40}
41pub fn base64_encode(bytes: &[u8]) -> String {
42    bytes_to_standard_base64(bytes)
43}
44
45pub fn standard_base64_to_bytes(base64: &str) -> Result<Vec<u8>> {
46    BASE64_STANDARD
47        .decode(base64)
48        .map_err(|e| anyhow!("Failed to decode base64: {e}"))
49}
50pub fn base64_decode(base64: &str) -> Result<Vec<u8>> {
51    standard_base64_to_bytes(base64)
52}
53
54/// Converts base64 input string to decimal representation. Padding becomes 64.
55pub fn standard_base64_to_decimal(base64: String) -> Result<Vec<u8>> {
56    let alphabet = base64::alphabet::STANDARD.as_str();
57
58    let index: HashMap<u8, u8> = alphabet
59        .chars()
60        .enumerate()
61        .filter_map(|(i, c)| {
62            let c_u8 = u8::try_from(c).ok()?;
63            let i_u8 = u8::try_from(i).ok()?;
64            Some((c_u8, i_u8))
65        })
66        .collect();
67
68    let mut out = Vec::new();
69    // convert the decoded bytes to decimal using the index
70    for byte in base64.bytes() {
71        if byte == 61 {
72            out.push(64);
73        } else {
74            out.push(bail_if_none!(index.get(&byte).copied()));
75        }
76    }
77    Ok(out)
78}
79
80/// Converts decimal representation (0 = A, 1 = B and so on) to standard RFC
81/// 4648 base64 string. Padding is represented by 64.
82pub fn decimal_to_standard_base64(decimal: Vec<u8>) -> Result<String> {
83    let alphabet = base64::alphabet::STANDARD.as_str();
84    let mut out = String::new();
85
86    for &value in &decimal {
87        let v = value;
88        if v == 64 {
89            out.push('=');
90            continue;
91        }
92        out.push(bail_if_none!(alphabet.chars().nth(usize::from(v))));
93    }
94
95    Ok(out)
96}
97
98#[cfg(test)]
99#[allow(
100    clippy::panic,
101    clippy::expect_used,
102    clippy::unwrap_used,
103    clippy::unwrap_in_result,
104    clippy::panic_in_result_fn,
105    clippy::indexing_slicing,
106    clippy::arithmetic_side_effects,
107    reason = "Standard repository test boilerplate"
108)]
109mod tests {
110    use crate::utilities::{assert_vec_u8_eq, assert_vec_u8_ok_eq};
111    use ctb_formats_utilities::assert_string_ok_eq;
112
113    use super::*;
114
115    #[crate::ctb_test]
116    fn test_bytes_to_standard_base64() {
117        let input = b"Hello, world!";
118        let expected = "SGVsbG8sIHdvcmxkIQ==";
119        let result = bytes_to_standard_base64(input);
120        assert_eq!(result, expected);
121    }
122
123    #[crate::ctb_test]
124    fn test_standard_base64_to_bytes() {
125        let input = "SGVsbG8sIHdvcmxkIQ==".to_string();
126        let expected = b"Hello, world!";
127        let result = standard_base64_to_bytes(&input).unwrap();
128        assert_vec_u8_eq(expected, &result);
129    }
130
131    #[crate::ctb_test]
132    fn test_base64_to_decimal() {
133        let input = "SGVsbG8sIHdvcmxkIQ==";
134        let expected = vec![
135            18, 6, 21, 44, 27, 6, 60, 44, 8, 7, 29, 47, 28, 38, 49, 36, 8, 16,
136            64, 64,
137        ];
138        let result = standard_base64_to_decimal(input.to_string());
139        assert_vec_u8_ok_eq(&expected, result);
140    }
141
142    #[crate::ctb_test]
143    fn test_decimal_to_base64() {
144        let input = vec![
145            18, 6, 21, 44, 27, 6, 60, 44, 8, 7, 29, 47, 28, 38, 49, 36, 8, 16,
146            64, 64,
147        ];
148        let expected = "SGVsbG8sIHdvcmxkIQ==";
149        let result = decimal_to_standard_base64(input);
150        assert_string_ok_eq(expected, result);
151    }
152}