0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00
nodejs/lib/internal/buffer.js
Anna Henningsen beca3244e2
buffer: allow Uint8Array input to methods
Allow all methods on `buffer` and `Buffer` to take `Uint8Array`
arguments where it makes sense. On the native side, there is
effectively no difference, and as a bonus the `isUint8Array`
check is faster than `instanceof Buffer`.

PR-URL: https://github.com/nodejs/node/pull/10236
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
2016-12-21 07:48:14 +01:00

32 lines
1000 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 } = process.binding('util');
// Transcodes the Buffer from one encoding to another, returning a new
// Buffer instance.
exports.transcode = 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;
};