cache.dart 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import 'package:flutter/painting.dart';
  2. import 'package:quiver/collection.dart';
  3. class TextLayoutCache {
  4. TextLayoutCache(this.textDirection, int maximumSize)
  5. : _cache = LruMap<TextSpan, TextPainter>(maximumSize: maximumSize);
  6. final LruMap<TextSpan, TextPainter> _cache;
  7. final TextDirection textDirection;
  8. TextPainter getOrPerformLayout(TextSpan text) {
  9. final cachedPainter = _cache[text];
  10. if (cachedPainter != null) {
  11. return cachedPainter;
  12. } else {
  13. return _performAndCacheLayout(text);
  14. }
  15. }
  16. TextPainter _performAndCacheLayout(TextSpan text) {
  17. final textPainter = TextPainter(text: text, textDirection: textDirection);
  18. textPainter.layout();
  19. _cache[text] = textPainter;
  20. return textPainter;
  21. }
  22. int get length {
  23. return _cache.length;
  24. }
  25. }
  26. final textLayoutCache = TextLayoutCache(TextDirection.ltr, 1024);
  27. class TextLayoutCacheV2 {
  28. TextLayoutCacheV2(this.textDirection, int maximumSize)
  29. : _cache = LruMap<int, TextPainter>(maximumSize: maximumSize);
  30. final LruMap<int, TextPainter> _cache;
  31. final TextDirection textDirection;
  32. TextPainter getOrPerformLayout(TextSpan text, int key) {
  33. final cachedPainter = _cache[key];
  34. if (cachedPainter != null) {
  35. return cachedPainter;
  36. } else {
  37. return _performAndCacheLayout(text, key);
  38. }
  39. }
  40. TextPainter _performAndCacheLayout(TextSpan text, int key) {
  41. final textPainter = TextPainter(text: text, textDirection: textDirection);
  42. textPainter.layout();
  43. _cache[key] = textPainter;
  44. return textPainter;
  45. }
  46. int get length {
  47. return _cache.length;
  48. }
  49. }
  50. final textLayoutCacheV2 = TextLayoutCacheV2(TextDirection.ltr, 1024);
  51. // class CodePointCache {
  52. // CodePointCache(int maximumSize)
  53. // : _cache = LruMap<int, String>(maximumSize: maximumSize);
  54. // final LruMap<int, String> _cache;
  55. // String getOrConstruct(int codePoint) {
  56. // final cachedString = _cache[codePoint];
  57. // if (cachedString != null) {
  58. // return cachedString;
  59. // } else {
  60. // return _constructAndCacheString(codePoint);
  61. // }
  62. // }
  63. // String _constructAndCacheString(int codePoint) {
  64. // final string = String.fromCharCode(codePoint);
  65. // _cache[codePoint] = string;
  66. // return string;
  67. // }
  68. // }
  69. // final codePointCache = CodePointCache(1024);