walrus_memory/
inmemory.rs1use crate::Memory;
4use std::sync::Mutex;
5
6#[derive(Default, Debug)]
8pub struct InMemory {
9 entries: Mutex<Vec<(String, String)>>,
10}
11
12impl InMemory {
13 pub fn new() -> Self {
15 Self::default()
16 }
17
18 pub fn with_entries(entries: impl IntoIterator<Item = (String, String)>) -> Self {
20 Self {
21 entries: Mutex::new(entries.into_iter().collect()),
22 }
23 }
24}
25
26impl Memory for InMemory {
27 fn get(&self, key: &str) -> Option<String> {
28 let entries = self.entries.lock().unwrap();
29 entries
30 .iter()
31 .find(|(k, _)| k == key)
32 .map(|(_, v)| v.clone())
33 }
34
35 fn entries(&self) -> Vec<(String, String)> {
36 self.entries.lock().unwrap().clone()
37 }
38
39 fn set(&self, key: impl Into<String>, value: impl Into<String>) -> Option<String> {
40 let key = key.into();
41 let value = value.into();
42 let mut entries = self.entries.lock().unwrap();
43 if let Some(existing) = entries.iter_mut().find(|(k, _)| *k == key) {
44 Some(std::mem::replace(&mut existing.1, value))
45 } else {
46 entries.push((key, value));
47 None
48 }
49 }
50
51 fn remove(&self, key: &str) -> Option<String> {
52 let mut entries = self.entries.lock().unwrap();
53 let idx = entries.iter().position(|(k, _)| k == key)?;
54 Some(entries.remove(idx).1)
55 }
56}