windjammer_runtime/
encoding.rs1use base64::{engine::general_purpose, Engine as _};
6
7pub fn base64_encode(data: &[u8]) -> String {
9 general_purpose::STANDARD.encode(data)
10}
11
12pub 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
19pub fn hex_encode(data: &[u8]) -> String {
21 data.iter().map(|b| format!("{:02x}", b)).collect()
22}
23
24pub 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}