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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use todo::Todo;
use error::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TodoList {
pub name: String,
pub list: Vec<Todo>,
}
impl TodoList {
pub fn new(name: &str) -> TodoList {
TodoList {
name: name.to_string(),
list: Vec::new(),
}
}
pub fn add(&mut self, new_todo: Todo) {
self.list.push(new_todo);
}
pub fn contains_id(&self, id: u32) -> TdoResult<usize> {
match self.list.iter().position(|x| x.id == id) {
Some(index) => Ok(index),
None => Err(ErrorKind::TodoError(todo_error::ErrorKind::NotInList).into()),
}
}
pub fn done_id(&mut self, id: u32) -> TdoResult<()> {
match self.contains_id(id) {
Ok(index) => Ok(self.list[index].set_done()),
_ => Err(ErrorKind::TodoError(todo_error::ErrorKind::NotInList).into()),
}
}
pub fn remove_id(&mut self, id: u32) -> TdoResult<Todo> {
match self.contains_id(id) {
Ok(index) => Ok(self.list.remove(index)),
_ => Err(ErrorKind::TodoError(todo_error::ErrorKind::NotInList).into()),
}
}
pub fn list_undone(&self) -> Vec<Todo> {
let mut undone: Vec<Todo> = vec![];
for entry in self.to_owned().list.into_iter() {
if !entry.done {
undone.push(entry);
}
}
undone
}
pub fn clean(&mut self) {
for entry in self.to_owned().list.into_iter() {
if entry.done {
let _ = self.remove_id(entry.id);
}
}
}
pub fn pop_id(&mut self, todo_id: u32) -> TdoResult<Todo> {
let list_pos = self.contains_id(todo_id)?;
Ok(self.list.remove(list_pos))
}
pub fn insert_todo(&mut self, todo: Todo) {
let insert_id = self.list
.iter()
.fold(0, |acc, &ref x| if todo.id > x.id { acc + 1 } else { acc });
self.list.insert(insert_id, todo);
}
}
impl Default for TodoList {
fn default() -> TodoList {
TodoList {
name: "default".to_string(),
list: Vec::new(),
}
}
}