-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathensure_buffer.ts
More file actions
27 lines (24 loc) · 889 Bytes
/
ensure_buffer.ts
File metadata and controls
27 lines (24 loc) · 889 Bytes
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
import { Buffer } from 'buffer';
import { BSONTypeError } from './error';
import { isAnyArrayBuffer } from './parser/utils';
/**
* Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
*
* @param potentialBuffer - The potential buffer
* @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
* wraps a passed in Uint8Array
* @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
*/
export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer {
if (ArrayBuffer.isView(potentialBuffer)) {
return Buffer.from(
potentialBuffer.buffer,
potentialBuffer.byteOffset,
potentialBuffer.byteLength
);
}
if (isAnyArrayBuffer(potentialBuffer)) {
return Buffer.from(potentialBuffer);
}
throw new BSONTypeError('Must use either Buffer or TypedArray');
}