Skip to main content

ac_algorithm/
ids.rs

1//! Identifier types for the Algorithm domain.
2//!
3//! IDs are opaque strings: their format is an implementation detail and they
4//! serialize as plain strings for IPC and persistence.
5
6use 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            /// Creates an identifier from its string form.
19            #[must_use]
20            pub fn new(id: impl Into<String>) -> Self {
21                Self(id.into())
22            }
23
24            /// Returns the identifier as a string slice.
25            #[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    /// Identifier of an `AtCoder` contest (e.g. `abc351`).
49    ContestId
50);
51id_type!(
52    /// Identifier of a single problem within a contest (e.g. `abc351_c`).
53    TaskId
54);
55id_type!(
56    /// Identifier of a solution snapshot.
57    SolutionId
58);
59id_type!(
60    /// Identifier of a test case.
61    CaseId
62);
63id_type!(
64    /// Identifier of a local test run.
65    TestRunId
66);
67id_type!(
68    /// Identifier of a submission intent/result record.
69    SubmissionId
70);
71id_type!(
72    /// Identifier of a practice attempt.
73    PracticeAttemptId
74);
75
76impl TaskId {
77    /// Builds a task identifier from contest and problem label, matching the
78    /// `<contest>_<label>` form used by `AtCoder` task pages.
79    #[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}