Skip to content

Commit

Permalink
feat: add const equivalents of color & flavor index impls (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
backwardspy authored Mar 18, 2024
1 parent 10fb0c5 commit a13db45
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
18 changes: 16 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,22 @@ fn make_colorname_index_impl<W: Write>(
{}
}}
}}
}}
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(())
}
Expand Down Expand Up @@ -245,7 +259,7 @@ fn make_colorname_fromstr_impl<W: Write>(
let match_arms = sample_flavor
.colors
.keys()
.map(|name| format!("{:?} => Ok(ColorName::{}),", name, titlecase(name)))
.map(|name| format!("{:?} => Ok(Self::{}),", name, titlecase(name)))
.collect::<Vec<_>>();
writeln!(
w,
Expand Down
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,22 @@ impl Index<FlavorName> 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;
Expand Down Expand Up @@ -400,6 +416,17 @@ impl Index<ColorName> 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 [`<color>.name.identifier()`](ColorName::identifier).
#[must_use]
Expand Down

0 comments on commit a13db45

Please sign in to comment.