|
| 1 | +/* eslint-disable no-plusplus */ |
| 2 | +/* eslint-disable no-bitwise */ |
| 3 | + |
| 4 | +// Originally from: https://github.com/google/closure-library/blob/a1f5a029c1b32eb4793a2d920aa52abc085e1bf7/closure/goog/crypt/crypt.js |
| 5 | + |
| 6 | +// Once React Native versions uniformly support TextEncoder this code can be removed. |
| 7 | + |
| 8 | +// Copyright 2008 The Closure Library Authors. All Rights Reserved. |
| 9 | +// |
| 10 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 11 | +// you may not use this file except in compliance with the License. |
| 12 | +// You may obtain a copy of the License at |
| 13 | +// |
| 14 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | +// |
| 16 | +// Unless required by applicable law or agreed to in writing, software |
| 17 | +// distributed under the License is distributed on an "AS-IS" BASIS, |
| 18 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 | +// See the License for the specific language governing permissions and |
| 20 | +// limitations under the License. |
| 21 | + |
| 22 | +export default function toUtf8Array(str: string): Uint8Array { |
| 23 | + const out: number[] = []; |
| 24 | + let p = 0; |
| 25 | + for (let i = 0; i < str.length; i += 1) { |
| 26 | + let c = str.charCodeAt(i); |
| 27 | + if (c < 128) { |
| 28 | + out[p++] = c; |
| 29 | + } else if (c < 2048) { |
| 30 | + out[p++] = (c >> 6) | 192; |
| 31 | + out[p++] = (c & 63) | 128; |
| 32 | + } else if ( |
| 33 | + (c & 0xfc00) === 0xd800 && |
| 34 | + i + 1 < str.length && |
| 35 | + (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00 |
| 36 | + ) { |
| 37 | + // Surrogate Pair |
| 38 | + c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); |
| 39 | + out[p++] = (c >> 18) | 240; |
| 40 | + out[p++] = ((c >> 12) & 63) | 128; |
| 41 | + out[p++] = ((c >> 6) & 63) | 128; |
| 42 | + out[p++] = (c & 63) | 128; |
| 43 | + } else { |
| 44 | + out[p++] = (c >> 12) | 224; |
| 45 | + out[p++] = ((c >> 6) & 63) | 128; |
| 46 | + out[p++] = (c & 63) | 128; |
| 47 | + } |
| 48 | + } |
| 49 | + return Uint8Array.from(out); |
| 50 | +} |
0 commit comments