Debian Codegraph @

debian/fontawesome.rs

raw
1 use std::{
2 collections::HashMap,
3 fmt::{self, Display, Formatter},
4 io::{self, Error, ErrorKind},
5 path::Path,
6 sync::{LazyLock, Mutex},
7 };
8
9 const FONTAWESOME_DIR: &str = "/usr/share/nodejs/@fortawesome/fontawesome-free/svgs";
10
11 static CACHE: LazyLock<Mutex<HashMap<(Type, String), &'static str>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
12
13 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
14 pub(crate) enum Type {
15 Brands,
16 Regular,
17 Solid,
18 }
19
20 impl Type {
21 fn as_str(self) -> &'static str {
22 match self {
23 Self::Brands => "brands",
24 Self::Regular => "regular",
25 Self::Solid => "solid",
26 }
27 }
28 }
29
30 impl Display for Type {
31 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32 write!(f, "{}", self.as_str())
33 }
34 }
35
36 impl std::str::FromStr for Type {
37 type Err = ();
38
39 fn from_str(value: &str) -> Result<Self, Self::Err> {
40 match value {
41 "brands" => Ok(Self::Brands),
42 "regular" => Ok(Self::Regular),
43 "solid" => Ok(Self::Solid),
44 _ => Err(()),
45 }
46 }
47 }
48
49 pub(crate) fn svg(type_: Type, name: &str) -> io::Result<&'static str> {
50 if name.is_empty() || !name.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') {
51 return Err(Error::new(ErrorKind::InvalidInput, "invalid FontAwesome icon name"));
52 }
53
54 let key = (type_, name.to_owned());
55 let mut cache = CACHE.lock().expect("FontAwesome cache poisoned");
56 if let Some(&svg) = cache.get(&key) {
57 return Ok(svg);
58 }
59
60 let path = Path::new(FONTAWESOME_DIR).join(type_.as_str()).join(format!("{name}.svg"));
61 let svg = std::fs::read_to_string(&path)
62 .map_err(|e| Error::new(e.kind(), format!("failed to read `{}`: {e:?}", path.display())))?;
63 let svg: &'static str = Box::leak(svg.into_boxed_str());
64 cache.insert(key, svg);
65 Ok(svg)
66 }