Skip to content

Commit cf4dc80

Browse files
aduh95targos
authored andcommitted
lib: make IterableWeakMap safe to iterate
PR-URL: #38523 Reviewed-By: Rich Trott <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 1d9fd49 commit cf4dc80

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

lib/internal/util/iterable_weak_map.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,22 @@ class IterableWeakMap {
5454
return true;
5555
}
5656

57-
*[SymbolIterator]() {
58-
for (const ref of this.#refSet) {
59-
const key = ref.deref();
60-
if (!key) continue;
57+
[SymbolIterator]() {
58+
const iterator = this.#refSet[SymbolIterator]();
59+
60+
const next = () => {
61+
const result = iterator.next();
62+
if (result.done) return result;
63+
const key = result.value.deref();
64+
if (key == null) return next();
6165
const { value } = this.#weakMap.get(key);
62-
yield value;
63-
}
66+
return { done: false, value };
67+
};
68+
69+
return {
70+
[SymbolIterator]() { return this; },
71+
next,
72+
};
6473
}
6574
}
6675

test/parallel/test-internal-iterable-weak-map.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
// Flags: --expose-gc --expose-internals
22
'use strict';
33

4-
require('../common');
4+
const common = require('../common');
55
const { deepStrictEqual, strictEqual } = require('assert');
66
const { IterableWeakMap } = require('internal/util/iterable_weak_map');
77

8+
// Ensures iterating over the map does not rely on methods which can be
9+
// mutated by users.
10+
Reflect.getPrototypeOf(function*() {}).prototype.next = common.mustNotCall();
11+
Reflect.getPrototypeOf(new Set()[Symbol.iterator]()).next =
12+
common.mustNotCall();
13+
814
// It drops entry if a reference is no longer held.
915
{
1016
const wm = new IterableWeakMap();

0 commit comments

Comments
 (0)