Skip to main content

windjammer_runtime/
encoding.rs

1//! Encoding and decoding utilities
2//!
3//! Windjammer's `std::encoding` module maps to these functions.
4
5use base64::{engine::general_purpose, Engine as _};
6
7/// Base64 encode bytes
8pub fn base64_encode(data: &[u8]) -> String {
9    general_purpose::STANDARD.encode(data)
10}
11
12/// Base64 decode string
13pub fn base64_decode(s: &str) -> Result<Vec<u8>, String> {
14    general_purpose::STANDARD
15        .decode(s)
16        .map_err(|e| e.to_string())
17}
18
19/// Hex encode bytes
20pub fn hex_encode(data: &[u8]) -> String {
21    data.iter().map(|b| format!("{:02x}", b)).collect()
22}
23
24/// Hex decode string
25pub fn hex_decode(s: &str) -> Result<Vec<u8>, String> {
26    (0..s.len())
27        .step_by(2)
28        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
29        .collect::<Result<Vec<u8>, _>>()
30        .map_err(|e| e.to_string())
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn test_base64() {
39        let data = b"hello world";
40        let encoded = base64_encode(data);
41        let decoded = base64_decode(&encoded).unwrap();
42        assert_eq!(decoded, data);
43    }
44
45    #[test]
46    fn test_hex() {
47        let data = b"test";
48        let encoded = hex_encode(data);
49        assert_eq!(encoded, "74657374");
50        let decoded = hex_decode(&encoded).unwrap();
51        assert_eq!(decoded, data);
52    }
53}