Skip to main content

ferroui_base/media/
known_color_brushes.rs

1//! The brush lookups of the known colors.
2
3use crate::media::immutable::ImmutableSolidColorBrush;
4use crate::media::{KnownColor, KnownColors};
5use std::cell::RefCell;
6use std::collections::HashMap;
7use std::rc::Rc;
8
9crate::ferro_thread_local! {
10    static KNOWN_BRUSHES: RefCell<HashMap<u32, Rc<ImmutableSolidColorBrush>>> = RefCell::new(HashMap::new());
11}
12
13impl KnownColor {
14    /// Converts the known color to a solid color brush.
15    ///
16    /// Brushes created from known colors are cached and reused for
17    /// efficiency.
18    pub fn to_brush(self) -> Rc<ImmutableSolidColorBrush> {
19        KNOWN_BRUSHES.with(|brushes| {
20            brushes
21                .borrow_mut()
22                .entry(self.value())
23                .or_insert_with(|| Rc::new(ImmutableSolidColorBrush::new(self.to_color())))
24                .clone()
25        })
26    }
27}
28
29impl KnownColors {
30    /// Gets the cached brush of the known color with the given name (ASCII
31    /// case-insensitive), or `None` when there is no such color.
32    pub fn get_known_brush(s: &str) -> Option<Rc<ImmutableSolidColorBrush>> {
33        let color = KnownColors::get_known_color(s);
34        if color != KnownColor::NONE {
35            Some(color.to_brush())
36        } else {
37            None
38        }
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use crate::media::Colors;
46
47    #[test]
48    fn known_brushes_are_cached() {
49        let a = KnownColor::RED.to_brush();
50        let b = KnownColors::get_known_brush("red").unwrap();
51        assert!(Rc::ptr_eq(&a, &b));
52        assert_eq!(Colors::RED, a.color());
53        assert!(KnownColors::get_known_brush("NotAColor").is_none());
54        // Aliases share one brush.
55        assert!(Rc::ptr_eq(&KnownColor::AQUA.to_brush(), &KnownColor::CYAN.to_brush()));
56    }
57}