opendal_core/services/sled/
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::fmt::Debug;
19
20use crate::*;
21
22#[derive(Clone)]
23pub struct SledCore {
24    pub datadir: String,
25    pub tree: sled::Tree,
26}
27
28impl Debug for SledCore {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("SledCore")
31            .field("path", &self.datadir)
32            .finish()
33    }
34}
35
36impl SledCore {
37    pub fn get(&self, path: &str) -> Result<Option<Buffer>> {
38        let res = self.tree.get(path).map_err(parse_error)?;
39        Ok(res.map(|v| Buffer::from(v.to_vec())))
40    }
41
42    pub fn set(&self, path: &str, value: Buffer) -> Result<()> {
43        self.tree
44            .insert(path, value.to_vec())
45            .map_err(parse_error)?;
46        Ok(())
47    }
48
49    pub fn delete(&self, path: &str) -> Result<()> {
50        self.tree.remove(path).map_err(parse_error)?;
51        Ok(())
52    }
53
54    pub fn list(&self, path: &str) -> Result<Vec<String>> {
55        let it = self.tree.scan_prefix(path).keys();
56        let mut res = Vec::default();
57
58        for i in it {
59            let bs = i.map_err(parse_error)?.to_vec();
60            let v = String::from_utf8(bs).map_err(|err| {
61                Error::new(ErrorKind::Unexpected, "store key is not valid utf-8 string")
62                    .set_source(err)
63            })?;
64
65            res.push(v);
66        }
67
68        Ok(res)
69    }
70}
71
72fn parse_error(err: sled::Error) -> Error {
73    Error::new(ErrorKind::Unexpected, "error from sled").set_source(err)
74}