opendal_core/services/memory/
core.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use 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/// Value stored in memory containing both metadata and content
27#[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}