anvil_core/eth/
subscription.rs
1use alloy_primitives::hex;
3use rand::{distributions::Alphanumeric, thread_rng, Rng};
4use std::fmt;
5
6#[derive(Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
8#[serde(untagged)]
9pub enum SubscriptionId {
10 Number(u64),
12 String(String),
14}
15
16impl SubscriptionId {
17 pub fn random_hex() -> Self {
19 Self::String(hex_id())
20 }
21}
22
23impl fmt::Display for SubscriptionId {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 match self {
26 Self::Number(num) => num.fmt(f),
27 Self::String(s) => s.fmt(f),
28 }
29 }
30}
31
32impl fmt::Debug for SubscriptionId {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 match self {
35 Self::Number(num) => num.fmt(f),
36 Self::String(s) => s.fmt(f),
37 }
38 }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct HexIdProvider {
44 len: usize,
45}
46
47impl HexIdProvider {
48 pub fn gen(&self) -> String {
50 let id: String =
51 (&mut thread_rng()).sample_iter(Alphanumeric).map(char::from).take(self.len).collect();
52 let out = hex::encode(id);
53 format!("0x{out}")
54 }
55}
56
57impl Default for HexIdProvider {
58 fn default() -> Self {
59 Self { len: 16 }
60 }
61}
62
63pub fn hex_id() -> String {
65 HexIdProvider::default().gen()
66}