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