Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions lib/parsers/string.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
'use strict';

const Iconv = require('iconv-lite');
const LRU = require('lru-cache').default;

exports.decode = function(buffer, encoding, start, end, options) {
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 decoder = Iconv.getDecoder(encoding, options || {});
// Optimize for common case: encoding="short_string", options=undefined.
Copy link
Contributor Author

@sandinmyjoints sandinmyjoints Jan 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I figure encoding is probably constant for most users. For my use case, it's always "cesu8" (for utf8mb3).

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();

return trail ? res + trail : res;
};

exports.encode = function(string, encoding, options) {
exports.encode = function (string, encoding, options) {
if (Buffer.isEncoding(encoding)) {
return Buffer.from(string, encoding);
}
Expand Down