Skip to content

Commit b785884

Browse files
committed
runtime: fix returning an empty array crash
1 parent fbd40a6 commit b785884

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

src/runtime/js.zig

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3469,11 +3469,16 @@ fn simpleZigValueToJs(isolate: v8.Isolate, value: anytype, comptime fail: bool)
34693469
else => @compileError("Invalid TypeArray type: " ++ @typeName(value_type)),
34703470
};
34713471

3472-
const buffer_len = len * bits / 8;
3473-
const backing_store = v8.BackingStore.init(isolate, buffer_len);
3474-
const data: [*]u8 = @alignCast(@ptrCast(backing_store.getData()));
3475-
@memcpy(data[0..buffer_len], @as([]const u8, @ptrCast(values))[0..buffer_len]);
3476-
const array_buffer = v8.ArrayBuffer.initWithBackingStore(isolate, &backing_store.toSharedPtr());
3472+
var array_buffer: v8.ArrayBuffer = undefined;
3473+
if (len == 0) {
3474+
array_buffer = v8.ArrayBuffer.init(isolate, 0);
3475+
} else {
3476+
const buffer_len = len * bits / 8;
3477+
const backing_store = v8.BackingStore.init(isolate, buffer_len);
3478+
const data: [*]u8 = @alignCast(@ptrCast(backing_store.getData()));
3479+
@memcpy(data[0..buffer_len], @as([]const u8, @ptrCast(values))[0..buffer_len]);
3480+
array_buffer = v8.ArrayBuffer.initWithBackingStore(isolate, &backing_store.toSharedPtr());
3481+
}
34773482

34783483
switch (@typeInfo(value_type)) {
34793484
.int => |n| switch (n.signedness) {

src/runtime/test_primitive_types.zig

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,10 @@ const Primitives = struct {
118118
}
119119
}
120120

121+
pub fn _returnEmptyUint8(_: *const Primitives) Env.TypedArray(u8) {
122+
return .{ .values = &.{} };
123+
}
124+
121125
pub fn _returnUint8(_: *const Primitives) Env.TypedArray(u8) {
122126
return .{ .values = &.{ 10, 20, 250 } };
123127
}
@@ -325,6 +329,7 @@ test "JS: primitive types" {
325329
.{ "try { p.intu64(arr_i64) } catch(e) { e instanceof TypeError; }", "true" },
326330
.{ "try { p.intu64(arr_u32) } catch(e) { e instanceof TypeError; }", "true" },
327331

332+
.{ "p.returnEmptyUint8()", "" },
328333
.{ "p.returnUint8()", "10,20,250" },
329334
.{ "p.returnInt8()", "10,-20,-120" },
330335
.{ "p.returnUint16()", "10,200,2050" },

0 commit comments

Comments
 (0)