React native support, strengthen TextEncoder/Decoder (#273)

This commit is contained in:
Jaco Greeff
2018-12-17 21:24:02 +01:00
committed by GitHub
parent 928d9bcff5
commit 30bf357d5d
6 changed files with 73 additions and 29 deletions
@@ -5,17 +5,9 @@
// tslint:disable-next-line
if (typeof TextDecoder === 'undefined') {
try {
// @ts-ignore For the Node.js case
// @ts-ignore
global.TextDecoder = require('util').TextDecoder;
} catch (error) {
// @ts-ignore For the old browser case
global.TextDecoder = {
// Very naive ascii-only decoder
decode: (u8a: Uint8Array) => {
return u8a.reduce((str, code) => {
return str + String.fromCharCode(code);
}, '');
}
};
// noop
}
}
@@ -8,18 +8,6 @@ if (typeof TextEncoder === 'undefined') {
// @ts-ignore For the Node.js case
global.TextEncoder = require('util').TextEncoder;
} catch (error) {
// @ts-ignore For the old browser case
global.TextEncoder = {
// Very naive ascii-only encoder
encode: (str: string) => {
const u8a = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
u8a[i] = str.charCodeAt(i);
}
return u8a;
}
};
// noop
}
}
+16 -2
View File
@@ -4,7 +4,13 @@
import './polyfill/textEncoder';
const encoder = new TextEncoder();
let encoder: TextEncoder | undefined;
try {
encoder = new TextEncoder();
} catch (error) {
// noop
}
/**
* @name stringToU8a
@@ -24,7 +30,15 @@ const encoder = new TextEncoder();
export default function stringToU8a (value?: string): Uint8Array {
if (!value) {
return new Uint8Array([]);
} else if (encoder) {
return encoder.encode(value);
}
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;
}