CachedUtf8Decoder.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CachedUtf8Decoder = void 0;
  4. const tslib_1 = require("tslib");
  5. const v10_1 = tslib_1.__importDefault(require("./decodeUtf8/v10"));
  6. let x = 1 + Math.round(Math.random() * ((-1 >>> 0) - 1));
  7. function randomU32(min, max) {
  8. x ^= x << 13;
  9. x ^= x >>> 17;
  10. x ^= x << 5;
  11. return ((x >>> 0) % (max - min + 1)) + min;
  12. }
  13. class CacheItem {
  14. constructor(bytes, value) {
  15. this.bytes = bytes;
  16. this.value = value;
  17. }
  18. }
  19. class CachedUtf8Decoder {
  20. constructor() {
  21. this.caches = [];
  22. for (let i = 0; i < 31; i++)
  23. this.caches.push([]);
  24. }
  25. get(bytes, offset, size) {
  26. const records = this.caches[size - 1];
  27. const len = records.length;
  28. FIND_CHUNK: for (let i = 0; i < len; i++) {
  29. const record = records[i];
  30. const recordBytes = record.bytes;
  31. for (let j = 0; j < size; j++)
  32. if (recordBytes[j] !== bytes[offset + j])
  33. continue FIND_CHUNK;
  34. return record.value;
  35. }
  36. return null;
  37. }
  38. store(bytes, value) {
  39. const records = this.caches[bytes.length - 1];
  40. const record = new CacheItem(bytes, value);
  41. const length = records.length;
  42. if (length >= 16)
  43. records[randomU32(0, 16 - 1)] = record;
  44. else
  45. records.push(record);
  46. }
  47. decode(bytes, offset, size) {
  48. if (!size)
  49. return '';
  50. const cachedValue = this.get(bytes, offset, size);
  51. if (cachedValue !== null)
  52. return cachedValue;
  53. const value = (0, v10_1.default)(bytes, offset, size);
  54. const copy = Uint8Array.prototype.slice.call(bytes, offset, offset + size);
  55. this.store(copy, value);
  56. return value;
  57. }
  58. }
  59. exports.CachedUtf8Decoder = CachedUtf8Decoder;
  60. //# sourceMappingURL=CachedUtf8Decoder.js.map