node/lib/internal/buffer.js
Timothy Gu 67aed7972d lib: faster type checks for some types
Backport-PR-URL: https://github.com/nodejs/node/pull/16073
PR-URL: https://github.com/nodejs/node/pull/15663
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Benedikt Meurer <benedikt.meurer@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2017-10-23 09:10:04 -05:00

35 lines
1,021 B
JavaScript

'use strict';
if (!process.binding('config').hasIntl) {
return;
}
const normalizeEncoding = require('internal/util').normalizeEncoding;
const Buffer = require('buffer').Buffer;
const icu = process.binding('icu');
const { isUint8Array } = require('internal/util/types');
// Transcodes the Buffer from one encoding to another, returning a new
// Buffer instance.
function transcode(source, fromEncoding, toEncoding) {
if (!isUint8Array(source))
throw new TypeError('"source" argument must be a Buffer or Uint8Array');
if (source.length === 0) return Buffer.alloc(0);
fromEncoding = normalizeEncoding(fromEncoding) || fromEncoding;
toEncoding = normalizeEncoding(toEncoding) || toEncoding;
const result = icu.transcode(source, fromEncoding, toEncoding);
if (typeof result !== 'number')
return result;
const code = icu.icuErrName(result);
const err = new Error(`Unable to transcode Buffer [${code}]`);
err.code = code;
err.errno = result;
throw err;
}
module.exports = {
transcode
};