-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
95 lines (73 loc) · 2.04 KB
/
browser.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const { hex, base64 } = require('./lib')
const utf8 = require('./lib/utf8-browser')
module.exports.toString = function (buf, enc) {
switch (enc) {
case 'hex' :
return hex.toString(buf)
case 'base64' :
return base64.toString(buf)
case 'utf-8' :
case 'utf8' :
case 'ascii' :
case undefined :
return utf8.toString(buf)
default :
throw new Error(`${enc} is not a supported encoding.`)
}
}
module.exports.fromString = function (str, enc) {
switch (enc) {
case 'hex' :
return hex.fromString(str)
case 'base64' :
return base64.fromString(str)
case 'utf-8' :
case 'utf8' :
case 'ascii' :
case undefined :
return utf8.fromString(str)
default :
throw new Error(`${enc} is not a supported encoding.`)
}
}
module.exports.equals = function (a, b) {
if (a.byteLength !== b.byteLength) return false
const len = a.byteLength >>> 2
const A = new Uint32Array(a.buffer, a.byteOffset, len)
const B = new Uint32Array(b.buffer, b.byteOffset, len)
for (let i = 0; i < A.length; i++) {
if (A[i] !== B[i]) return false
}
for (let i = len << 2; i < a.byteLength; i++) {
if (a[i] !== b[i]) return false
}
return true
}
module.exports.compare = function (a, b) {
const min = Math.min(a.byteLength, b.byteLength)
const len = min >>> 2
const A = new Uint32Array(a.buffer, a.byteOffset, len)
const B = new Uint32Array(b.buffer, b.byteOffset, len)
let i
for (i = 0; i < len; i++) {
if (A[i] !== B[i]) break
}
const pos = i << 2
for (let j = pos; j < min; j++) {
if (a[j] < b[j]) return -1
if (a[j] > b[j]) return 1
}
return a.byteLength > b.byteLength ? 1 : a.byteLength < b.byteLength ? -1 : 0
}
module.exports.concat = function (bufs) {
const len = bufs.reduce((len, buf) => len + buf.byteLength, 0)
const ret = new Uint8Array(len)
bufs.reduce((acc, buf) => {
ret.set(buf, acc)
return acc + buf.byteLength
}, 0)
return ret
}
module.exports.allocUnsafe = function (size) {
return new Uint8Array(size)
}