cargo_graphmod/formatter/
colors.rs

1/**
2 * Copyright 2023 Thomas Hügel.
3 * This file is part of Cargo Graphmod.
4 * SPDX-License-Identifier: GPL-3.0-only
5 */
6
7pub fn make_gray(level: usize) -> String {
8    let l = if level > 16 { 0 } else { 15 - level } as u32;
9    let c = String::from(char::from_digit(l, 16).unwrap_or('f')).repeat(2);
10    String::from("#") + &c.repeat(3)
11}
12
13pub fn make_random_color(dirname: &str) -> String {
14    let n = dirname.chars().filter_map(|c| c.to_digit(36)).sum::<u32>() + 4;
15    let red = (255 - n * 71 % 128) as u8;
16    let green = (255 - n * 131 % 128) as u8;
17    let blue = (255 - n * 29 % 128) as u8;
18    let number = u32::from_be_bytes([0, red, green, blue]);
19    let hexadecimal = format!("{:#08x}", number);
20    String::from("#") + &hexadecimal.chars().skip(2).collect::<String>()
21}
22
23#[cfg(test)]
24mod tests {
25    use crate::formatter::colors::{make_gray, make_random_color};
26
27    #[test]
28    fn it_makes_gray() {
29        assert_eq!(String::from("#dddddd"), make_gray(2))
30    }
31
32    #[test]
33    fn it_makes_a_random_color() {
34        assert_eq!(String::from("#9aa6f8"), make_random_color("::foo::bar"))
35    }
36}