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