TextEncoder/Decoder polyfill optimisation (#286)
This commit is contained in:
@@ -2,12 +2,24 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
let encoder: TextEncoder | undefined;
|
||||
let encoder: { encode: (value: string) => Uint8Array };
|
||||
|
||||
function polyfilledEncode (value: string): Uint8Array {
|
||||
const u8a = new Uint8Array(value.length);
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
u8a[i] = value.charCodeAt(i);
|
||||
}
|
||||
|
||||
return u8a;
|
||||
}
|
||||
|
||||
try {
|
||||
encoder = new TextEncoder();
|
||||
} catch (error) {
|
||||
// noop
|
||||
encoder = {
|
||||
encode: polyfilledEncode
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,15 +40,7 @@ try {
|
||||
export default function stringToU8a (value?: string): Uint8Array {
|
||||
if (!value) {
|
||||
return new Uint8Array([]);
|
||||
} else if (encoder) {
|
||||
return encoder.encode(value);
|
||||
}
|
||||
|
||||
const u8a = new Uint8Array(value.length);
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
u8a[i] = value.charCodeAt(i);
|
||||
}
|
||||
|
||||
return u8a;
|
||||
return encoder.encode(value);
|
||||
}
|
||||
|
||||
@@ -2,12 +2,20 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
let decoder: TextDecoder | undefined;
|
||||
let decoder: { decode: (value: Uint8Array) => string };
|
||||
|
||||
function polyfilledDecode (value: Uint8Array): string {
|
||||
return value.reduce((str, code) => {
|
||||
return str + String.fromCharCode(code);
|
||||
}, '');
|
||||
}
|
||||
|
||||
try {
|
||||
decoder = new TextDecoder('utf-8');
|
||||
} catch (error) {
|
||||
// ignore
|
||||
decoder = {
|
||||
decode: polyfilledDecode
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,11 +36,7 @@ try {
|
||||
export default function u8aToString (value?: Uint8Array): string {
|
||||
if (!value || !value.length) {
|
||||
return '';
|
||||
} else if (decoder) {
|
||||
return decoder.decode(value);
|
||||
}
|
||||
|
||||
return value.reduce((str, code) => {
|
||||
return str + String.fromCharCode(code);
|
||||
}, '');
|
||||
return decoder.decode(value);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user