-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path10-persistent-data-vecs.rs
More file actions
111 lines (98 loc) · 2.62 KB
/
10-persistent-data-vecs.rs
File metadata and controls
111 lines (98 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use statum::{machine, state, validators};
#[state]
enum State {
Draft(Article),
InReview,
Published,
}
#[machine]
struct Machine<State> {
client: String,
}
#[derive(Debug, PartialEq)]
enum Status {
Draft,
InReview,
Published,
}
struct Article {
status: Status,
}
#[validators(Machine)]
impl Article {
pub async fn is_draft(&self) -> Result<Article, statum::Error> {
if self.status == Status::Draft {
Ok(Article {
status: Status::Draft,
})
} else {
Err(statum::Error::InvalidState)
}
}
pub fn is_in_review(&self) -> Result<(), statum::Error> {
println!("Machines client: {}", client);
if self.status == Status::InReview {
Ok(())
} else {
Err(statum::Error::InvalidState)
}
}
pub fn is_published(&self) -> Result<(), statum::Error> {
if self.status == Status::Published {
Ok(())
} else {
Err(statum::Error::InvalidState)
}
}
}
pub async fn run() -> Result<(), statum::Error> {
let articles: Vec<Article> = pretend_db_call().await?;
// The builder is async because one validator is async.
let machine_states = Machine::rebuild_many(articles)
.client("client".to_string())
.build()
.await;
// Real applications should handle invalid rows instead of discarding them.
let machine_states: Vec<machine::SomeState> =
machine_states.into_iter().filter_map(Result::ok).collect();
for machine in machine_states {
match machine {
machine::SomeState::Draft(_machine) => {
println!("_machine is Machine<Draft>");
}
machine::SomeState::InReview(_machine) => {
println!("_machine is Machine<InReview>");
}
machine::SomeState::Published(_machine) => {
println!("_machine is Machine<Published>");
}
}
}
//OUTPUT:
//_machine is Machine<Draft>
//_machine is Machine<InReview>
//_machine is Machine<Published>
//_machine is Machine<Draft>
//_machine is Machine<InReview>
Ok(())
}
async fn pretend_db_call() -> Result<Vec<Article>, statum::Error> {
let articles = [
Article {
status: Status::Draft,
},
Article {
status: Status::InReview,
},
Article {
status: Status::Published,
},
Article {
status: Status::Draft,
},
Article {
status: Status::InReview,
},
];
Ok(articles.into())
}