1#[macro_export]
3macro_rules! generate_id_type {
4 ($struct_name:ident) => {
5 #[derive(Hash, Clone, Copy, Debug, PartialEq, Eq)]
6 #[cfg_attr(feature = "serde-support", derive(serde::Serialize))]
7 pub struct $struct_name(u16);
8 impl $struct_name {
9 pub fn new(val: u16) -> Self {
10 $struct_name(val)
11 }
12 pub fn val(&self) -> u16 {
13 self.0
14 }
15 }
16 impl std::fmt::Display for $struct_name {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 write!(f, "{}", self.0)
19 }
20 }
21 impl std::str::FromStr for $struct_name {
22 type Err = IdError<$struct_name>;
23
24 fn from_str(s: &str) -> Result<Self, Self::Err> {
25 let val = s.parse::<u16>().map_err(|_e| IdError::CannotParse(s.to_owned()))?;
26 Ok(Self::new(val))
27 }
28 }
29
30 impl std::default::Default for $struct_name {
31 fn default() -> Self {
32 Self::new(0)
33 }
34 }
35 };
36}
37
38#[cfg(test)]
39mod tests {
40 use crate::IdError;
41 use stepflow_test_util::test_id;
42
43 generate_id_type!(TestId);
44
45 #[test]
46 fn new_id() {
47 let test_id = TestId::new(10);
48
49 assert_eq!(test_id.val(), 10);
51 assert_ne!(test_id.val(), TestId::new(15).val());
52 }
53
54 #[test]
55 fn test_testid() {
56 let test_id1: TestId = test_id!(TestId);
57 let test_id2: TestId = test_id!(TestId);
58 assert_ne!(test_id1.val(), test_id2.val());
59 }
60
61 #[test]
62 fn from_str() {
63 let test_id = "48".parse::<TestId>().unwrap();
64 assert_eq!(test_id, TestId::new(48));
65 }
66}
67