diff options
author | 2023-03-02 09:00:20 -0800 | |
---|---|---|
committer | 2023-03-02 09:00:20 -0800 | |
commit | 20930849ce0bcfe685e8042a4a53d9c9dd67343b (patch) | |
tree | 2f7eaa99dd6e273bcd0e26c2adc772f2aefc7bf1 /src | |
parent | efdf64746076c4ed09da87e41d7de81c2b659dab (diff) | |
download | bun-20930849ce0bcfe685e8042a4a53d9c9dd67343b.tar.gz bun-20930849ce0bcfe685e8042a4a53d9c9dd67343b.tar.zst bun-20930849ce0bcfe685e8042a4a53d9c9dd67343b.zip |
Fix `Bun.sleepSync` to actually use milliseconds (#2242)
* Fix Bun.sleep/sleepSync to actually use milliseconds
`Bun.sleepSync` was accidentally treating its argument as seconds rather than milliseconds as the docs stated. This is a breaking change in that the function now behaves as documented. Fixed relevant tests.
* sleepSync: add more argument checking, tests
Diffstat (limited to 'src')
-rw-r--r-- | src/bun.js/api/bun.zig | 28 |
1 files changed, 24 insertions, 4 deletions
diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig index 1c991eece..5dc3abcf9 100644 --- a/src/bun.js/api/bun.zig +++ b/src/bun.js/api/bun.zig @@ -861,12 +861,32 @@ pub fn sleepSync( arguments: []const js.JSValueRef, _: js.ExceptionRef, ) js.JSValueRef { - if (js.JSValueIsNumber(ctx, arguments[0])) { - const seconds = JSValue.fromRef(arguments[0]).asNumber(); - if (seconds > 0 and std.math.isFinite(seconds)) std.time.sleep(@floatToInt(u64, seconds * 1000) * std.time.ns_per_ms); + // This function always returns undefined + const ret = js.JSValueMakeUndefined(ctx); + + // Expect at least one argument. We allow more than one but ignore them; this + // is useful for supporting things like `[1, 2].map(sleepSync)` + if (arguments.len < 1) { + ctx.throwInvalidArguments("expected one argument, got {}", .{arguments.len}); + return ret; } + const arg = JSValue.fromRef(arguments[0]); - return js.JSValueMakeUndefined(ctx); + // The argument must be a number + if (!arg.isNumber()) { + ctx.throwInvalidArguments("argument to sleepSync must be a number, got {}", .{arg.jsTypeLoose()}); + return ret; + } + + //NOTE: if argument is > max(i32) then it will be truncated + const milliseconds = arg.coerce(i32, ctx); + if (milliseconds < 0) { + ctx.throwInvalidArguments("argument to sleepSync must not be negative, got {}", .{milliseconds}); + return ret; + } + + std.time.sleep(@intCast(u64, milliseconds) * std.time.ns_per_ms); + return ret; } pub fn createNodeFS( |