ballista_cache/backend/
mod.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
18pub mod policy;
19
20use crate::backend::policy::CachePolicy;
21use std::fmt::Debug;
22use std::hash::Hash;
23
24/// Backend to keep and manage stored entries.
25///
26/// A backend might remove entries at any point, e.g. due to memory pressure or expiration.
27#[derive(Debug)]
28pub struct CacheBackend<K, V>
29where
30    K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
31    V: Clone + Debug + Send + 'static,
32{
33    policy: Box<dyn CachePolicy<K = K, V = V>>,
34}
35
36impl<K, V> CacheBackend<K, V>
37where
38    K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
39    V: Clone + Debug + Send + 'static,
40{
41    pub fn new(policy: impl CachePolicy<K = K, V = V>) -> Self {
42        Self {
43            policy: Box::new(policy),
44        }
45    }
46
47    /// Get value for given key if it exists.
48    pub fn get(&mut self, k: &K) -> Option<V> {
49        self.policy.get(k)
50    }
51
52    /// Peek value for given key if it exists.
53    ///
54    /// In contrast to [`get`](Self::get) this will only return a value if there is a stored value.
55    /// This will not change the cache contents.
56    pub fn peek(&mut self, k: &K) -> Option<V> {
57        self.policy.peek(k)
58    }
59
60    /// Put value for given key.
61    ///
62    /// If a key already exists, its old value will be returned.
63    pub fn put(&mut self, k: K, v: V) -> Option<V> {
64        self.policy.put(k, v).0
65    }
66
67    /// Remove value for given key.
68    ///
69    /// If a key does not exist, none will be returned.
70    pub fn remove(&mut self, k: &K) -> Option<V> {
71        self.policy.remove(k)
72    }
73}