kapot_cache/backend/policy/
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
18use std::any::Any;
19use std::fmt::Debug;
20use std::hash::Hash;
21
22pub mod lru;
23
24pub type CachePolicyPutResult<K, V> = (Option<V>, Vec<(K, V)>);
25
26pub trait CachePolicy: Debug + Send + 'static {
27    /// Cache key.
28    type K: Clone + Eq + Hash + Ord + Debug + Send + 'static;
29
30    /// Cached value.
31    type V: Clone + Debug + Send + 'static;
32
33    /// Get value for given key if it exists.
34    fn get(&mut self, k: &Self::K) -> Option<Self::V>;
35
36    /// Peek value for given key if it exists.
37    ///
38    /// In contrast to [`get`](Self::get) this will only return a value if there is a stored value.
39    /// This will not change the cache entries.
40    fn peek(&mut self, k: &Self::K) -> Option<Self::V>;
41
42    /// Put value for given key.
43    ///
44    /// If a key already exists, its old value will be returned.
45    ///
46    /// At the meanwhile, entries popped due to memory pressure will be returned
47    fn put(&mut self, k: Self::K, v: Self::V) -> CachePolicyPutResult<Self::K, Self::V>;
48
49    /// Remove value for given key.
50    ///
51    /// If a key does not exist, none will be returned.
52    fn remove(&mut self, k: &Self::K) -> Option<Self::V>;
53
54    /// Remove an entry from the cache due to memory pressure or expiration.
55    ///
56    /// If the cache is empty, none will be returned.
57    fn pop(&mut self) -> Option<(Self::K, Self::V)>;
58
59    /// Return backend as [`Any`] which can be used to downcast to a specific implementation.
60    fn as_any(&self) -> &dyn Any;
61}