flexpool_core/
portfolio.rs1use std::fmt;
6
7use serde::{Deserialize, Serialize};
8
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
11#[error("{kind} id {value:?} must match [a-z0-9-]{{1,64}}")]
12pub struct IdError {
13 kind: &'static str,
14 value: String,
15}
16
17fn is_slug(value: &str) -> bool {
18 (1..=64).contains(&value.len())
19 && value
20 .bytes()
21 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
22}
23
24macro_rules! id {
25 ($(#[$meta:meta])* $name:ident, $kind:literal) => {
26 $(#[$meta])*
27 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
28 #[serde(try_from = "String", into = "String")]
29 pub struct $name(String);
30
31 impl $name {
32 pub fn parse(value: impl Into<String>) -> Result<Self, IdError> {
37 let value = value.into();
38 if is_slug(&value) {
39 Ok(Self(value))
40 } else {
41 Err(IdError { kind: $kind, value })
42 }
43 }
44
45 #[must_use]
47 pub fn as_str(&self) -> &str {
48 &self.0
49 }
50 }
51
52 impl TryFrom<String> for $name {
53 type Error = IdError;
54 fn try_from(value: String) -> Result<Self, IdError> {
55 Self::parse(value)
56 }
57 }
58
59 impl From<$name> for String {
60 fn from(id: $name) -> String {
61 id.0
62 }
63 }
64
65 impl fmt::Display for $name {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 f.write_str(&self.0)
68 }
69 }
70 };
71}
72
73id!(
74 AssetId,
76 "asset"
77);
78id!(
79 SliceId,
81 "slice"
82);
83id!(
84 TechnicalUnitId,
86 "technical unit"
87);
88id!(
89 ReserveGroupId,
91 "reserve group"
92);
93id!(
94 PoolId,
96 "pool"
97);
98id!(
99 OwnerId,
101 "owner"
102);
103id!(
104 ProductId,
106 "product"
107);