Skip to content

Commit

Permalink
Cache with lru-cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
sandinmyjoints committed Jan 22, 2024
1 parent 93c1fac commit 5f4ed84
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions lib/parsers/string.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
'use strict';

const Iconv = require('iconv-lite');
const decoderCache = new Map();
const LRU = require('lru-cache');

const decoderCache = new LRU({
max: 500,
});

exports.decode = function (buffer, encoding, start, end, options) {
if (Buffer.isEncoding(encoding)) {
return buffer.toString(encoding, start, end);
}

const decoderArgs = { encoding, options: options || {} };
const decoder =
decoderCache.get(decoderArgs) ||
decoderCache
.set(
decoderArgs,
Iconv.getDecoder(decoderArgs.encoding, decoderArgs.options),
)
.get(decoderArgs);
// Optimize for common case: encoding="short_string", options=undefined.
let decoder;
if (!options) {
decoder = decoderCache.get(encoding);
if (!decoder) {
decoder = Iconv.getDecoder(encoding);
decoderCache.set(encoding, decoder);
}
} else {
const decoderArgs = { encoding, options };
const decoderKey = JSON.stringify(decoderArgs);
decoder = decoderCache.get(decoderKey);
if (!decoder) {
decoder = Iconv.getDecoder(decoderArgs.encoding, decoderArgs.options);
decoderCache.set(decoderKey, decoder);
}
}

const res = decoder.write(buffer.slice(start, end));
const trail = decoder.end();
Expand Down

0 comments on commit 5f4ed84

Please sign in to comment.