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
129
130
131
132
use crate::{
command::{Command, Commands},
store::Store,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Operation {
Get { key: String },
Set { key: String, value: Option<Store> },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Operations {
pub operations: Vec<Operation>,
}
impl Default for Operations {
fn default() -> Self {
Self::new()
}
}
impl Operations {
pub fn new() -> Self {
Self { operations: vec![] }
}
pub fn push(&mut self, operation: Operation) {
self.operations.push(operation);
}
// pub fn add(mut self, operation: Operation) -> Self {
// self.operations.push(operation);
// self
// }
}
impl IntoIterator for Operations {
type Item = Operation;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.operations.into_iter()
}
}
impl From<Vec<Operation>> for Operations {
fn from(value: Vec<Operation>) -> Self {
Self { operations: value }
}
}
impl From<Commands> for Operations {
fn from(commands: Commands) -> Self {
let mut ops = Operations::new();
for command in commands {
match command {
Command::Read { key } => ops.push(Operation::Get { key }),
Command::Update { key, value } => {
ops.push(Operation::Get { key: key.clone() });
ops.push(Operation::Set {
key,
value: Some(value),
});
}
Command::Delete { key } => ops.push(Operation::Set { key, value: None }),
}
}
ops
}
}
#[cfg(test)]
mod tests {
use crate::{
command::{Command, Commands},
operation::{Operation, Operations},
};
#[test]
fn convert_read_to_get() {
let commands = Commands::from(vec![Command::Read {
key: "balls".to_string(),
}]);
let operations = commands.into();
assert_eq!(
Operations::from(vec![Operation::Get {
key: "balls".to_string()
}]),
operations
);
}
// #[test]
// fn convert_update_to_get_and_set() {
// let commands = Commands::from(vec![Command::Update {
// key: "balls".to_string(),
// value: "weiner".to_string(),
// }]);
// let operations = commands.into();
//
// assert_eq!(
// Operations::from(vec![
// Operation::Get {
// key: "balls".to_string()
// },
// Operation::Set {
// key: "balls".to_string(),
// value: Some("weiner".to_string())
// }
// ]),
// operations
// );
// }
#[test]
fn convert_delete_to_set() {
let commands = Commands::from(vec![Command::Delete {
key: "balls".to_string(),
}]);
let operations = commands.into();
assert_eq!(
Operations::from(vec![Operation::Set {
key: "balls".to_string(),
value: None
}]),
operations
);
}
}