Nenhuma descrição

lru_cache.dart 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import 'dart:collection';
  2. import 'dart:typed_data';
  3. import 'package:photo_manager/photo_manager.dart';
  4. class ImageLruCache {
  5. static LRUMap<_ImageCacheEntity, Uint8List> _map = LRUMap(500);
  6. static Uint8List getData(ImageEntity entity, [int size = 64]) {
  7. return _map.get(_ImageCacheEntity(entity, size));
  8. }
  9. static void setData(ImageEntity entity, int size, Uint8List list) {
  10. _map.put(_ImageCacheEntity(entity, size), list);
  11. }
  12. }
  13. class _ImageCacheEntity {
  14. ImageEntity entity;
  15. int size;
  16. _ImageCacheEntity(this.entity, this.size);
  17. @override
  18. bool operator ==(Object other) =>
  19. identical(this, other) ||
  20. other is _ImageCacheEntity &&
  21. runtimeType == other.runtimeType &&
  22. entity == other.entity &&
  23. size == other.size;
  24. @override
  25. int get hashCode => entity.hashCode ^ size.hashCode;
  26. }
  27. // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
  28. // for details. All rights reserved. Use of this source code is governed by a
  29. // BSD-style license that can be found in the LICENSE file.
  30. typedef EvictionHandler<K, V>(K key, V value);
  31. class LRUMap<K, V> {
  32. final LinkedHashMap<K, V> _map = new LinkedHashMap<K, V>();
  33. final int _maxSize;
  34. final EvictionHandler<K, V> _handler;
  35. LRUMap(this._maxSize, [this._handler]);
  36. V get(K key) {
  37. V value = _map.remove(key);
  38. if (value != null) {
  39. _map[key] = value;
  40. }
  41. return value;
  42. }
  43. void put(K key, V value) {
  44. _map.remove(key);
  45. _map[key] = value;
  46. if (_map.length > _maxSize) {
  47. K evictedKey = _map.keys.first;
  48. V evictedValue = _map.remove(evictedKey);
  49. if (_handler != null) {
  50. _handler(evictedKey, evictedValue);
  51. }
  52. }
  53. }
  54. void remove(K key) {
  55. _map.remove(key);
  56. }
  57. }