1use crate::{
2 command::{Command, Commands},
3 store::Store,
4};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum Operation {
8 Get { key: String },
9 Set { key: String, value: Option<Store> },
10}
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Operations {
14 pub operations: Vec<Operation>,
15}
16
17impl Default for Operations {
18 fn default() -> Self {
19 Self::new()
20 }
21}
22
23impl Operations {
24 pub fn new() -> Self {
25 Self { operations: vec![] }
26 }
27
28 pub fn push(&mut self, operation: Operation) {
29 self.operations.push(operation);
30 }
31
32 }
37
38impl IntoIterator for Operations {
39 type Item = Operation;
40 type IntoIter = std::vec::IntoIter<Self::Item>;
41
42 fn into_iter(self) -> Self::IntoIter {
43 self.operations.into_iter()
44 }
45}
46
47impl From<Vec<Operation>> for Operations {
48 fn from(value: Vec<Operation>) -> Self {
49 Self { operations: value }
50 }
51}
52
53impl From<Commands> for Operations {
54 fn from(commands: Commands) -> Self {
55 let mut ops = Operations::new();
56 for command in commands {
57 match command {
58 Command::Read { key } => ops.push(Operation::Get { key }),
59 Command::Update { key, value } => {
60 ops.push(Operation::Get { key: key.clone() });
61 ops.push(Operation::Set {
62 key,
63 value: Some(value),
64 });
65 }
66 Command::Delete { key } => ops.push(Operation::Set { key, value: None }),
67 }
68 }
69 ops
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use crate::{
76 command::{Command, Commands},
77 operation::{Operation, Operations},
78 };
79
80 #[test]
81 fn convert_read_to_get() {
82 let commands = Commands::from(vec![Command::Read {
83 key: "balls".to_string(),
84 }]);
85 let operations = commands.into();
86
87 assert_eq!(
88 Operations::from(vec![Operation::Get {
89 key: "balls".to_string()
90 }]),
91 operations
92 );
93 }
94
95 #[test]
118 fn convert_delete_to_set() {
119 let commands = Commands::from(vec![Command::Delete {
120 key: "balls".to_string(),
121 }]);
122 let operations = commands.into();
123
124 assert_eq!(
125 Operations::from(vec![Operation::Set {
126 key: "balls".to_string(),
127 value: None
128 }]),
129 operations
130 );
131 }
132}