Skip to content

Commit 26efee3

Browse files
committed
Avoid the need for an extra new Uint8Array(…)
1 parent 7777402 commit 26efee3

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

packages/encoding/src/uint8array.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1+
// See https://stackoverflow.com/q/79803845/2013738 for why this is needed
2+
function isUint8ArrayOfArrayBuffer(source: Uint8Array): source is Uint8Array<ArrayBuffer> {
3+
return source.buffer instanceof ArrayBuffer;
4+
}
5+
16
/**
27
* Safely converts a Uint8Array<T> or Uint8Array into a
38
* Uint8Array<ArrayBuffer>, often without a copy at runtime.
49
*
510
* @see https://github.com/paulmillr/scure-base/issues/53
611
*/
7-
export function fixUint8Array<T extends ArrayBufferLike>(source: Uint8Array<T>): Uint8Array<ArrayBuffer> {
8-
const buffer = source.buffer;
9-
if (buffer instanceof ArrayBuffer) {
10-
return new Uint8Array(buffer, source.byteOffset, source.length); // new instance just to make TS happy without unsafe cast
11-
}
12-
12+
export function fixUint8Array(source: Uint8Array<ArrayBuffer> | Uint8Array): Uint8Array<ArrayBuffer> {
13+
if (isUint8ArrayOfArrayBuffer(source)) return source;
1314
const copy = new ArrayBuffer(source.byteLength); // allocate memory
1415
const out = new Uint8Array(copy);
1516
out.set(source); // copy data

0 commit comments

Comments
 (0)