df_hyperliquid_core/utils/
address.rs1use std::{fmt, str::FromStr};
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
10pub struct Address([u8; 20]);
11
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14#[error("`{0}` is not a 20-byte hex address")]
15pub struct BadAddress(String);
16
17impl Address {
18 pub const ZERO: Address = Address([0u8; 20]);
20
21 #[must_use]
23 pub const fn from_bytes(bytes: [u8; 20]) -> Self {
24 Address(bytes)
25 }
26
27 #[must_use]
29 pub const fn bytes(&self) -> &[u8; 20] {
30 &self.0
31 }
32
33 #[must_use]
35 pub fn is_zero(&self) -> bool {
36 *self == Address::ZERO
37 }
38
39 #[must_use]
41 pub const fn parse_const(text: &str) -> Option<Address> {
42 let raw = text.as_bytes();
43 if raw.len() != 42 || raw[0] != b'0' || (raw[1] != b'x' && raw[1] != b'X') {
44 return None;
45 }
46 let mut bytes = [0u8; 20];
47 let mut at = 0;
48 while at < 20 {
49 let (Some(high), Some(low)) = (hex_digit(raw[2 + at * 2]), hex_digit(raw[3 + at * 2])) else {
50 return None;
51 };
52 bytes[at] = (high << 4) | low;
53 at += 1;
54 }
55 Some(Address(bytes))
56 }
57
58 #[must_use]
60 pub fn to_hex(self) -> String {
61 crate::utils::hex::encode_prefixed(&self.0)
62 }
63}
64
65const HEX: [u8; 256] = {
67 let mut table = [NOT_HEX; 256];
68 let mut byte = 0;
69 while byte < 256 {
70 table[byte] = match byte as u8 {
71 digit @ b'0'..=b'9' => digit - b'0',
72 digit @ b'a'..=b'f' => digit - b'a' + 10,
73 digit @ b'A'..=b'F' => digit - b'A' + 10,
74 _ => NOT_HEX,
75 };
76 byte += 1;
77 }
78 table
79};
80const NOT_HEX: u8 = 0xff;
81
82const fn hex_digit(byte: u8) -> Option<u8> {
83 match HEX[byte as usize] {
84 NOT_HEX => None,
85 digit => Some(digit),
86 }
87}
88
89impl FromStr for Address {
90 type Err = BadAddress;
91
92 fn from_str(text: &str) -> Result<Self, Self::Err> {
93 let raw = text.trim();
94 Address::parse_const(raw).ok_or_else(|| BadAddress(raw.to_owned()))
95 }
96}
97
98impl fmt::Display for Address {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 f.write_str(&self.to_hex())
101 }
102}
103
104impl Serialize for Address {
105 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
106 serializer.collect_str(self)
107 }
108}
109
110impl<'de> Deserialize<'de> for Address {
111 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
112 let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
113 text.parse().map_err(de::Error::custom)
114 }
115}
116
117#[cfg(test)]
118#[path = "tests/address.rs"]
119mod tests;