OXYGENHUB
# 5f3fa151688e oxygenhub / crates / hub / src / render / mod.rs
1.4 KiB · Rust · last changed Cache rendered Markdown and highlighted files by content, in memory-bounded LRUs 1 month ago source blame history raw
1
//! Rendering helpers with no knowledge of routes: Markdown, syntax
2
//! highlighting, diffs, the history graph, and human times. Each is pure
3
//! and unit tested.
4
5
pub mod cache;
6
pub mod diff;
7
pub mod graph;
8
pub mod highlight;
9
pub mod markdown;
10
pub mod refs;
11
pub mod time;
12
13
/// HTML-escape text for insertion into element content or attributes.
14
pub fn escape(s: &str) -> String {
15
    let mut out = String::with_capacity(s.len());
16
    for c in s.chars() {
17
        match c {
18
            '&' => out.push_str("&"),
19
            '<' => out.push_str("&lt;"),
20
            '>' => out.push_str("&gt;"),
21
            '"' => out.push_str("&quot;"),
22
            '\'' => out.push_str("&#39;"),
23
            _ => out.push(c),
24
        }
25
    }
26
    out
27
}
28
29
/// `1.2 KiB`, `3.4 MiB`, `512 B`.
30
pub fn bytes(n: u64) -> String {
31
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
32
    let mut v = n as f64;
33
    let mut i = 0;
34
    while v >= 1024.0 && i < UNITS.len() - 1 {
35
        v /= 1024.0;
36
        i += 1;
37
    }
38
    if i == 0 {
39
        format!("{n} B")
40
    } else {
41
        format!("{v:.1} {}", UNITS[i])
42
    }
43
}
44
45
#[cfg(test)]
46
mod tests {
47
    use super::*;
48
49
    #[test]
50
    fn escaping_and_sizes() {
51
        assert_eq!(escape("<a href=\"x\">&'"), "&lt;a href=&quot;x&quot;&gt;&amp;&#39;");
52
        assert_eq!(bytes(512), "512 B");
53
        assert_eq!(bytes(1536), "1.5 KiB");
54
        assert_eq!(bytes(5 << 20), "5.0 MiB");
55
    }
56
}