1use std::fmt;
8use std::str::FromStr;
9use std::time::Duration;
10
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12use sha2::{Digest, Sha256};
13
14use crate::encoding;
15
16pub const OPERATION_ID_MAX_LEN: usize = 64;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
21#[non_exhaustive]
22pub enum ParseIdError {
23 #[error("expected {expected} lowercase hex digits")]
25 InvalidHex {
26 expected: usize,
28 },
29 #[error("operation id is empty")]
31 Empty,
32 #[error("operation id is longer than {OPERATION_ID_MAX_LEN} characters")]
34 TooLong,
35 #[error("operation id may contain only A-Z, a-z, 0-9, '_' and '-'")]
37 InvalidCharacter,
38}
39
40macro_rules! hex_bytes_type {
44 ($name:ident, $len:literal) => {
45 impl $name {
46 pub const fn from_bytes(bytes: [u8; $len]) -> Self {
48 Self(bytes)
49 }
50
51 pub const fn as_bytes(&self) -> &[u8; $len] {
53 &self.0
54 }
55
56 pub fn to_hex(&self) -> String {
58 hex::encode(self.0)
59 }
60 }
61
62 impl From<[u8; $len]> for $name {
63 fn from(bytes: [u8; $len]) -> Self {
64 Self(bytes)
65 }
66 }
67
68 impl fmt::Display for $name {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.write_str(&self.to_hex())
71 }
72 }
73
74 impl fmt::Debug for $name {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 write!(f, concat!(stringify!($name), "({})"), self.to_hex())
77 }
78 }
79
80 impl FromStr for $name {
81 type Err = ParseIdError;
82
83 fn from_str(text: &str) -> Result<Self, Self::Err> {
85 encoding::decode_lower_hex::<$len>(text)
86 .map(Self)
87 .ok_or(ParseIdError::InvalidHex { expected: $len * 2 })
88 }
89 }
90
91 impl Serialize for $name {
92 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
93 serializer.serialize_str(&self.to_hex())
94 }
95 }
96
97 impl<'de> Deserialize<'de> for $name {
98 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
99 let text = String::deserialize(deserializer)?;
100 text.parse().map_err(serde::de::Error::custom)
101 }
102 }
103 };
104}
105
106#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
124pub struct EventId([u8; 32]);
125hex_bytes_type!(EventId, 32);
126
127#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
141pub struct Sha256Digest([u8; 32]);
142hex_bytes_type!(Sha256Digest, 32);
143
144impl Sha256Digest {
145 pub fn of(data: &[u8]) -> Self {
147 Self(Sha256::digest(data).into())
148 }
149}
150
151#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
169pub struct ChallengeId([u8; 16]);
170hex_bytes_type!(ChallengeId, 16);
171
172#[derive(
186 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
187)]
188#[serde(transparent)]
189pub struct Revision(u64);
190
191impl Revision {
192 pub const fn new(value: u64) -> Self {
194 Self(value)
195 }
196
197 pub const fn get(self) -> u64 {
199 self.0
200 }
201
202 pub const fn next(self) -> Option<Self> {
204 match self.0.checked_add(1) {
205 Some(value) => Some(Self(value)),
206 None => None,
207 }
208 }
209}
210
211impl From<u64> for Revision {
212 fn from(value: u64) -> Self {
213 Self(value)
214 }
215}
216
217impl From<Revision> for u64 {
218 fn from(revision: Revision) -> Self {
219 revision.0
220 }
221}
222
223impl fmt::Display for Revision {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 fmt::Display::fmt(&self.0, f)
226 }
227}
228
229#[derive(
244 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
245)]
246#[serde(transparent)]
247pub struct UnixTime(u64);
248
249impl UnixTime {
250 pub const fn from_secs(secs: u64) -> Self {
252 Self(secs)
253 }
254
255 pub const fn as_secs(self) -> u64 {
257 self.0
258 }
259
260 pub const fn checked_add(self, duration: Duration) -> Option<Self> {
263 match self.0.checked_add(duration.as_secs()) {
264 Some(secs) => Some(Self(secs)),
265 None => None,
266 }
267 }
268
269 pub const fn abs_diff(self, other: Self) -> u64 {
271 self.0.abs_diff(other.0)
272 }
273}
274
275impl From<u64> for UnixTime {
276 fn from(secs: u64) -> Self {
277 Self(secs)
278 }
279}
280
281impl From<UnixTime> for u64 {
282 fn from(time: UnixTime) -> Self {
283 time.0
284 }
285}
286
287impl fmt::Display for UnixTime {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 fmt::Display::fmt(&self.0, f)
290 }
291}
292
293#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
311pub struct OperationId(String);
312
313impl OperationId {
314 pub fn as_str(&self) -> &str {
316 &self.0
317 }
318
319 fn validate(text: &str) -> Result<(), ParseIdError> {
321 if text.is_empty() {
322 return Err(ParseIdError::Empty);
323 }
324 if text.len() > OPERATION_ID_MAX_LEN {
325 return Err(ParseIdError::TooLong);
326 }
327 if !text
328 .bytes()
329 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
330 {
331 return Err(ParseIdError::InvalidCharacter);
332 }
333 Ok(())
334 }
335}
336
337impl FromStr for OperationId {
338 type Err = ParseIdError;
339
340 fn from_str(text: &str) -> Result<Self, Self::Err> {
341 Self::validate(text)?;
342 Ok(Self(text.to_owned()))
343 }
344}
345
346impl TryFrom<String> for OperationId {
347 type Error = ParseIdError;
348
349 fn try_from(text: String) -> Result<Self, Self::Error> {
350 Self::validate(&text)?;
351 Ok(Self(text))
352 }
353}
354
355impl AsRef<str> for OperationId {
356 fn as_ref(&self) -> &str {
357 &self.0
358 }
359}
360
361impl fmt::Display for OperationId {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.write_str(&self.0)
364 }
365}
366
367impl Serialize for OperationId {
368 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
369 serializer.serialize_str(&self.0)
370 }
371}
372
373impl<'de> Deserialize<'de> for OperationId {
374 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
375 let text = String::deserialize(deserializer)?;
376 Self::try_from(text).map_err(serde::de::Error::custom)
377 }
378}