Skip to content

Commit 44da5eb

Browse files
committed
Fix typing around shared array buffers
1 parent c3806dd commit 44da5eb

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/utils/gz.ts

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
44

55
async function readableStreamToBuffer(
6-
stream: ReadableStream<Uint8Array>
7-
): Promise<Uint8Array> {
6+
stream: ReadableStream<Uint8Array<ArrayBuffer>>
7+
): Promise<Uint8Array<ArrayBuffer>> {
88
const reader = stream.getReader();
99
const chunks: Uint8Array[] = [];
1010

@@ -32,9 +32,21 @@ async function readableStreamToBuffer(
3232
return result;
3333
}
3434

35+
// The Streams API doesn't support SAB, and so we need to copy from these to
36+
// use these API's.
37+
function copyBufferIfShared(buffer: Uint8Array): Uint8Array<ArrayBuffer> {
38+
// Check if the buffer is a view into a larger ArrayBuffer (shared)
39+
if (buffer.buffer instanceof SharedArrayBuffer) {
40+
// Create a new buffer with its own ArrayBuffer
41+
return new Uint8Array(buffer);
42+
}
43+
// Return the original buffer if it's not shared
44+
return buffer as Uint8Array<ArrayBuffer>;
45+
}
46+
3547
export async function compress(
36-
data: string | Uint8Array<ArrayBuffer>
37-
): Promise<Uint8Array> {
48+
data: string | Uint8Array
49+
): Promise<Uint8Array<ArrayBuffer>> {
3850
// Encode the data if it's a string
3951
const arrayData =
4052
typeof data === 'string' ? new TextEncoder().encode(data) : data;
@@ -44,22 +56,22 @@ export async function compress(
4456

4557
// Write the data to the compression stream
4658
const writer = compressionStream.writable.getWriter();
47-
writer.write(arrayData);
59+
writer.write(copyBufferIfShared(arrayData));
4860
writer.close();
4961

5062
// Read the compressed data back into a buffer
5163
return readableStreamToBuffer(compressionStream.readable);
5264
}
5365

5466
export async function decompress(
55-
data: Uint8Array<ArrayBuffer>
56-
): Promise<Uint8Array> {
67+
data: Uint8Array
68+
): Promise<Uint8Array<ArrayBuffer>> {
5769
// Create a gzip compression stream
5870
const decompressionStream = new DecompressionStream('gzip');
5971

6072
// Write the data to the compression stream
6173
const writer = decompressionStream.writable.getWriter();
62-
writer.write(data);
74+
writer.write(copyBufferIfShared(data));
6375
writer.close();
6476

6577
// Read the compressed data back into a buffer

0 commit comments

Comments
 (0)