Skip to content

Commit

Permalink
util: add internal sleep() function
Browse files Browse the repository at this point in the history
PR-URL: #30787
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Gus Caplan <me@gus.host>
Reviewed-By: Richard Lau <riclau@uk.ibm.com>
  • Loading branch information
cjihrig committed Dec 7, 2019
1 parent 4ec02d5 commit f446929
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/internal/util.js
Expand Up @@ -26,7 +26,8 @@ const {
getHiddenValue,
setHiddenValue,
arrow_message_private_symbol: kArrowMessagePrivateSymbolIndex,
decorated_private_symbol: kDecoratedPrivateSymbolIndex
decorated_private_symbol: kDecoratedPrivateSymbolIndex,
sleep: _sleep
} = internalBinding('util');
const { isNativeError } = internalBinding('types');

Expand Down Expand Up @@ -385,6 +386,17 @@ function once(callback) {
};
}

let validateUint32;

function sleep(msec) {
// Lazy-load to avoid a circular dependency.
if (validateUint32 === undefined)
({ validateUint32 } = require('internal/validators'));

validateUint32(msec, 'msec');
_sleep(msec);
}

module.exports = {
assertCrypto,
cachedResult,
Expand All @@ -402,6 +414,7 @@ module.exports = {
normalizeEncoding,
once,
promisify,
sleep,
spliceOne,
removeColors,

Expand Down
7 changes: 7 additions & 0 deletions src/node_util.cc
Expand Up @@ -169,6 +169,12 @@ static void SetHiddenValue(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(maybe_value.FromJust());
}

static void Sleep(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsUint32());
uint32_t msec = args[0].As<Uint32>()->Value();
uv_sleep(msec);
}

void ArrayBufferViewHasBuffer(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsArrayBufferView());
args.GetReturnValue().Set(args[0].As<ArrayBufferView>()->HasBuffer());
Expand Down Expand Up @@ -290,6 +296,7 @@ void Initialize(Local<Object> target,
env->SetMethodNoSideEffect(target, "getOwnNonIndexProperties",
GetOwnNonIndexProperties);
env->SetMethodNoSideEffect(target, "getConstructorName", GetConstructorName);
env->SetMethod(target, "sleep", Sleep);

env->SetMethod(target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer);
Local<Object> constants = Object::New(env->isolate());
Expand Down
19 changes: 19 additions & 0 deletions test/parallel/test-util-sleep.js
@@ -0,0 +1,19 @@
// Flags: --expose-internals
'use strict';
require('../common');
const assert = require('assert');
const { sleep } = require('internal/util');

[undefined, null, '', {}, true, false].forEach((value) => {
assert.throws(
() => { sleep(value); },
/The "msec" argument must be of type number/
);
});

[-1, 3.14, NaN, 4294967296].forEach((value) => {
assert.throws(
() => { sleep(value); },
/The value of "msec" is out of range/
);
});

0 comments on commit f446929

Please sign in to comment.