From 968defa9947524077ae4da0021be490b2d0a7669 Mon Sep 17 00:00:00 2001 From: londek <48859717+Londek@users.noreply.github.com> Date: Wed, 9 Apr 2025 18:13:38 +0200 Subject: [PATCH 1/2] Implement context IsEmpty check --- context.cc | 10 ++++++++++ context.go | 4 ++++ context.h | 1 + 3 files changed, 15 insertions(+) diff --git a/context.cc b/context.cc index ccaaf2d8b..723bc1f9b 100644 --- a/context.cc +++ b/context.cc @@ -56,6 +56,16 @@ void ContextFree(ContextPtr ctx) { delete ctx; } +int ContextIsEmpty(ContextPtr ctx) { + // ContextFree deletes ContextPtr, so we have to handle the case + // when the context was already closed, gracefully, by go side + if (ctx == nullptr) { + return 1; + } + + return ctx->ptr.IsEmpty(); +} + m_value* tracked_value(m_ctx* ctx, m_value* val) { // (rogchap) we track values against a context so that when the context is // closed (either manually or GC'd by Go) we can also release all the diff --git a/context.go b/context.go index ad7c8965a..82267afb7 100644 --- a/context.go +++ b/context.go @@ -127,6 +127,10 @@ func (c *Context) Close() { c.ptr = nil } +func (c *Context) IsEmpty() bool { + return C.ContextIsEmpty(c.ptr) != 0 +} + func (c *Context) register() { ctxMutex.Lock() r := ctxRegistry[c.ref] diff --git a/context.h b/context.h index 40eb4e9c4..ab4a9d409 100644 --- a/context.h +++ b/context.h @@ -49,6 +49,7 @@ extern ContextPtr NewContext(IsolatePtr iso_ptr, extern int ContextRetainedValueCount(ContextPtr ctx); extern ValuePtr ContextGlobal(ContextPtr ctx_ptr); extern void ContextFree(ContextPtr ctx); +extern int ContextIsEmpty(ContextPtr ctx); extern RtnValue RunScript(ContextPtr ctx_ptr, const char* source, const char* origin); From 1a2567f8e84098f99f01f94d9e30724bfabb0d10 Mon Sep 17 00:00:00 2001 From: londek <48859717+Londek@users.noreply.github.com> Date: Wed, 9 Apr 2025 18:16:57 +0200 Subject: [PATCH 2/2] Add tests for IsEmpty functionality --- context_test.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/context_test.go b/context_test.go index ebacdb6cd..609f92de8 100644 --- a/context_test.go +++ b/context_test.go @@ -152,6 +152,27 @@ func TestRegistryFromJSON(t *testing.T) { } } +func TestContextIsEmpty(t *testing.T) { + iso := v8.NewIsolate() + defer iso.Dispose() + + t.Run("Closed", func(t *testing.T) { + ctx := v8.NewContext(iso) + ctx.Close() + + if !ctx.IsEmpty() { + t.Error("expected context to be empty. ctx.IsEmpty() == false") + } + }) + + t.Run("Active", func(t *testing.T) { + ctx := v8.NewContext(iso) + if ctx.IsEmpty() { + t.Error("expected context to be active. ctx.IsEmpty() == true") + } + }) +} + func BenchmarkContext(b *testing.B) { b.ReportAllocs() iso := v8.NewIsolate()