aboutsummaryrefslogtreecommitdiff
path: root/src/ext/framework/command.rs
blob: 46338a1cc01e3638cc6b534ca0baf9e4b991905e (plain) (blame)
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
use std::sync::Arc;
use super::Configuration;
use ::client::Context;
use ::model::Message;

#[doc(hidden)]
pub type Command = Fn(&Context, &Message, Vec<String>) + Send + Sync;
#[doc(hidden)]
pub type InternalCommand = Arc<Command>;

pub fn positions(content: &str, conf: &Configuration) -> Option<Vec<usize>> {
    if let Some(ref prefix) = conf.prefix {
        // Find out if they were mentioned. If not, determine if the prefix
        // was used. If not, return None.
        let mut positions = if let Some(mention_end) = find_mention_end(content, conf) {
            vec![mention_end]
        } else if content.starts_with(prefix) {
            vec![prefix.len()]
        } else {
            return None;
        };

        if conf.allow_whitespace {
            let pos = *unsafe {
                positions.get_unchecked(0)
            };

            positions.insert(0, pos + 1);
        }

        Some(positions)
    } else if conf.on_mention.is_some() {
        match find_mention_end(content, conf) {
            Some(mention_end) => {
                let mut positions = vec![mention_end];

                if conf.allow_whitespace {
                    positions.insert(0, mention_end + 1);
                }

                Some(positions)
            },
            None => None,
        }
    } else {
        None
    }
}

fn find_mention_end(content: &str, conf: &Configuration) -> Option<usize> {
    if let Some(ref mentions) = conf.on_mention {
        for mention in mentions {
            if !content.starts_with(&mention[..]) {
                continue;
            }

            return Some(mention.len());
        }
    }

    None
}