anvil_core/eth/
subscription.rs1use alloy_primitives::hex;
3use rand::{Rng, distr::Alphanumeric, 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 generate(&self) -> String {
50 let id: String =
51 (&mut rng()).sample_iter(Alphanumeric).map(char::from).take(self.len).collect();
52 hex::encode_prefixed(id)
53 }
54}
55
56impl Default for HexIdProvider {
57 fn default() -> Self {
58 Self { len: 16 }
59 }
60}
61
62pub fn hex_id() -> String {
64 HexIdProvider::default().generate()
65}