df_hyperliquid_core/utils/
hex.rs1#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
6#[non_exhaustive]
7pub enum BadHex {
8 #[error("hex must have an even number of digits, found {0}")]
10 OddLength(usize),
11 #[error("expected {expected} bytes of hex, found {found}")]
13 WrongLength {
14 expected: usize,
16 found: usize,
18 },
19 #[error("`{0}` is not a hex digit")]
21 NotAHexDigit(char),
22}
23
24#[must_use]
26pub fn encode(bytes: &[u8]) -> String {
27 let mut text = String::with_capacity(bytes.len() * 2);
28 for byte in bytes {
29 text.push(nibble(byte >> 4));
30 text.push(nibble(byte & 0x0f));
31 }
32 text
33}
34
35#[must_use]
37pub fn encode_prefixed(bytes: &[u8]) -> String {
38 let mut text = String::with_capacity(bytes.len() * 2 + 2);
39 text.push_str("0x");
40 text.push_str(&encode(bytes));
41 text
42}
43
44pub fn decode(text: &str) -> Result<Vec<u8>, BadHex> {
46 let body = body_of(text);
47 if !body.len().is_multiple_of(2) {
48 return Err(BadHex::OddLength(body.len()));
49 }
50 let mut bytes = vec![0u8; body.len() / 2];
51 fill(body, &mut bytes)?;
52 Ok(bytes)
53}
54
55pub fn decode_into(text: &str, out: &mut [u8]) -> Result<(), BadHex> {
57 let body = body_of(text);
58 if !body.len().is_multiple_of(2) {
59 return Err(BadHex::OddLength(body.len()));
60 }
61 if body.len() / 2 != out.len() {
62 return Err(BadHex::WrongLength { expected: out.len(), found: body.len() / 2 });
63 }
64 fill(body, out)
65}
66
67pub fn decode_array<const N: usize>(text: &str) -> Result<[u8; N], BadHex> {
69 let mut bytes = [0u8; N];
70 decode_into(text, &mut bytes)?;
71 Ok(bytes)
72}
73
74fn body_of(text: &str) -> &str {
75 let raw = text.trim();
76 raw.strip_prefix("0x").or_else(|| raw.strip_prefix("0X")).unwrap_or(raw)
77}
78
79fn fill(body: &str, out: &mut [u8]) -> Result<(), BadHex> {
80 let digits = body.as_bytes();
81 for &byte in digits {
82 digit(byte)?;
83 }
84 for (index, slot) in out.iter_mut().enumerate() {
85 let high = digit(digits[index * 2])?;
86 let low = digit(digits[index * 2 + 1])?;
87 *slot = (high << 4) | low;
88 }
89 Ok(())
90}
91
92fn digit(byte: u8) -> Result<u8, BadHex> {
93 match byte {
94 b'0'..=b'9' => Ok(byte - b'0'),
95 b'a'..=b'f' => Ok(byte - b'a' + 10),
96 b'A'..=b'F' => Ok(byte - b'A' + 10),
97 _ => Err(BadHex::NotAHexDigit(char::from(byte))),
98 }
99}
100
101const fn nibble(value: u8) -> char {
102 (if value < 10 { b'0' + value } else { b'a' + value - 10 }) as char
103}
104
105#[cfg(test)]
106#[path = "tests/hex.rs"]
107mod tests;