OXYGENHUB
# de505df5cf8d oxygenhub / crates / hub / src / render / mod.rs
1.4 KiB · Rust · last changed Milestone 0.1: browse 1 month ago source blame history raw
d23464c0 Andy McCall ↶ 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 diff;
6
pub mod graph;
7
pub mod highlight;
8
pub mod markdown;
9
pub mod time;
10
11
/// HTML-escape text for insertion into element content or attributes.
12
pub fn escape(s: &str) -> String {
13
    let mut out = String::with_capacity(s.len());
14
    for c in s.chars() {
15
        match c {
16
            '&' => out.push_str("&"),
17
            '<' => out.push_str("&lt;"),
18
            '>' => out.push_str("&gt;"),
19
            '"' => out.push_str("&quot;"),
20
            '\'' => out.push_str("&#39;"),
21
            _ => out.push(c),
22
        }
23
    }
24
    out
25
}
26
27
/// `1.2 KiB`, `3.4 MiB`, `512 B`.
28
pub fn bytes(n: u64) -> String {
29
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
30
    let mut v = n as f64;
31
    let mut i = 0;
32
    while v >= 1024.0 && i < UNITS.len() - 1 {
33
        v /= 1024.0;
34
        i += 1;
35
    }
36
    if i == 0 {
37
        format!("{n} B")
38
    } else {
39
        format!("{v:.1} {}", UNITS[i])
40
    }
41
}
42
43
#[cfg(test)]
44
mod tests {
45
    use super::*;
46
47
    #[test]
48
    fn escaping_and_sizes() {
49
        assert_eq!(escape("<a href=\"x\">&'"), "&lt;a href=&quot;x&quot;&gt;&amp;&#39;");
50
        assert_eq!(bytes(512), "512 B");
51
        assert_eq!(bytes(1536), "1.5 KiB");
52
        assert_eq!(bytes(5 << 20), "5.0 MiB");
53
    }
54
}