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

Fix CallbackStack leak on JS #3361

Merged
Merged
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
26 changes: 12 additions & 14 deletions core/js/src/main/scala/cats/effect/CallbackStack.scala
Original file line number Diff line number Diff line change
Expand Up @@ -36,24 +36,22 @@ private final class CallbackStackOps[A](private val callbacks: js.Array[A => Uni
* Invokes *all* non-null callbacks in the queue, starting with the current one. Returns true
* iff *any* callbacks were invoked.
*/
@inline def apply(oc: A, _invoked: Boolean): Boolean = {
var i = callbacks.length - 1
var invoked = _invoked
while (i >= 0) {
val cb = callbacks(i)
if (cb ne null) {
cb(oc)
invoked = true
}
i -= 1
}
invoked
}
@inline def apply(oc: A, invoked: Boolean): Boolean =
callbacks
.asInstanceOf[js.Dynamic]
.reduceRight( // skips deleted indices, but there can still be nulls
(acc: Boolean, cb: A => Unit) =>
if (cb ne null) { cb(oc); true }
else acc,
invoked)
.asInstanceOf[Boolean]

/**
* Removes the current callback from the queue.
*/
@inline def clearCurrent(handle: CallbackStack.Handle): Unit = callbacks(handle) = null
@inline def clearCurrent(handle: Int): Unit =
// deleting an index from a js.Array makes it sparse (aka "holey"), so no memory leak
js.special.delete(callbacks, handle)

@inline def currentHandle(): CallbackStack.Handle = callbacks.length - 1

Expand Down