From 07f272073a935cf603e8786e3c344681f1c9c43b Mon Sep 17 00:00:00 2001 From: Joscha Date: Fri, 2 Dec 2022 12:56:27 +0100 Subject: [PATCH] [rs] Use macros to specify days --- rs/src/main.rs | 44 ++++++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/rs/src/main.rs b/rs/src/main.rs index f9d1d59..f041859 100644 --- a/rs/src/main.rs +++ b/rs/src/main.rs @@ -6,8 +6,28 @@ use std::{fmt, fs}; use clap::Parser; -enum Day { - Y2022D01, +macro_rules! days { + ( $( $day:ident : $name:expr, )* ) => { + enum Day { $( $day, )* } + + impl fmt::Display for Day{ + fn fmt(&self, f:&mut fmt::Formatter<'_>) -> fmt::Result { + match self { + $( Self::$day => $name, )* + }.fmt(f) + } + } + + impl FromStr for Day { + type Err = (); + fn from_str(s: &str) -> Result { + Ok(match s { + $( $name => Self::$day, )* + _ => return Err(()), + }) + } + } + }; } impl Day { @@ -16,24 +36,8 @@ impl Day { } } -impl fmt::Display for Day { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Day::Y2022D01 => "2022_01", - } - .fmt(f) - } -} - -impl FromStr for Day { - type Err = (); - - fn from_str(s: &str) -> Result { - Ok(match s { - "2022_01" => Self::Y2022D01, - _ => return Err(()), - }) - } +days! { + Y2022D01: "2022_01", } #[derive(Parser)]