ac-algorithm 0.2.0

Algorithm competition domain logic for ac
Documentation
//! Identifier types for the Algorithm domain.
//!
//! IDs are opaque strings: their format is an implementation detail and they
//! serialize as plain strings for IPC and persistence.

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 {
            /// Creates an identifier from its string form.
            #[must_use]
            pub fn new(id: impl Into<String>) -> Self {
                Self(id.into())
            }

            /// Returns the identifier as a string slice.
            #[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!(
    /// Identifier of an `AtCoder` contest (e.g. `abc351`).
    ContestId
);
id_type!(
    /// Identifier of a single problem within a contest (e.g. `abc351_c`).
    TaskId
);
id_type!(
    /// Identifier of a solution snapshot.
    SolutionId
);
id_type!(
    /// Identifier of a test case.
    CaseId
);
id_type!(
    /// Identifier of a local test run.
    TestRunId
);
id_type!(
    /// Identifier of a submission intent/result record.
    SubmissionId
);
id_type!(
    /// Identifier of a practice attempt.
    PracticeAttemptId
);

impl TaskId {
    /// Builds a task identifier from contest and problem label, matching the
    /// `<contest>_<label>` form used by `AtCoder` task pages.
    #[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);
    }
}