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