rust/chat_sanitizer/src/bad_words.rs
changeset 14508 831ecafd74c6
child 14510 ba29aa03db87
equal deleted inserted replaced
14507:abe0a561005e 14508:831ecafd74c6
       
     1 use crate::{normalized_message, MessageChecker, Severity};
       
     2 
       
     3 use std::marker::PhantomData;
       
     4 
       
     5 struct BadWordsChecker<T> {
       
     6     blacklist: Vec<String>,
       
     7     whitelist: Vec<String>,
       
     8     player_id_type: PhantomData<T>,
       
     9 }
       
    10 
       
    11 impl<T> BadWordsChecker<T> {
       
    12     pub fn new(blacklist: &[&str], whitelist: &[&str]) -> Self {
       
    13         Self {
       
    14             blacklist: blacklist.iter().map(|s| normalized_message(*s)).collect(),
       
    15             whitelist: whitelist.iter().map(|s| normalized_message(*s)).collect(),
       
    16             player_id_type: PhantomData,
       
    17         }
       
    18     }
       
    19 }
       
    20 
       
    21 impl<T> MessageChecker<T> for BadWordsChecker<T> {
       
    22     fn check(&self, player_id: T, message: &str) -> Severity {
       
    23         let msg = normalized_message(message);
       
    24 
       
    25         // silly implementation, allows bad messages with a single good word
       
    26         for badword in &self.blacklist {
       
    27             if msg.contains(badword) {
       
    28                 if !self.whitelist.iter().any(|goodword| msg.contains(goodword)) {
       
    29                     return Severity::Warn;
       
    30                 }
       
    31             }
       
    32         }
       
    33 
       
    34         Severity::Pass
       
    35     }
       
    36 }
       
    37 
       
    38 #[cfg(test)]
       
    39 mod tests {
       
    40     use super::*;
       
    41     #[test]
       
    42     fn it_works() {
       
    43         let checker = BadWordsChecker::new(&["fsck", "poop"], &["fsck -y"]);
       
    44         assert_eq!(checker.check(0, "group hug"), Severity::Pass);
       
    45         assert_eq!(checker.check(0, "fpoopf"), Severity::Warn);
       
    46         assert_eq!(checker.check(0, "PooP"), Severity::Warn);
       
    47 
       
    48         // this one fails
       
    49         //assert_eq!(checker.check(0, "poop 'fsck -y' poop"), Severity::Warn);
       
    50 
       
    51         // ideally this one shouldn't fail
       
    52         // assert_eq!(checker.check(0, "P00P"), Severity::Warn);
       
    53     }
       
    54 }