opendal_core/services/memory/
core.rs1use std::collections::BTreeMap;
19use std::collections::btree_map::Entry;
20use std::fmt::Debug;
21use std::sync::Arc;
22use std::sync::Mutex;
23
24use crate::*;
25
26#[derive(Clone)]
28pub struct MemoryValue {
29 pub metadata: Metadata,
30 pub content: Buffer,
31}
32
33#[derive(Clone)]
34pub struct MemoryCore {
35 pub data: Arc<Mutex<BTreeMap<String, MemoryValue>>>,
36}
37
38impl Debug for MemoryCore {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("MemoryCore").finish_non_exhaustive()
41 }
42}
43
44impl MemoryCore {
45 pub fn new() -> Self {
46 Self {
47 data: Arc::new(Mutex::new(BTreeMap::new())),
48 }
49 }
50
51 pub fn get(&self, key: &str) -> Result<Option<MemoryValue>> {
52 Ok(self.data.lock().unwrap().get(key).cloned())
53 }
54
55 pub fn set(&self, key: &str, value: MemoryValue) -> Result<()> {
56 self.data.lock().unwrap().insert(key.to_string(), value);
57 Ok(())
58 }
59
60 pub fn set_if_not_exists(&self, key: &str, value: MemoryValue) -> Result<()> {
61 let mut data = self.data.lock().unwrap();
62 match data.entry(key.to_string()) {
63 Entry::Vacant(entry) => entry.insert(value),
64 Entry::Occupied(_) => {
65 return Err(Error::new(
66 ErrorKind::ConditionNotMatch,
67 "key already exists",
68 ));
69 }
70 };
71 Ok(())
72 }
73
74 pub fn delete(&self, key: &str) -> Result<()> {
75 self.data.lock().unwrap().remove(key);
76 Ok(())
77 }
78
79 pub fn scan(&self, prefix: &str) -> Result<Vec<String>> {
80 let data = self.data.lock().unwrap();
81
82 if prefix.is_empty() {
83 return Ok(data.keys().cloned().collect());
84 }
85
86 let mut keys = Vec::new();
87 for (key, _) in data.range(prefix.to_string()..) {
88 if !key.starts_with(prefix) {
89 break;
90 }
91 keys.push(key.clone());
92 }
93 Ok(keys)
94 }
95}