-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutf32.js
More file actions
67 lines (56 loc) · 2.3 KB
/
utf32.js
File metadata and controls
67 lines (56 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { assertU8, E_STRING } from './fallback/_utils.js'
import { isHermes, isLE } from './fallback/platform.js'
import * as js from './fallback/utf32.js'
import * as utf16 from '@exodus/bytes/utf16.js'
// Unlike utf8, operates on Uint32Arrays by default
function encode(str, loose = false, format = 'uint32') {
if (typeof str !== 'string') throw new TypeError(E_STRING)
if (format !== 'uint32' && format !== 'uint8-le' && format !== 'uint8-be') {
throw new TypeError('Unknown format')
}
const u32 = js.utf16to32(loose ? utf16.utf16fromStringLoose(str) : utf16.utf16fromString(str))
if (format === 'uint32') return u32
if (format === 'uint8-le' || format === 'uint8-be') {
const u8 = js.to8(u32)
if (isLE !== (format === 'uint8-le')) js.swap32(u8)
return u8
}
/* c8 ignore next */
throw new Error('Unreachable')
}
function decode(input, loose = false, format = 'uint32') {
let u32
switch (format) {
case 'uint32':
if (!(input instanceof Uint32Array)) throw new TypeError('Expected an Uint32Array')
u32 = input
break
case 'uint8-le':
assertU8(input)
if (input.byteLength % 4 !== 0) throw new TypeError('Expected length to be a multiple of 4')
u32 = js.to32input(input, true)
break
case 'uint8-be':
assertU8(input)
if (input.byteLength % 4 !== 0) throw new TypeError('Expected length to be a multiple of 4')
u32 = js.to32input(input, false)
break
default:
throw new TypeError('Unknown format')
}
// TODO: recheck spidermonkey/Firefox/jsc perf
if (!js.isWellFormed(u32)) {
if (!loose) throw new RangeError(js.E_STRICT)
if (u32.buffer === input.buffer) u32 = new Uint32Array(u32)
js.toWellFormed(u32)
}
// Significantly faster on Hermes
if (isHermes) return js.decode(u32, loose)
// Significantly faster on Node.js, Chromium, v8, WebKit
const u16 = js.utf32to16view(u32)
return loose ? utf16.utf16toStringLoose(u16) : utf16.utf16toString(u16)
}
export const utf32fromString = (str, format = 'uint32') => encode(str, false, format)
export const utf32fromStringLoose = (str, format = 'uint32') => encode(str, true, format)
export const utf32toString = (arr, format = 'uint32') => decode(arr, false, format)
export const utf32toStringLoose = (arr, format = 'uint32') => decode(arr, true, format)