Skip to content

Commit

Permalink
events: refactor to use more primordials
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Dec 17, 2020
1 parent 32d58d7 commit 5e8dfd7
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 31 deletions.
60 changes: 36 additions & 24 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,19 @@
'use strict';

const {
ArrayPrototypeForEach,
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
ArrayPrototypePush,
ArrayPrototypeShift,
ArrayPrototypeSlice,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
Boolean,
Error,
ErrorCaptureStackTrace,
FunctionPrototypeBind,
FunctionPrototypeCall,
MathMin,
NumberIsNaN,
ObjectCreate,
Expand All @@ -39,6 +48,7 @@ const {
ReflectApply,
ReflectOwnKeys,
String,
StringPrototypeSplit,
Symbol,
SymbolFor,
SymbolAsyncIterator
Expand Down Expand Up @@ -81,7 +91,7 @@ const lazyDOMException = hideStackFrames((message, name) => {


function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
FunctionPrototypeCall(EventEmitter.init, this, opts);
}
module.exports = EventEmitter;
module.exports.once = once;
Expand Down Expand Up @@ -173,7 +183,7 @@ EventEmitter.setMaxListeners =
isEventTarget = require('internal/event_target').isEventTarget;

// Performance for forEach is now comparable with regular for-loop
eventTargets.forEach((target) => {
ArrayPrototypeForEach(eventTargets, (target) => {
if (isEventTarget(target)) {
target[kMaxEventTargetListeners] = n;
target[kMaxEventTargetListenersWarned] = false;
Expand Down Expand Up @@ -224,11 +234,11 @@ function addCatch(that, promise, type, args) {
const then = promise.then;

if (typeof then === 'function') {
then.call(promise, undefined, function(err) {
ReflectApply(then, promise, [undefined, function(err) {
// The callback is called with nextTick to avoid a follow-up
// rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, that, err, type, args);
});
}]);
}
} catch (err) {
that.emit('error', err);
Expand Down Expand Up @@ -281,7 +291,7 @@ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
function identicalSequenceRange(a, b) {
for (let i = 0; i < a.length - 3; i++) {
// Find the first entry of b that matches the current entry of a.
const pos = b.indexOf(a[i]);
const pos = ArrayPrototypeIndexOf(b, a[i]);
if (pos !== -1) {
const rest = b.length - pos;
if (rest > 3) {
Expand Down Expand Up @@ -310,16 +320,18 @@ function enhanceStackTrace(err, own) {
} catch {}
const sep = `\nEmitted 'error' event${ctorInfo} at:\n`;

const errStack = err.stack.split('\n').slice(1);
const ownStack = own.stack.split('\n').slice(1);
const errStack =
ArrayPrototypeSlice(StringPrototypeSplit(err.stack, '\n'), 1);
const ownStack =
ArrayPrototypeSlice(StringPrototypeSplit(own.stack, '\n'), 1);

const [ len, off ] = identicalSequenceRange(ownStack, errStack);
if (len > 0) {
ownStack.splice(off + 1, len - 2,
' [... lines matching original stack trace ...]');
ArrayPrototypeSplice(ownStack, off + 1, len - 2,
' [... lines matching original stack trace ...]');
}

return err.stack + sep + ownStack.join('\n');
return err.stack + sep + ArrayPrototypeJoin(ownStack, '\n');
}

EventEmitter.prototype.emit = function emit(type, ...args) {
Expand All @@ -343,7 +355,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
const capture = {};
ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit);
ObjectDefineProperty(er, kEnhanceStackBeforeInspector, {
value: enhanceStackTrace.bind(this, er, capture),
value: FunctionPrototypeBind(enhanceStackTrace, this, er, capture),
configurable: true
});
} catch {}
Expand Down Expand Up @@ -437,9 +449,9 @@ function _addListener(target, type, listener, prepend) {
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
ArrayPrototypeUnshift(existing, listener);
} else {
existing.push(listener);
ArrayPrototypePush(existing, listener);
}

// Check for listener leak
Expand Down Expand Up @@ -479,14 +491,14 @@ function onceWrapper() {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
return FunctionPrototypeCall(this.listener, this.target);
return ReflectApply(this.listener, this.target, arguments);
}
}

function _onceWrap(target, type, listener) {
const state = { fired: false, wrapFn: undefined, target, type, listener };
const wrapped = onceWrapper.bind(state);
const wrapped = FunctionPrototypeBind(onceWrapper, state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
Expand Down Expand Up @@ -542,7 +554,7 @@ EventEmitter.prototype.removeListener =
return this;

if (position === 0)
list.shift();
ArrayPrototypeShift(list);
else {
if (spliceOne === undefined)
spliceOne = require('internal/util').spliceOne;
Expand Down Expand Up @@ -636,7 +648,7 @@ EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
}
return listenerCount.call(emitter, type);
return FunctionPrototypeCall(listenerCount, emitter, type);
};

EventEmitter.prototype.listenerCount = listenerCount;
Expand Down Expand Up @@ -670,7 +682,7 @@ function arrayClone(arr) {
case 5: return [arr[0], arr[1], arr[2], arr[3], arr[4]];
case 6: return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]];
}
return arr.slice();
return ArrayPrototypeSlice(arr);
}

function unwrapListeners(arr) {
Expand Down Expand Up @@ -791,7 +803,7 @@ function on(emitter, event, options) {
const iterator = ObjectSetPrototypeOf({
next() {
// First, we consume all unread events
const value = unconsumedEvents.shift();
const value = ArrayPrototypeShift(unconsumedEvents);
if (value) {
return PromiseResolve(createIterResult(value, false));
}
Expand All @@ -813,7 +825,7 @@ function on(emitter, event, options) {

// Wait until an event happens
return new Promise(function(resolve, reject) {
unconsumedPromises.push({ resolve, reject });
ArrayPrototypePush(unconsumedPromises, { resolve, reject });
});
},

Expand Down Expand Up @@ -873,18 +885,18 @@ function on(emitter, event, options) {
}

function eventHandler(...args) {
const promise = unconsumedPromises.shift();
const promise = ArrayPrototypeShift(unconsumedPromises);
if (promise) {
promise.resolve(createIterResult(args, false));
} else {
unconsumedEvents.push(args);
ArrayPrototypePush(unconsumedEvents, args);
}
}

function errorHandler(err) {
finished = true;

const toError = unconsumedPromises.shift();
const toError = ArrayPrototypeShift(unconsumedPromises);

if (toError) {
toError.reject(err);
Expand Down
10 changes: 6 additions & 4 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const {
Boolean,
Error,
FunctionPrototypeCall,
FunctionPrototypeBind,
FunctionPrototypeCall,
NumberIsInteger,
ObjectAssign,
ObjectDefineProperties,
Expand Down Expand Up @@ -212,7 +214,7 @@ class Listener {
this.callback =
typeof listener === 'function' ?
listener :
listener.handleEvent.bind(listener);
FunctionPrototypeBind(listener.handleEvent, listener);
}

same(listener, capture) {
Expand Down Expand Up @@ -419,7 +421,7 @@ class EventTarget {
} else {
arg = createEvent();
}
const result = handler.callback.call(this, arg);
const result = FunctionPrototypeCall(handler.callback, this, arg);
if (result !== undefined && result !== null)
addCatch(this, result, createEvent());
} catch (err) {
Expand Down Expand Up @@ -590,11 +592,11 @@ function isEventTarget(obj) {
function addCatch(that, promise, event) {
const then = promise.then;
if (typeof then === 'function') {
then.call(promise, undefined, function(err) {
ReflectApply(then, promise, [undefined, function(err) {
// The callback is called with nextTick to avoid a follow-up
// rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, that, err, event);
});
}]);
}
}

Expand Down
7 changes: 4 additions & 3 deletions lib/trace_events.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

const {
ArrayIsArray,
Set,
ArrayPrototypeJoin,
SafeSet,
Symbol,
} = primordials;

Expand All @@ -27,7 +28,7 @@ const { CategorySet, getEnabledCategories } = internalBinding('trace_events');
const { customInspectSymbol } = require('internal/util');
const { format } = require('internal/util/inspect');

const enabledTracingObjects = new Set();
const enabledTracingObjects = new SafeSet();

class Tracing {
constructor(categories) {
Expand Down Expand Up @@ -63,7 +64,7 @@ class Tracing {
}

get categories() {
return this[kCategories].join(',');
return ArrayPrototypeJoin(this[kCategories], ',');
}

[customInspectSymbol](depth, opts) {
Expand Down

0 comments on commit 5e8dfd7

Please sign in to comment.