Advertisement
A248

Rust implementation of adjective replacement

Apr 6th, 2021
1,152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.79 KB | None | 0 0
  1.  
  2.  
  3. trait AdjectiveGenerator {
  4.     fn random_adjective(&self) -> Box<str>;
  5. }
  6.  
  7. struct FixedAdjectiveGenerator {}
  8. impl AdjectiveGenerator for FixedAdjectiveGenerator {
  9.     fn random_adjective(&self) -> Box<str> {
  10.         Box::from("ADJ")
  11.     }
  12. }
  13.  
  14. fn replace_adjectives_in<A: AdjectiveGenerator>(generator: Box<A>, review_contents: &str) -> Box<str> {
  15.     let mut string_builder = String::new();
  16.     for segment in review_contents.split("*") {
  17.         if string_builder.is_empty() {
  18.             // First segment before any asterisk
  19.             string_builder.push_str(segment);
  20.             continue;
  21.         }
  22.         let words_in_segment = segment.split(" ");
  23.         let remaining_words = words_in_segment.skip(1);
  24.  
  25.         let random_adjective = generator.random_adjective();
  26.         string_builder.push_str(&random_adjective);
  27.         for remaining_word in remaining_words {
  28.             string_builder.push(' ');
  29.             string_builder.push_str(remaining_word);
  30.         }
  31.     }
  32.     return string_builder.into_boxed_str();
  33.  
  34. }
  35.  
  36. #[cfg(test)]
  37. mod tests {
  38.     use crate::totp::totp::{replace_adjectives_in, FixedAdjectiveGenerator, AdjectiveGenerator};
  39.     use std::borrow::Borrow;
  40.     use std::ops::Deref;
  41.  
  42.     #[test]
  43.     fn replace_adjectives_in_test1() {
  44.         let generator = Box::new(FixedAdjectiveGenerator {});
  45.         assert_eq!(
  46.             replace_adjectives_in(generator, "this is a *spicy review"),
  47.             Box::from("this is a ADJ review"));
  48.     }
  49.  
  50.     #[test]
  51.     fn replace_adjectives_in_test2() {
  52.         let generator = Box::new(FixedAdjectiveGenerator {});
  53.         assert_eq!(
  54.             replace_adjectives_in(generator, "this is a *spicy review with lots of *salty salt"),
  55.             Box::from("this is a ADJ review with lots of ADJ salt"));
  56.     }
  57. }
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement