Skip to content

Commit

Permalink
Use hex values in languages.yaml
Browse files Browse the repository at this point in the history
  • Loading branch information
spenserblack committed Jul 7, 2022
1 parent c745b64 commit 9f02ad7
Show file tree
Hide file tree
Showing 4 changed files with 351 additions and 303 deletions.
32 changes: 32 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let out_dir = env::var("OUT_DIR").unwrap();
let mut tera = Tera::new("src/**/*.tera.rs")?;
tera.register_filter("strip_color_indices", strip_color_indices);
tera.register_filter("hextorgb", hex_to_rgb);

let lang_data: serde_json::Value = serde_yaml::from_reader(File::open("languages.yaml")?)?;
let context = Context::from_value(serde_json::json!({
Expand Down Expand Up @@ -41,3 +42,34 @@ fn strip_color_indices(
COLOR_INDEX_REGEX.replace_all(s, "").to_string(),
));
}

/// Converts a hex string to an object with keys `r`, `g`, `b`.
fn hex_to_rgb(
value: &tera::Value,
_args: &HashMap<String, tera::Value>,
) -> tera::Result<tera::Value> {
let hex_string = match value {
tera::Value::String(s) => s,
_ => return Err(tera::Error::msg("expected string")),
};
let hex_string = match hex_string.strip_prefix("#") {
Some(s) => s,
None => return Err(tera::Error::msg("expected hex string starting with `#`")),
};
if hex_string.len() != 6 {
return Err(tera::Error::msg("expected a 6 digit hex string"));
}
let channel_bytes = match u32::from_str_radix(&hex_string, 16) {
Ok(n) => n,
Err(_) => return Err(tera::Error::msg("expected a valid hex string")),
};
let r = (channel_bytes >> 16) & 0xFF;
let g = (channel_bytes >> 8) & 0xFF;
let b = channel_bytes & 0xFF;

Ok(serde_json::json!({
"r": r,
"g": g,
"b": b,
}))
}
Loading

0 comments on commit 9f02ad7

Please sign in to comment.