UNPKG

2.73 kBJavaScriptView Raw
1/**
2 * Utility functions to work with buffers (Uint8Array).
3 *
4 * @module buffer
5 */
6
7import * as string from './string.js'
8import * as env from './environment.js'
9import * as encoding from './encoding.js'
10import * as decoding from './decoding.js'
11
12/**
13 * @param {number} len
14 */
15export const createUint8ArrayFromLen = len => new Uint8Array(len)
16
17/**
18 * Create Uint8Array with initial content from buffer
19 *
20 * @param {ArrayBuffer} buffer
21 * @param {number} byteOffset
22 * @param {number} length
23 */
24export const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)
25
26/**
27 * Create Uint8Array with initial content from buffer
28 *
29 * @param {ArrayBuffer} buffer
30 */
31export const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)
32
33/* istanbul ignore next */
34/**
35 * @param {Uint8Array} bytes
36 * @return {string}
37 */
38const toBase64Browser = bytes => {
39 let s = ''
40 for (let i = 0; i < bytes.byteLength; i++) {
41 s += string.fromCharCode(bytes[i])
42 }
43 // eslint-disable-next-line no-undef
44 return btoa(s)
45}
46
47/**
48 * @param {Uint8Array} bytes
49 * @return {string}
50 */
51const toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')
52
53/* istanbul ignore next */
54/**
55 * @param {string} s
56 * @return {Uint8Array}
57 */
58const fromBase64Browser = s => {
59 // eslint-disable-next-line no-undef
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 * @param {string} s
70 */
71const fromBase64Node = s => {
72 const buf = Buffer.from(s, 'base64')
73 return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
74}
75
76/* istanbul ignore next */
77export const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node
78
79/* istanbul ignore next */
80export const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node
81
82/**
83 * Copy the content of an Uint8Array view to a new ArrayBuffer.
84 *
85 * @param {Uint8Array} uint8Array
86 * @return {Uint8Array}
87 */
88export const copyUint8Array = uint8Array => {
89 const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)
90 newBuf.set(uint8Array)
91 return newBuf
92}
93
94/**
95 * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.
96 * See encoding.writeAny for more information.
97 *
98 * @param {any} data
99 * @return {Uint8Array}
100 */
101export const encodeAny = data => {
102 const encoder = encoding.createEncoder()
103 encoding.writeAny(encoder, data)
104 return encoding.toUint8Array(encoder)
105}
106
107/**
108 * Decode an any-encoded value.
109 *
110 * @param {Uint8Array} buf
111 * @return {any}
112 */
113export const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))