diff --git a/runtime.go b/runtime.go index 552ae139..8b7a3995 100644 --- a/runtime.go +++ b/runtime.go @@ -501,6 +501,9 @@ func (r *Runtime) MemUsage(ctx *MemUsageContext) (memUsage uint64, newMemUsage u if err != nil { return memUsage, newMemUsage, err } + if exceeded := ctx.MemUsageLimitExceeded(memUsage); exceeded { + return memUsage, newMemUsage, nil + } } if r.vm == nil { diff --git a/runtime_test.go b/runtime_test.go index 964add28..7dd4ad59 100644 --- a/runtime_test.go +++ b/runtime_test.go @@ -3087,14 +3087,34 @@ func TestRuntimeMemUsage(t *testing.T) { name: "should account for globalObject given a runtime with non-empty globalObject", val: &Runtime{ globalObject: &Object{ - self: &baseObject{propNames: []unistring.String{"test"}, values: map[unistring.String]Value{"test": valueInt(99)}}, + self: &baseObject{ + propNames: []unistring.String{"test0", "test1", "test2"}, + values: map[unistring.String]Value{"test0": valueInt(99), "test1": valueInt(99), "test2": valueInt(99)}, + }, }, }, memLimit: 100, // baseObject overhead + key/value pair with string overhead - expectedMem: SizeEmptyStruct + (4 + SizeString + SizeInt), + expectedMem: SizeEmptyStruct + (5+SizeString+SizeInt)*3, // baseObject overhead + key/value pair with string overhead - expectedNewMem: SizeEmptyStruct + (4 + SizeString + SizeInt), + expectedNewMem: SizeEmptyStruct + (5+SizeString+SizeInt)*3, + errExpected: nil, + }, + { + name: "should exit early given a runtime with non-empty globalObject exceeding the memory limit", + val: &Runtime{ + globalObject: &Object{ + self: &baseObject{ + propNames: []unistring.String{"test0", "test1", "test2"}, + values: map[unistring.String]Value{"test0": valueInt(99), "test1": valueInt(99), "test2": valueInt(99)}, + }, + }, + }, + memLimit: 0, + // baseObject overhead + key/value pair with string overhead + expectedMem: SizeEmptyStruct + (5 + SizeString + SizeInt), + // baseObject overhead + key/value pair with string overhead + expectedNewMem: SizeEmptyStruct + (5 + SizeString + SizeInt), errExpected: nil, }, {