Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: make IterableWeakMap safe to iterate #38523

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions lib/internal/util/iterable_weak_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,22 @@ class IterableWeakMap {
return true;
}

*[SymbolIterator]() {
for (const ref of this.#refSet) {
const key = ref.deref();
if (!key) continue;
[SymbolIterator]() {
const iterator = this.#refSet[SymbolIterator]();

const next = () => {
const result = iterator.next();
if (result.done) return result;
const key = result.value.deref();
if (key == null) return next();
const { value } = this.#weakMap.get(key);
yield value;
}
return { done: false, value };
};

return {
[SymbolIterator]() { return this; },
next,
};
}
}

Expand Down
8 changes: 7 additions & 1 deletion test/parallel/test-internal-iterable-weak-map.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
// Flags: --expose-gc --expose-internals
'use strict';

require('../common');
const common = require('../common');
const { deepStrictEqual, strictEqual } = require('assert');
const { IterableWeakMap } = require('internal/util/iterable_weak_map');

// Ensures iterating over the map does not rely on methods which can be
// mutated by users.
Reflect.getPrototypeOf(function*() {}).prototype.next = common.mustNotCall();
Reflect.getPrototypeOf(new Set()[Symbol.iterator]()).next =
common.mustNotCall();

// It drops entry if a reference is no longer held.
{
const wm = new IterableWeakMap();
Expand Down