use crate::PayloadSort;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Label {
pub name: String,
#[serde(default)]
pub sort: PayloadSort,
}
impl Label {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
sort: PayloadSort::Unit,
}
}
#[must_use]
pub fn with_sort(name: impl Into<String>, sort: PayloadSort) -> Self {
Self {
name: name.into(),
sort,
}
}
#[must_use]
pub fn matches(&self, other: &Label) -> bool {
self == other
}
#[must_use]
pub fn matches_name(&self, name: &str) -> bool {
self.name == name
}
}
impl std::fmt::Display for Label {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)?;
if self.sort != PayloadSort::Unit {
write!(f, "({})", self.sort)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_label_new() {
let label = Label::new("hello");
assert_eq!(label.name, "hello");
assert_eq!(label.sort, PayloadSort::Unit);
}
#[test]
fn test_label_with_sort() {
let label = Label::with_sort("data", PayloadSort::Nat);
assert_eq!(label.name, "data");
assert_eq!(label.sort, PayloadSort::Nat);
}
#[test]
fn test_label_matches() {
let l1 = Label::new("msg");
let l2 = Label::with_sort("msg", PayloadSort::Bool);
let l3 = Label::new("other");
let l4 = Label::new("msg");
assert!(!l1.matches(&l2)); assert!(!l1.matches(&l3)); assert!(l1.matches(&l4)); assert!(l1.matches_name("msg")); }
#[test]
fn test_label_display() {
let unit_label = Label::new("hello");
assert_eq!(format!("{}", unit_label), "hello");
let typed_label = Label::with_sort("data", PayloadSort::Nat);
assert_eq!(format!("{}", typed_label), "data(Nat)");
}
}