1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use core::{cell::Cell, fmt};
/// A datastructure that [memoizes](https://wikipedia.org/wiki/Memoization) a query function
///
/// This can be used for when queries rarely change and can potentially be expensive or on hot
/// code paths. After the `input` is mutated, the query value should be `clear`ed to signal that
/// the function needs to be executed again.
///
/// In debug mode the `get` call will always run the query and assert that the values match.
#[derive(Clone)]
pub struct Memo<T: Copy, Input, Check = DefaultConsistencyCheck> {
value: Cell<Option<T>>,
query: fn(&Input) -> T,
check: Check,
}
impl<T: Copy + fmt::Debug, Input, Check> fmt::Debug for Memo<T, Input, Check> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Memo").field(&self.value.get()).finish()
}
}
impl<T: Copy + PartialEq + fmt::Debug, Input, Check: ConsistencyCheck> Memo<T, Input, Check> {
/// Creates a new `Memo` over a query function
#[inline]
pub fn new(query: fn(&Input) -> T) -> Self {
Self {
value: Cell::new(None),
query,
check: Check::default(),
}
}
/// Returns the current value of the query function, which may be cached
#[inline]
#[track_caller]
pub fn get(&self, input: &Input) -> T {
if let Some(value) = self.value.get() {
// make sure the values match
self.check.check_consistency(value, input, self.query);
return value;
}
let value = (self.query)(input);
self.value.set(Some(value));
value
}
/// Clears the cached value of the query function
#[inline]
pub fn clear(&self) {
self.value.set(None);
}
/// Asserts that the cached value reflects the current query result in debug mode
#[inline]
#[track_caller]
pub fn check_consistency(&self, input: &Input) {
if cfg!(debug_assertions) {
// `get` will assert the value matches the query internally
let _ = self.get(input);
}
}
}
/// Trait to configure consistency checking behavior
pub trait ConsistencyCheck: Clone + Default {
/// Called when the `Memo` struct has a cached value
///
/// An implementation can assert that the `cache` value matches the current `query` result
fn check_consistency<T: PartialEq + fmt::Debug, Input>(
&self,
cache: T,
input: &Input,
query: fn(&Input) -> T,
);
}
#[derive(Copy, Clone, Default)]
pub struct ConsistencyCheckAlways;
impl ConsistencyCheck for ConsistencyCheckAlways {
#[inline]
fn check_consistency<T: PartialEq + fmt::Debug, Input>(
&self,
actual: T,
input: &Input,
query: fn(&Input) -> T,
) {
let expected = query(input);
assert_eq!(expected, actual);
}
}
#[derive(Copy, Clone, Default)]
pub struct ConsistencyCheckNever;
impl ConsistencyCheck for ConsistencyCheckNever {
#[inline]
fn check_consistency<T: PartialEq + fmt::Debug, Input>(
&self,
_cache: T,
_input: &Input,
_query: fn(&Input) -> T,
) {
// noop
}
}
#[cfg(debug_assertions)]
pub type DefaultConsistencyCheck = ConsistencyCheckAlways;
#[cfg(not(debug_assertions))]
pub type DefaultConsistencyCheck = ConsistencyCheckNever;
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Default)]
struct Input<Value> {
value: Value,
should_query: bool,
}
#[test]
fn memo_test() {
let memo = Memo::<u64, Input<_>, ConsistencyCheckNever>::new(|input| {
assert!(
input.should_query,
"query was called when it wasn't expected"
);
input.value
});
assert_eq!(
memo.get(&Input {
value: 1,
should_query: true,
}),
1
);
assert_eq!(
memo.get(&Input {
value: 2,
should_query: false,
}),
1
);
memo.clear();
assert_eq!(
memo.get(&Input {
value: 3,
should_query: true,
}),
3
);
assert_eq!(
memo.get(&Input {
value: 4,
should_query: false,
}),
3
);
}
}