1+ import { utf8DecodeJs } from "./utils/utf8.mjs" ;
2+ var DEFAULT_MAX_KEY_LENGTH = 16 ;
3+ var DEFAULT_MAX_LENGTH_PER_KEY = 16 ;
4+ var CachedKeyDecoder = /** @class */ ( function ( ) {
5+ function CachedKeyDecoder ( maxKeyLength , maxLengthPerKey ) {
6+ if ( maxKeyLength === void 0 ) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH ; }
7+ if ( maxLengthPerKey === void 0 ) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY ; }
8+ this . maxKeyLength = maxKeyLength ;
9+ this . maxLengthPerKey = maxLengthPerKey ;
10+ this . hit = 0 ;
11+ this . miss = 0 ;
12+ // avoid `new Array(N)`, which makes a sparse array,
13+ // because a sparse array is typically slower than a non-sparse array.
14+ this . caches = [ ] ;
15+ for ( var i = 0 ; i < this . maxKeyLength ; i ++ ) {
16+ this . caches . push ( [ ] ) ;
17+ }
18+ }
19+ CachedKeyDecoder . prototype . canBeCached = function ( byteLength ) {
20+ return byteLength > 0 && byteLength <= this . maxKeyLength ;
21+ } ;
22+ CachedKeyDecoder . prototype . find = function ( bytes , inputOffset , byteLength ) {
23+ var records = this . caches [ byteLength - 1 ] ;
24+ FIND_CHUNK: for ( var _i = 0 , records_1 = records ; _i < records_1 . length ; _i ++ ) {
25+ var record = records_1 [ _i ] ;
26+ var recordBytes = record . bytes ;
27+ for ( var j = 0 ; j < byteLength ; j ++ ) {
28+ if ( recordBytes [ j ] !== bytes [ inputOffset + j ] ) {
29+ continue FIND_CHUNK;
30+ }
31+ }
32+ return record . str ;
33+ }
34+ return null ;
35+ } ;
36+ CachedKeyDecoder . prototype . store = function ( bytes , value ) {
37+ var records = this . caches [ bytes . length - 1 ] ;
38+ var record = { bytes : bytes , str : value } ;
39+ if ( records . length >= this . maxLengthPerKey ) {
40+ // `records` are full!
41+ // Set `record` to an arbitrary position.
42+ records [ ( Math . random ( ) * records . length ) | 0 ] = record ;
43+ }
44+ else {
45+ records . push ( record ) ;
46+ }
47+ } ;
48+ CachedKeyDecoder . prototype . decode = function ( bytes , inputOffset , byteLength ) {
49+ var cachedValue = this . find ( bytes , inputOffset , byteLength ) ;
50+ if ( cachedValue != null ) {
51+ this . hit ++ ;
52+ return cachedValue ;
53+ }
54+ this . miss ++ ;
55+ var str = utf8DecodeJs ( bytes , inputOffset , byteLength ) ;
56+ // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
57+ var slicedCopyOfBytes = Uint8Array . prototype . slice . call ( bytes , inputOffset , inputOffset + byteLength ) ;
58+ this . store ( slicedCopyOfBytes , str ) ;
59+ return str ;
60+ } ;
61+ return CachedKeyDecoder ;
62+ } ( ) ) ;
63+ export { CachedKeyDecoder } ;
64+ //# sourceMappingURL=CachedKeyDecoder.mjs.map
0 commit comments