1use std::fmt;
7use std::str::FromStr;
8
9use serde::{Deserialize, Serialize};
10
11macro_rules! id_type {
12 ($(#[$meta:meta])* $name:ident) => {
13 $(#[$meta])*
14 #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15 pub struct $name(String);
16
17 impl $name {
18 #[must_use]
20 pub fn new(id: impl Into<String>) -> Self {
21 Self(id.into())
22 }
23
24 #[must_use]
26 pub fn as_str(&self) -> &str {
27 &self.0
28 }
29 }
30
31 impl fmt::Display for $name {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.write_str(&self.0)
34 }
35 }
36
37 impl FromStr for $name {
38 type Err = std::convert::Infallible;
39
40 fn from_str(s: &str) -> Result<Self, Self::Err> {
41 Ok(Self(s.to_owned()))
42 }
43 }
44 };
45}
46
47id_type!(
48 ContestId
50);
51id_type!(
52 TaskId
54);
55id_type!(
56 SolutionId
58);
59id_type!(
60 CaseId
62);
63id_type!(
64 TestRunId
66);
67id_type!(
68 SubmissionId
70);
71id_type!(
72 PracticeAttemptId
74);
75
76impl TaskId {
77 #[must_use]
80 pub fn for_problem(contest: &ContestId, label: &str) -> Self {
81 Self(format!("{contest}_{label}"))
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn task_id_builds_from_contest_and_label() {
91 let contest = ContestId::new("abc351");
92 let task = TaskId::for_problem(&contest, "c");
93 assert_eq!(task.as_str(), "abc351_c");
94 assert_eq!(task.to_string(), "abc351_c");
95 }
96
97 #[test]
98 fn ids_roundtrip_through_string() {
99 let id = SolutionId::new("sol-1");
100 let parsed: SolutionId = "sol-1".parse().expect("infallible parse");
101 assert_eq!(parsed, id);
102 }
103}