1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const KEY: &'static str = "[HS_HELP]:";

fn trim_first_white(s: &str) -> &str {
    if s.starts_with(' ') {
        &s[1..]
    } else {
        s
    }
}

pub fn extract_help(mut content: &str, long: bool) -> Vec<&str> {
    let mut ans = vec![];
    if let Some(pos) = content.find(KEY) {
        content = &content[pos..];
        let new_line_pos = content.find("\n").unwrap_or(content.len());
        ans.push(trim_first_white(&content[KEY.len()..new_line_pos]));
        if !long {
            return ans;
        }
        content = &content[new_line_pos..];
    } else {
        return ans;
    }

    while let Some(pos) = content.find(KEY) {
        content = &content[pos..];
        let new_line_pos = content.find("\n").unwrap_or(content.len());
        ans.push(trim_first_white(&content[KEY.len()..new_line_pos]));

        content = &content[new_line_pos..];
    }

    ans
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_extract_help() {
        let content = "
        // 不要解析我
        // [HS_HELP]:   解析我吧  

        // [HS_NOHELP]: 不要解析我QQ
        // [HS_HELP]:
        fn this_is_a_test() -> bool {}

        # [HS_HELP]: 解析我吧,雖然我是個失敗的註解

        //  前面有些 垃圾[HS_HELP]:我是最後一行";
        let short = extract_help(content, false);
        let long = extract_help(content, true);
        assert_eq!(short, vec!["  解析我吧  "]);
        assert_eq!(
            long,
            vec![
                "  解析我吧  ",
                "",
                "解析我吧,雖然我是個失敗的註解",
                "我是最後一行"
            ]
        );

        let appended = format!("{}\n 真.最後一行", content);
        let short2 = extract_help(&appended, false);
        let long2 = extract_help(&appended, true);
        assert_eq!(short, short2);
        assert_eq!(long, long2);
    }
    #[test]
    fn test_extract_empty() {
        let content = "
        // 不要解析我
        fn this_is_a_test() -> bool {}

        // [HS_HOLP]:我是最後一行,還拼錯字…";
        let short = extract_help(content, false);
        let long = extract_help(content, true);
        assert_eq!(short.len(), 0);
        assert_eq!(long.len(), 0);
    }
}