Skip to content

Commit

Permalink
fix: Logic error in MemoryCache.setValue() (#2931)
Browse files Browse the repository at this point in the history
Fixes a logic error which prevented values in `MemoryCache` from being
updated when calling `setValue` with a preexisting `key`.


Replace or remove this text.
  • Loading branch information
filiph authored Dec 18, 2023
1 parent 3730cb1 commit 8cee80c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
13 changes: 10 additions & 3 deletions packages/flame/lib/src/cache/memory_cache.dart
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import 'dart:collection';

/// Simple class to cache values with size based eviction.
///
class MemoryCache<K, V> {
final LinkedHashMap<K, V> _cache = LinkedHashMap();
final int cacheSize;

MemoryCache({this.cacheSize = 10});

/// Adds the [value] to the cache under [key].
///
/// If that [key] is already used, updates the value.
void setValue(K key, V value) {
if (!_cache.containsKey(key)) {
_cache[key] = value;
final preexisting = _cache.containsKey(key);
_cache[key] = value;

if (!preexisting) {
while (_cache.length > cacheSize) {
final k = _cache.keys.first;
_cache.remove(k);
Expand All @@ -29,11 +32,15 @@ class MemoryCache<K, V> {
_cache.clear();
}

/// Gets the value under [key].
V? getValue(K key) => _cache[key];

/// Checks whether the cache has any value under [key].
bool containsKey(K key) => _cache.containsKey(key);

/// Returns the number of values saved in this memory cache.
int get size => _cache.length;

/// Iterates over all existing keys with values.
Iterable<K> get keys => _cache.keys;
}
8 changes: 8 additions & 0 deletions packages/flame/test/cache/memory_cache_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ void main() {
expect(cache.keys.length, 1);
});

test('updates key', () {
final cache = MemoryCache<int, String>();
cache.setValue(0, 'bla');
expect(cache.getValue(0), 'bla');
cache.setValue(0, 'ble');
expect(cache.getValue(0), 'ble');
});

test('cache size', () {
final cache = MemoryCache<int, String>(cacheSize: 1);
cache.setValue(0, 'bla');
Expand Down

0 comments on commit 8cee80c

Please sign in to comment.