Browse code

More information in the state

Julio Biason authored on 27/02/2019 13:22:15
Showing 1 changed files

... ...
@@ -4,10 +4,36 @@ use std::fs::File;
4 4
 use std::io::prelude::*;
5 5
 use slug::slugify;
6 6
 
7
-enum State {
7
+enum CurrentTag {
8 8
     Title
9 9
 }
10 10
 
11
+struct State {
12
+    tag: Option<CurrentTag>,
13
+    title: String
14
+}
15
+
16
+impl State {
17
+    pub fn new() -> Self {
18
+        Self { tag: None, title: String::from("") }
19
+    }
20
+
21
+    pub fn change_title(self, title:&str) -> Self {
22
+        Self { tag:self.tag,
23
+               title:title.to_string() }
24
+    }
25
+
26
+    pub fn change_tag(self, tag:CurrentTag) -> Self {
27
+        Self { tag:Some(tag),
28
+               title:self.title }
29
+    }
30
+
31
+    pub fn remove_tag(self) -> Self {
32
+        Self { tag:None,
33
+               title:self.title }
34
+    }
35
+}
36
+
11 37
 fn main() {
12 38
     let args:Vec<_> = env::args().collect();
13 39
     if args.len() != 2 {
... ...
@@ -29,23 +55,23 @@ fn main() {
29 55
     let mut parser = Parser::new();
30 56
     parser.feed_str(&contents);
31 57
     
32
-    parser.fold(None, {|state:Option<State>, element| {
58
+    parser.fold(State::new(), {|state:State, element| {
33 59
         match element.unwrap() {
34 60
             Event::ElementStart(tag) => {
35 61
                 match tag.name.as_ref() {
36
-                    "title" => Some(State::Title),
37
-                    _ => None
62
+                    "title" => state.change_tag(CurrentTag::Title),
63
+                    _ => state
38 64
                 }
39 65
             },
40 66
             Event::ElementEnd(_) => {
41
-                None    // ending a tag always remove the state
67
+                state.remove_tag()
42 68
             },
43 69
             Event::Characters(data) => {
44 70
                 // println!("Data: {}", data);
45
-                match state {
46
-                    Some(State::Title) => {
47
-                        println!("TITLE: {}", slugify(data));
48
-                        None
71
+                match state.tag {
72
+                    Some(CurrentTag::Title) => {
73
+                        println!("TITLE: {}", slugify(&data));
74
+                        state.change_title(&slugify(data))
49 75
                     },
50 76
                     _ => state
51 77
                 }