Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Logic error in MemoryCache.setValue() #2931

Merged
merged 2 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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