2019-07-17 17:23:52 +00:00
|
|
|
import { Buffer } from 'buffer'
|
2018-09-22 12:28:50 +00:00
|
|
|
|
2019-07-17 17:23:52 +00:00
|
|
|
const typedArrays: Record<string, Function> = {
|
2018-05-24 12:05:46 +00:00
|
|
|
Buffer,
|
|
|
|
ArrayBuffer,
|
|
|
|
Int8Array,
|
|
|
|
Uint8Array,
|
|
|
|
Uint8ClampedArray,
|
|
|
|
Int16Array,
|
|
|
|
Uint16Array,
|
|
|
|
Int32Array,
|
|
|
|
Uint32Array,
|
|
|
|
Float32Array,
|
|
|
|
Float64Array
|
|
|
|
}
|
|
|
|
|
2019-07-17 17:23:52 +00:00
|
|
|
type BufferLike = Buffer | ArrayBuffer | ArrayBufferView
|
|
|
|
|
|
|
|
function getType (value: BufferLike) {
|
2018-05-24 12:05:46 +00:00
|
|
|
for (const type of Object.keys(typedArrays)) {
|
|
|
|
if (value instanceof typedArrays[type]) {
|
|
|
|
return type
|
|
|
|
}
|
|
|
|
}
|
2019-07-17 17:23:52 +00:00
|
|
|
throw new Error('Invalid buffer')
|
2018-05-24 12:05:46 +00:00
|
|
|
}
|
|
|
|
|
2019-07-17 17:23:52 +00:00
|
|
|
function getBuffer (value: BufferLike) {
|
2018-06-13 07:38:31 +00:00
|
|
|
if (value instanceof Buffer) {
|
|
|
|
return value
|
|
|
|
} else if (value instanceof ArrayBuffer) {
|
|
|
|
return Buffer.from(value)
|
|
|
|
} else {
|
|
|
|
return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-17 17:23:52 +00:00
|
|
|
export function isBuffer (value: BufferLike) {
|
2018-05-24 12:05:46 +00:00
|
|
|
return ArrayBuffer.isView(value) || value instanceof ArrayBuffer
|
|
|
|
}
|
|
|
|
|
2019-07-17 17:23:52 +00:00
|
|
|
interface BufferMeta {
|
|
|
|
type: keyof typeof typedArrays;
|
|
|
|
data: Buffer;
|
|
|
|
length: number | undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function bufferToMeta (value: BufferLike): BufferMeta {
|
2018-05-24 12:05:46 +00:00
|
|
|
return {
|
|
|
|
type: getType(value),
|
2018-06-13 07:38:31 +00:00
|
|
|
data: getBuffer(value),
|
2019-07-17 17:23:52 +00:00
|
|
|
// NB. We only use length when decoding Int8Array and friends.
|
|
|
|
// For other buffer-like types this is expected to be undefined.
|
|
|
|
length: (value as Buffer).length
|
2018-05-24 12:05:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-17 17:23:52 +00:00
|
|
|
export function metaToBuffer (value: BufferMeta) {
|
2018-05-24 12:05:46 +00:00
|
|
|
const constructor = typedArrays[value.type]
|
2018-06-13 07:38:31 +00:00
|
|
|
const data = getBuffer(value.data)
|
2018-05-24 12:05:46 +00:00
|
|
|
|
|
|
|
if (constructor === Buffer) {
|
|
|
|
return data
|
|
|
|
} else if (constructor === ArrayBuffer) {
|
|
|
|
return data.buffer
|
|
|
|
} else if (constructor) {
|
2019-07-17 17:23:52 +00:00
|
|
|
return new (constructor as any)(data.buffer, data.byteOffset, value.length)
|
2018-05-24 12:05:46 +00:00
|
|
|
} else {
|
|
|
|
return data
|
|
|
|
}
|
|
|
|
}
|