1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
use std::cmp::Ordering; use std::convert::Infallible; use std::fmt; use std::hash::{Hash, Hasher}; use std::str::FromStr; use getset::Getters; use serde::{Deserialize, Serialize}; use crate::regex; pub static DEFAULT_CONTEST_ID_STR: &str = "arc100"; static DEFAULT_CONTEST_NAME_STR: &str = "AtCoder Regular Contest 100"; #[derive(Serialize, Deserialize, Getters, Debug, Clone, PartialEq, Eq, Hash)] #[get = "pub"] pub struct Contest { id: ContestId, name: String, } impl Contest { pub fn new(id: impl Into<ContestId>, name: impl Into<String>) -> Self { Self { id: id.into(), name: name.into(), } } } impl Default for Contest { fn default() -> Self { Self::new(DEFAULT_CONTEST_ID_STR, DEFAULT_CONTEST_NAME_STR) } } #[derive(Serialize, Deserialize, Debug, Clone, Eq)] pub struct ContestId(String); impl ContestId { pub fn normalize(&self) -> String { regex!(r"[-_]").replace_all(&self.0, "").to_lowercase() } } impl Default for ContestId { fn default() -> Self { Self::from(DEFAULT_CONTEST_ID_STR) } } impl PartialEq<ContestId> for ContestId { fn eq(&self, other: &ContestId) -> bool { self.normalize() == other.normalize() } } impl PartialOrd for ContestId { fn partial_cmp(&self, other: &ContestId) -> Option<Ordering> { Some(self.normalize().cmp(&other.normalize())) } } impl Ord for ContestId { fn cmp(&self, other: &Self) -> Ordering { self.normalize().cmp(&other.normalize()) } } impl Hash for ContestId { fn hash<H: Hasher>(&self, state: &mut H) { self.normalize().hash(state); } } impl<T: Into<String>> From<T> for ContestId { fn from(id: T) -> Self { Self(id.into()) } } impl FromStr for ContestId { type Err = Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(Self::from(s)) } } impl AsRef<str> for ContestId { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for ContestId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0) } } #[cfg(test)] mod tests { use super::*; #[test] fn contest_id_eq() { assert_eq!(ContestId::from("arc100"), ContestId::from("arc100")); assert_eq!(ContestId::from("ARC100"), ContestId::from("arc100")); assert_eq!( ContestId::from("CodeFestival2017QualA"), ContestId::from("code-festival-2017-quala"), ); } #[test] fn test_contest_id_display() { assert_eq!(&ContestId::from("arc100").to_string(), "arc100"); assert_eq!(&ContestId::from("ARC100").to_string(), "ARC100"); assert_eq!( &ContestId::from("code-festival-2017-quala").to_string(), "code-festival-2017-quala" ); } }