OXYGENHUB

Coverage / crates/hub/src/render/mod.rs 100.0%

29 of 29 lines run, 5 of 5 functions · run #474 on main · run missed

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.
1435×
pub fn escape(s: &str) -> String {
1535×
    let mut out = String::with_capacity(s.len());
168866×
    for c in s.chars() {
178866×
        match c {
181×
            '&' => out.push_str("&"),
195×
            '<' => out.push_str("&lt;"),
203×
            '>' => out.push_str("&gt;"),
214×
            '"' => out.push_str("&quot;"),
221×
            '\'' => out.push_str("&#39;"),
238852×
            _ => out.push(c),
24
        }
25
    }
2635×
    out
2735×
}
28
29
/// `1.2 KiB`, `3.4 MiB`, `512 B`.
3086×
pub fn bytes(n: u64) -> String {
31
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
3286×
    let mut v = n as f64;
3386×
    let mut i = 0;
34105×
    while v >= 1024.0 && i < UNITS.len() - 1 {
3519×
        v /= 1024.0;
3619×
        i += 1;
3719×
    }
3886×
    if i == 0 {
3970×
        format!("{n} B")
40
    } else {
4116×
        format!("{v:.1} {}", UNITS[i])
42
    }
4386×
}
44
45
#[cfg(test)]
46
mod tests {
47
    use super::*;
48
49
    #[test]
501×
    fn escaping_and_sizes() {
511×
        assert_eq!(escape("<a href=\"x\">&'"), "&lt;a href=&quot;x&quot;&gt;&amp;&#39;");
521×
        assert_eq!(bytes(512), "512 B");
531×
        assert_eq!(bytes(1536), "1.5 KiB");
541×
        assert_eq!(bytes(5 << 20), "5.0 MiB");
551×
    }
56
}