From ffa63c68c73b800d805a3f06ce400271f06efa82 Mon Sep 17 00:00:00 2001 From: Brad Clawsie Date: Sun, 22 Nov 2026 13:12:12 -0600 Subject: feat: learn_17 commit b27c8fc4c30cb45b29c16f0d488351451f5b4c2b Author: Brad Clawsie Date: Sun Nov 22 13:11:45 2026 -0600 feat: learn_17 --- learn_17/src/main.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 learn_17/src/main.rs (limited to 'learn_17/src') diff --git a/learn_17/src/main.rs b/learn_17/src/main.rs new file mode 100644 index 0000000..559a0c6 --- /dev/null +++ b/learn_17/src/main.rs @@ -0,0 +1,84 @@ +#[derive(Debug, PartialEq)] +struct Document { + title: String, + body: String, +} + +impl Document { + fn new(title: String, body: String) -> Self { + Self { + title, + body, + } + } + + fn title(&self) -> &str { + self.title.as_ref() + } + + fn body(&self) -> &str { + self.body.as_ref() + } +} + +impl AsRef for Document { + fn as_ref(&self) -> &str { + self.body() + } +} + +fn word_count>(value: T) -> usize { + value.as_ref().split_whitespace().count() +} + +fn contains_text(haystack: T, needle: U) -> bool +where + T: AsRef, + U: AsRef, +{ + haystack.as_ref().contains(needle.as_ref()) +} + +fn main() { + () +} + +#[cfg(test)] +mod tests { + use crate::*; + + #[test] + fn test_document() { + let document = Document::new("title".to_string(), "body".to_string()); + assert_eq!(document.title(), "title"); + assert_eq!(document.body(), "body"); + assert_eq!(document.as_ref(), document.body()); + } + + #[test] + fn test_word_count() { + let document = Document::new("title".to_string(), "one two three".to_string()); + assert_eq!(word_count(&document), 3); + assert_eq!(word_count(document), 3); + assert_eq!(word_count("one two three".to_string()), 3); + assert_eq!(word_count("one two three"), 3); + assert_eq!(word_count(""), 0); + assert_eq!(word_count(" "), 0); + assert_eq!(word_count("one\ttwo\nthree"), 3); + } + + #[test] + fn test_contains_text() { + assert!(contains_text("a b c", "a")); + assert!(contains_text("a b c", "")); + assert!(!contains_text("a b c", "z")); + assert!(!contains_text("a b c", "A")); + assert!(contains_text("a b c".to_string(), "a".to_string())); + assert!(!contains_text("a b c".to_string(), "z".to_string())); + let d0 = Document::new("t".to_string(), "a b c".to_string()); + let d1 = Document::new("t".to_string(), "a".to_string()); + assert!(contains_text(&d0, d1)); + assert!(!contains_text(&d0, "z".to_string())); + + } +} -- cgit v1.2.3