spawn_base64/
lib.rs

1use wasm_bindgen::prelude::*;
2use base64::{encode_config, decode_config, STANDARD, URL_SAFE};
3
4/// Base64 encoding function for Ethereum smart contracts
5/// Encodes input bytes into a Base64 string.
6#[wasm_bindgen]
7pub fn base64_encode(data: &[u8]) -> String {
8    encode_config(data, STANDARD)
9}
10
11/// Base64 decoding function for Ethereum smart contracts
12/// Decodes a Base64 string back into bytes. Now with proper error handling.
13#[wasm_bindgen]
14pub fn base64_decode(encoded_data: &str) -> Result<Vec<u8>, JsValue> {
15    decode_config(encoded_data, STANDARD).map_err(|e| JsValue::from_str(&format!("Invalid Base64 input: {}", e)))
16}
17
18/// URL-safe Base64 encoding function
19/// Encodes input bytes into a URL-safe Base64 string.
20#[wasm_bindgen]
21pub fn base64_encode_url_safe(data: &[u8]) -> String {
22    encode_config(data, URL_SAFE)
23}
24
25/// URL-safe Base64 decoding function
26/// Decodes a URL-safe Base64 string back into bytes. Now with proper error handling.
27#[wasm_bindgen]
28pub fn base64_decode_url_safe(encoded_data: &str) -> Result<Vec<u8>, JsValue> {
29    decode_config(encoded_data, URL_SAFE).map_err(|e| JsValue::from_str(&format!("Invalid Base64 input: {}", e)))
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn test_base64_encode() {
38        let data = b"Hello, Ethereum!";
39        let encoded = base64_encode(data);
40        assert_eq!(encoded, "SGVsbG8sIEV0aGVyZXVtIQ==");
41    }
42
43    #[test]
44    fn test_base64_decode() {
45        let encoded = "SGVsbG8sIEV0aGVyZXVtIQ==";
46        let decoded = base64_decode(encoded).expect("Failed to decode");
47        assert_eq!(decoded, b"Hello, Ethereum!");
48    }
49
50    #[test]
51    fn test_base64_encode_url_safe() {
52        let data = b"Hello, Ethereum!";
53        let encoded = base64_encode_url_safe(data);
54        assert_eq!(encoded, "SGVsbG8sIEV0aGVyZXVtIQ==");
55    }
56
57    #[test]
58    fn test_base64_decode_url_safe() {
59        let encoded = "SGVsbG8sIEV0aGVyZXVtIQ==";
60        let decoded = base64_decode_url_safe(encoded).expect("Failed to decode");
61        assert_eq!(decoded, b"Hello, Ethereum!");
62    }
63
64    #[test]
65    fn test_invalid_base64_input() {
66        let invalid_data = "InvalidBase64";
67        let result = base64_decode(invalid_data);
68        assert!(result.is_err(), "Expected error on invalid Base64 input");
69    }
70}