workflow_core/
id.rs

1//!
2//! 64-bit random identifier struct [`Id`] that renders its value as a base58 string
3//!
4
5use borsh::{BorshDeserialize, BorshSerialize};
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use std::{fmt, str::FromStr};
8use thiserror::Error;
9use wasm_bindgen::JsValue;
10
11#[derive(Error, Debug)]
12pub enum Error {
13    #[error("Base58 decode error: {0}")]
14    Base58Decode(#[from] bs58::decode::Error),
15    #[error("Invalid buffer size")]
16    InvalidBufferSize,
17    #[error("Unable to decode id: JsValue must be a string")]
18    JsValueNotString,
19}
20
21/// 64-bit identifier that renders the value as a base58 string.
22/// This struct is useful for general-purpose random id generation
23/// for use with DOM elements and for other similar purposes.
24#[repr(transparent)]
25#[derive(
26    Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd, BorshSerialize, BorshDeserialize,
27)]
28pub struct Id(pub(crate) [u8; 8]);
29
30impl Id {
31    pub fn new() -> Id {
32        Id::new_from_slice(&rand::random::<[u8; 8]>())
33    }
34
35    pub fn new_from_slice(vec: &[u8]) -> Self {
36        Self(<[u8; 8]>::try_from(<&[u8]>::clone(&vec)).expect("Error: invalid slice size for id"))
37    }
38
39    pub fn to_bytes(self) -> [u8; 8] {
40        self.0
41    }
42}
43
44impl From<Id> for String {
45    fn from(id: Id) -> Self {
46        id.to_string()
47    }
48}
49
50impl AsRef<[u8]> for Id {
51    fn as_ref(&self) -> &[u8] {
52        &self.0[..]
53    }
54}
55
56impl AsMut<[u8]> for Id {
57    fn as_mut(&mut self) -> &mut [u8] {
58        &mut self.0[..]
59    }
60}
61
62impl fmt::Debug for Id {
63    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64        write!(f, "{}", bs58::encode(self.0).into_string())
65    }
66}
67
68impl fmt::Display for Id {
69    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70        write!(f, "{}", bs58::encode(self.0).into_string())
71    }
72}
73
74impl FromStr for Id {
75    type Err = Error;
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        if s.len() > std::mem::size_of::<Id>() * 2 {
79            return Err(Error::InvalidBufferSize);
80        }
81        let vec = bs58::decode(s).into_vec()?;
82        if vec.len() != std::mem::size_of::<Id>() {
83            Err(Error::InvalidBufferSize)
84        } else {
85            Ok(Id::new_from_slice(&vec))
86        }
87    }
88}
89
90impl TryFrom<&str> for Id {
91    type Error = Error;
92    fn try_from(s: &str) -> Result<Self, Self::Error> {
93        Id::from_str(s)
94    }
95}
96
97impl TryFrom<JsValue> for Id {
98    type Error = Error;
99    fn try_from(value: JsValue) -> Result<Self, Self::Error> {
100        let value_str = value.as_string().ok_or(Error::JsValueNotString)?;
101        FromStr::from_str(&value_str)
102    }
103}
104
105impl From<Id> for JsValue {
106    fn from(id: Id) -> Self {
107        JsValue::from_str(&id.to_string())
108    }
109}
110
111impl Serialize for Id {
112    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
113    where
114        S: Serializer,
115    {
116        serializer.serialize_str(&self.to_string())
117    }
118}
119
120impl<'de> Deserialize<'de> for Id {
121    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122    where
123        D: Deserializer<'de>,
124    {
125        let s = <std::string::String as Deserialize>::deserialize(deserializer)?;
126        FromStr::from_str(&s).map_err(serde::de::Error::custom)
127    }
128}