1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | import * as string from './string.js'
|
8 | import * as env from './environment.js'
|
9 | import * as encoding from './encoding.js'
|
10 | import * as decoding from './decoding.js'
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export const createUint8ArrayFromLen = len => new Uint8Array(len)
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | export const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | export const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | const toBase64Browser = bytes => {
|
39 | let s = ''
|
40 | for (let i = 0; i < bytes.byteLength; i++) {
|
41 | s += string.fromCharCode(bytes[i])
|
42 | }
|
43 |
|
44 | return btoa(s)
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | const toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | const fromBase64Browser = s => {
|
59 |
|
60 | const a = atob(s)
|
61 | const bytes = createUint8ArrayFromLen(a.length)
|
62 | for (let i = 0; i < a.length; i++) {
|
63 | bytes[i] = a.charCodeAt(i)
|
64 | }
|
65 | return bytes
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | const fromBase64Node = s => {
|
72 | const buf = Buffer.from(s, 'base64')
|
73 | return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
|
74 | }
|
75 |
|
76 |
|
77 | export const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node
|
78 |
|
79 |
|
80 | export const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | export const copyUint8Array = uint8Array => {
|
89 | const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)
|
90 | newBuf.set(uint8Array)
|
91 | return newBuf
|
92 | }
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | export const encodeAny = data => {
|
102 | const encoder = encoding.createEncoder()
|
103 | encoding.writeAny(encoder, data)
|
104 | return encoding.toUint8Array(encoder)
|
105 | }
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 | export const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))
|