Skip to content

Commit

Permalink
use the textencoders from the global instead of Buffer for perf testing
Browse files Browse the repository at this point in the history
  • Loading branch information
trxcllnt committed Jan 9, 2019
1 parent 47f0677 commit 78ecc4c
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions js/src/util/utf8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,27 @@ import {
TextEncoder as TextEncoderPolyfill,
} from 'text-encoding-utf-8';

/** @suppress {missingRequire} */
const _Buffer = typeof Buffer === 'function' ? Buffer : null;
const useNativeEncoders = typeof TextDecoder === 'function' && typeof TextEncoder === 'function';

/** @ignore */
export const decodeUtf8 = ((decoder) => {
/** @suppress {missingRequire} */
const NodeBuffer = typeof Buffer !== 'undefined' ? Buffer : null;
return !NodeBuffer ? decoder.decode.bind(decoder) : (input: ArrayBufferLike | ArrayBufferView) => {
export const decodeUtf8 = ((TextDecoder) => {
if (useNativeEncoders || !_Buffer) {
const decoder = new TextDecoder();
return decoder.decode.bind(decoder);
}
return (input: ArrayBufferLike | ArrayBufferView) => {
const { buffer, byteOffset, length } = toUint8Array(input);
return NodeBuffer.from(buffer, byteOffset, length).toString();
return _Buffer.from(buffer, byteOffset, length).toString();
};
})(new (typeof TextDecoder !== 'undefined' ? TextDecoder : TextDecoderPolyfill)());
})(typeof TextDecoder !== 'undefined' ? TextDecoder : TextDecoderPolyfill);

/** @ignore */
export const encodeUtf8 = ((encoder) => {
/** @suppress {missingRequire} */
const NodeBuffer = typeof Buffer !== 'undefined' ? Buffer : null;
return !NodeBuffer ? encoder.encode.bind(encoder) :
(input = '') => toUint8Array(NodeBuffer.from(input, 'utf8'));
})(new (typeof TextEncoder !== 'undefined' ? TextEncoder : TextEncoderPolyfill)());
export const encodeUtf8 = ((TextEncoder) => {
if (useNativeEncoders || !_Buffer) {
const encoder = new TextEncoder();
return encoder.encode.bind(encoder);
}
return (input = '') => toUint8Array(_Buffer.from(input, 'utf8'));
})(typeof TextEncoder !== 'undefined' ? TextEncoder : TextEncoderPolyfill);

0 comments on commit 78ecc4c

Please sign in to comment.