From a13db45c173b91e0df13acdf1c562889870c1a16 Mon Sep 17 00:00:00 2001 From: backwardspy Date: Mon, 18 Mar 2024 22:42:34 +0000 Subject: [PATCH] feat: add const equivalents of color & flavor index impls (#18) --- build.rs | 18 ++++++++++++++++-- src/lib.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/build.rs b/build.rs index 1c5cd02..9b9ef6f 100644 --- a/build.rs +++ b/build.rs @@ -174,8 +174,22 @@ fn make_colorname_index_impl( {} }} }} +}} + +impl FlavorColors {{ + /// Get a color by name. + /// + /// This is equivalent to using the index operator, but can also be used in + /// const contexts. + #[must_use] + pub const fn get_color(&self, name: ColorName) -> &Color {{ + match name {{ + {} + }} + }} }}", - match_arms.join("\n ") + match_arms.join("\n "), + match_arms.join("\n "), )?; Ok(()) } @@ -245,7 +259,7 @@ fn make_colorname_fromstr_impl( let match_arms = sample_flavor .colors .keys() - .map(|name| format!("{:?} => Ok(ColorName::{}),", name, titlecase(name))) + .map(|name| format!("{:?} => Ok(Self::{}),", name, titlecase(name))) .collect::>(); writeln!( w, diff --git a/src/lib.rs b/src/lib.rs index 2a2ef2c..70f4341 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -203,6 +203,22 @@ impl Index for Palette { } } +impl Palette { + /// Get a flavor by name. + /// + /// This is equivalent to using the index operator, but can also be used in + /// const contexts. + #[must_use] + pub const fn get_flavor(&self, name: FlavorName) -> &Flavor { + match name { + FlavorName::Latte => &self.latte, + FlavorName::Frappe => &self.frappe, + FlavorName::Macchiato => &self.macchiato, + FlavorName::Mocha => &self.mocha, + } + } +} + impl fmt::Display for Hex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Rgb { r, g, b } = self.0; @@ -400,6 +416,17 @@ impl Index for Flavor { } } +impl Flavor { + /// Get a color by name. + /// + /// This is equivalent to using the index operator, but can also be used in + /// const contexts. + #[must_use] + pub const fn get_color(&self, name: ColorName) -> &Color { + self.colors.get_color(name) + } +} + impl Color { /// Equivalent to [`.name.identifier()`](ColorName::identifier). #[must_use]