ferroui_base/media/
known_color_brushes.rs1use 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 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 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 assert!(Rc::ptr_eq(&KnownColor::AQUA.to_brush(), &KnownColor::CYAN.to_brush()));
56 }
57}