summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--learn_17/Cargo.lock7
-rw-r--r--learn_17/Cargo.toml6
-rw-r--r--learn_17/src/main.rs84
3 files changed, 97 insertions, 0 deletions
diff --git a/learn_17/Cargo.lock b/learn_17/Cargo.lock
new file mode 100644
index 0000000..7229035
--- /dev/null
+++ b/learn_17/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "learn_17"
+version = "0.1.0"
diff --git a/learn_17/Cargo.toml b/learn_17/Cargo.toml
new file mode 100644
index 0000000..ac5454c
--- /dev/null
+++ b/learn_17/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "learn_17"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
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<str> for Document {
+ fn as_ref(&self) -> &str {
+ self.body()
+ }
+}
+
+fn word_count<T: AsRef<str>>(value: T) -> usize {
+ value.as_ref().split_whitespace().count()
+}
+
+fn contains_text<T, U>(haystack: T, needle: U) -> bool
+where
+ T: AsRef<str>,
+ U: AsRef<str>,
+{
+ 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()));
+
+ }
+}