]> piware.de Git - learn-rust.git/commitdiff
concepts: Add alternative Post implementation with states as types
authorMartin Pitt <martin@piware.de>
Sun, 29 Aug 2021 14:45:02 +0000 (16:45 +0200)
committerMartin Pitt <martin@piware.de>
Sun, 29 Aug 2021 14:45:02 +0000 (16:45 +0200)
concepts/src/lib.rs
concepts/src/main.rs

index b0839ad391739cb186adcf2bb81c97484c5a3dfe..5f1feea9404c8116e1cbb1106b825e5a6d52c677 100644 (file)
@@ -210,3 +210,46 @@ impl State for Published {
         &post.content
     }
 }
         &post.content
     }
 }
+
+// state encoded as types; this is the "approved" state
+pub struct TPost {
+    content: String,
+}
+
+impl TPost {
+    pub fn new() -> TPostDraft {
+        TPostDraft {content: String::new()}
+    }
+
+    pub fn content(&self) -> &str {
+        &self.content
+    }
+}
+
+pub struct TPostDraft {
+    content: String,
+}
+
+impl TPostDraft {
+    pub fn add_text(&mut self, text: &str) {
+        self.content.push_str(text);
+    }
+
+    pub fn request_review(self) -> TPostReview {
+        TPostReview {content: self.content}
+    }
+}
+
+pub struct TPostReview {
+    content: String,
+}
+
+impl TPostReview {
+    pub fn approve(self) -> TPost {
+        TPost {content: self.content}
+    }
+
+    pub fn reject(self) -> TPostDraft {
+        TPostDraft {content: self.content}
+    }
+}
index 20826216bbd4c0ec5a0e8e3cec408f507b28140b..4b6df6447be9930e5773202f24601cd817722eb8 100644 (file)
@@ -272,6 +272,17 @@ fn test_dyn_traits() {
     assert_eq!(text, post.content());
 }
 
     assert_eq!(text, post.content());
 }
 
+fn test_state_types() {
+    let mut post = TPost::new();
+    post.add_text("I ate a salad for lunch");
+    let post = post.request_review();
+    let mut post = post.reject();
+    post.add_text(" today");
+    let post = post.request_review();
+    let post = post.approve();
+    assert_eq!(post.content(), "I ate a salad for lunch today");
+}
+
 fn main() {
     test_strings();
     test_vectors();
 fn main() {
     test_strings();
     test_vectors();
@@ -282,4 +293,5 @@ fn main() {
     test_iterators();
     test_threads();
     test_dyn_traits();
     test_iterators();
     test_threads();
     test_dyn_traits();
+    test_state_types();
 }
 }