lru 1.0.0 copy "lru: ^1.0.0" to clipboard
lru: ^1.0.0 copied to clipboard

LRU (Least recently used) cache with additional weak map layer.

LRU Cache #

pub package package publisher

Cache based on Least Recently Used evict strategy.

Supports caching more than capacity via Week references (such values are cached until they garbage collected).

Features #

  • Supports full Map interface.
  • Store TypedData and evict entries by bytes capacity via LruTypedDataCache.
  • Expando compatible objects can be optionally cached via LruWeakCache.

Usage #

Create cache, add values, when space is exhausted;

// no weak cache, because String is not supported by Expando
final cache = new LruCache<int, String>(2);

cache[0] = '0';
cache[1] = '1';
cache[2] = '2'; // key 0 is evicted here

cache[0]; // try to touch

print(cache[0]); // null
print(cache[1]); // 1
print(cache[2]); // 2

Example with bytes capacity for TypedData.

// use capacityInBytes as additional eviction strategy
final cache = LruTypedDataCache<int, Uint8List>(capacity: 100, capacityInBytes: 2);
cache[0] = Uint8List(1)..[0] = 0;
cache[1] = Uint8List(1)..[0] = 1;
cache[2] = Uint8List(1)..[0] = 2;

print(cache[0]); // null
print(cache[1]); // [1]
print(cache[2]); // [2]

Example with Weak Cache support:

/// Helper class to demonstrate LruWeakCache
class Key {
  const Key(this.key);
  final String key;
  @override
  String toString() => key;
}

void main() {
  final cache = LruWeakCache<int, Key>(2);

  cache[0] = Key('0');
  cache[1] = Key('1');
  cache[2] = Key('2'); // key 0 is evicted from LRU and moved to weak cache

  // try to touch, if key 0 is not garbage collected yet
  // key 1 is moved to weak cache, and key 0 is restored
  cache[0];

  print(cache[0]); // likely 0
  print(cache[1]); // likely 1
  print(cache[2]); // 2
}
2
likes
0
points
36
downloads

Publisher

verified publishernull.moe

Weekly Downloads

LRU (Least recently used) cache with additional weak map layer.

Repository (GitHub)
View/report issues

Topics

#cache #lru

License

unknown (license)

Dependencies

meta, weak_cache

More

Packages that depend on lru