alephium_web3/utils/
mod.rs1pub mod bs58;
5pub mod djb2;
6
7use crate::error::{Error, Result};
8
9pub fn is_hex_string(s: &str) -> bool {
11 if s.is_empty() {
12 return false;
13 }
14 let s = s.strip_prefix("0x").unwrap_or(s);
15 s.chars().all(|c| c.is_ascii_hexdigit())
16}
17
18pub fn hex_to_bytes(s: &str) -> Result<Vec<u8>> {
20 let s = s.strip_prefix("0x").unwrap_or(s);
21 hex::decode(s).map_err(|e| Error::InvalidHex(format!("{}: {}", s, e)))
22}
23
24pub fn hex_to_bin_unsafe(s: &str) -> Vec<u8> {
26 let s = s.strip_prefix("0x").unwrap_or(s);
27 hex::decode(s).unwrap_or_default()
28}
29
30pub fn bin_to_hex(bytes: &[u8]) -> String {
32 hex::encode(bytes)
33}
34
35pub fn bin_to_hex_with_prefix(bytes: &[u8]) -> String {
37 format!("0x{}", hex::encode(bytes))
38}
39
40pub fn concat_bytes(slices: &[&[u8]]) -> Vec<u8> {
42 let total_len: usize = slices.iter().map(|s| s.len()).sum();
43 let mut result = Vec::with_capacity(total_len);
44 for slice in slices {
45 result.extend_from_slice(slice);
46 }
47 result
48}
49
50pub fn xor_byte(bytes: &[u8], byte: u8) -> Vec<u8> {
52 bytes.iter().map(|b| b ^ byte).collect()
53}
54
55pub fn djb2_hash(bytes: &[u8]) -> u32 {
57 djb2::djb2(bytes)
58}
59
60pub trait TypeEq<T> {}
62impl<T> TypeEq<T> for T {}
63
64#[macro_export]
66macro_rules! assert_type_eq {
67 ($t1:ty, $t2:ty) => {
68 const _: () = {
69 fn assert_eq<T: $crate::utils::TypeEq<$t2>>() {}
70 fn check() {
71 assert_eq::<$t1>()
72 }
73 };
74 };
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn test_is_hex_string() {
83 assert!(is_hex_string("deadbeef"));
84 assert!(is_hex_string("0xdeadbeef"));
85 assert!(is_hex_string("DEADBEEF"));
86 assert!(!is_hex_string("xyz"));
87 assert!(!is_hex_string(""));
88 }
89
90 #[test]
91 fn test_hex_conversion() {
92 let bytes = vec![0xde, 0xad, 0xbe, 0xef];
93 let hex_str = bin_to_hex(&bytes);
94 assert_eq!(hex_str, "deadbeef");
95
96 let decoded = hex_to_bytes(&hex_str).unwrap();
97 assert_eq!(decoded, bytes);
98
99 let decoded_with_prefix = hex_to_bytes("0xdeadbeef").unwrap();
100 assert_eq!(decoded_with_prefix, bytes);
101 }
102
103 #[test]
104 fn test_concat_bytes() {
105 let a = vec![1, 2, 3];
106 let b = vec![4, 5, 6];
107 let c = vec![7, 8, 9];
108 let result = concat_bytes(&[&a, &b, &c]);
109 assert_eq!(result, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
110 }
111
112 #[test]
113 fn test_xor_byte() {
114 let bytes = vec![0x00, 0xFF, 0xAA];
115 let result = xor_byte(&bytes, 0xFF);
116 assert_eq!(result, vec![0xFF, 0x00, 0x55]);
117 }
118}