1use crate::PayloadSort;
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub struct Label {
32 pub name: String,
34 #[serde(default)]
36 pub sort: PayloadSort,
37}
38
39impl Label {
40 #[must_use]
42 pub fn new(name: impl Into<String>) -> Self {
43 Self {
44 name: name.into(),
45 sort: PayloadSort::Unit,
46 }
47 }
48
49 #[must_use]
51 pub fn with_sort(name: impl Into<String>, sort: PayloadSort) -> Self {
52 Self {
53 name: name.into(),
54 sort,
55 }
56 }
57
58 #[must_use]
60 pub fn matches(&self, other: &Label) -> bool {
61 self == other
62 }
63
64 #[must_use]
66 pub fn matches_name(&self, name: &str) -> bool {
67 self.name == name
68 }
69}
70
71impl std::fmt::Display for Label {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 write!(f, "{}", self.name)?;
74 if self.sort != PayloadSort::Unit {
75 write!(f, "({})", self.sort)?;
76 }
77 Ok(())
78 }
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn test_label_new() {
87 let label = Label::new("hello");
88 assert_eq!(label.name, "hello");
89 assert_eq!(label.sort, PayloadSort::Unit);
90 }
91
92 #[test]
93 fn test_label_with_sort() {
94 let label = Label::with_sort("data", PayloadSort::Nat);
95 assert_eq!(label.name, "data");
96 assert_eq!(label.sort, PayloadSort::Nat);
97 }
98
99 #[test]
100 fn test_label_matches() {
101 let l1 = Label::new("msg");
102 let l2 = Label::with_sort("msg", PayloadSort::Bool);
103 let l3 = Label::new("other");
104 let l4 = Label::new("msg");
105
106 assert!(!l1.matches(&l2)); assert!(!l1.matches(&l3)); assert!(l1.matches(&l4)); assert!(l1.matches_name("msg")); }
111
112 #[test]
113 fn test_label_display() {
114 let unit_label = Label::new("hello");
115 assert_eq!(format!("{}", unit_label), "hello");
116
117 let typed_label = Label::with_sort("data", PayloadSort::Nat);
118 assert_eq!(format!("{}", typed_label), "data(Nat)");
119 }
120}