use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
macro_rules! id_type {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct $name(String);
impl $name {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for $name {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.to_owned()))
}
}
};
}
id_type!(
ContestId
);
id_type!(
TaskId
);
id_type!(
SolutionId
);
id_type!(
CaseId
);
id_type!(
TestRunId
);
id_type!(
SubmissionId
);
id_type!(
PracticeAttemptId
);
impl TaskId {
#[must_use]
pub fn for_problem(contest: &ContestId, label: &str) -> Self {
Self(format!("{contest}_{label}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn task_id_builds_from_contest_and_label() {
let contest = ContestId::new("abc351");
let task = TaskId::for_problem(&contest, "c");
assert_eq!(task.as_str(), "abc351_c");
assert_eq!(task.to_string(), "abc351_c");
}
#[test]
fn ids_roundtrip_through_string() {
let id = SolutionId::new("sol-1");
let parsed: SolutionId = "sol-1".parse().expect("infallible parse");
assert_eq!(parsed, id);
}
}