rustywallet_export/
hex_export.rs1use crate::types::HexOptions;
4use rustywallet_keys::prelude::PrivateKey;
5
6pub fn export_hex(key: &PrivateKey, options: HexOptions) -> String {
30 let bytes = key.to_bytes();
31
32 let hex = if options.uppercase {
33 bytes.iter().map(|b| format!("{:02X}", b)).collect::<String>()
34 } else {
35 bytes.iter().map(|b| format!("{:02x}", b)).collect::<String>()
36 };
37
38 if options.prefix {
39 format!("0x{}", hex)
40 } else {
41 hex
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn test_export_hex_default() {
51 let key = PrivateKey::random();
52 let hex = export_hex(&key, HexOptions::new());
53 assert_eq!(hex.len(), 64);
54 assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
55 }
56
57 #[test]
58 fn test_export_hex_with_prefix() {
59 let key = PrivateKey::random();
60 let hex = export_hex(&key, HexOptions::new().with_prefix(true));
61 assert!(hex.starts_with("0x"));
62 assert_eq!(hex.len(), 66);
63 }
64
65 #[test]
66 fn test_export_hex_uppercase() {
67 let key = PrivateKey::random();
68 let hex = export_hex(&key, HexOptions::new().with_uppercase(true));
69 assert!(hex.chars().filter(|c| c.is_alphabetic()).all(|c| c.is_uppercase()));
70 }
71
72 #[test]
73 fn test_export_hex_roundtrip() {
74 let key = PrivateKey::random();
75 let hex = export_hex(&key, HexOptions::new());
76 let recovered = PrivateKey::from_hex(&hex).unwrap();
77 assert_eq!(key.to_bytes(), recovered.to_bytes());
78 }
79}