From a089650e36358a276596dde0a8b26cf3af61c249 Mon Sep 17 00:00:00 2001 From: Lee ByeongJun Date: Mon, 19 Aug 2024 14:47:05 +0900 Subject: [PATCH] cap --- gnovm/pkg/gnolang/uverse_test.go | 64 ++++++++++++++++++++++++++++++++ gnovm/pkg/gnolang/values.go | 5 +++ gnovm/tests/files/cap1.gno | 9 +++++ 3 files changed, 78 insertions(+) create mode 100644 gnovm/tests/files/cap1.gno diff --git a/gnovm/pkg/gnolang/uverse_test.go b/gnovm/pkg/gnolang/uverse_test.go index e84f2ee66bf..1ee27822bfa 100644 --- a/gnovm/pkg/gnolang/uverse_test.go +++ b/gnovm/pkg/gnolang/uverse_test.go @@ -209,3 +209,67 @@ func main() { assertOutput(t, tc.code, tc.expected) } } + +func TestGetCapacityPointerSlice(t *testing.T) { + tests := []struct { + name string + code string + expected string + }{ + { + name: "cap of pointer to array", + code: ` +package test + +func main() { + exp := [...]string{"HELLO"} + x := cap(&exp) + println(x) +}`, + expected: "1\n", + }, + { + name: "cap of array", + code: ` +package test + +func main() { + exp := [...]int{1, 2, 3, 4, 5} + println(cap(exp)) +}`, + expected: "5\n", + }, + { + name: "cap of slice", + code: ` +package test + +func main() { + slice := make([]int, 3, 5) + println(cap(slice)) +}`, + expected: "5\n", + }, + { + name: "cap of nil slice", + code: ` +package test + +func main() { + var slice []int + println(cap(slice)) +}`, + expected: "0\n", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + m := NewMachine("test", nil) + n := MustParseFile("main.go", tc.code) + m.RunFiles(n) + m.RunMain() + assertOutput(t, tc.code, tc.expected) + }) + } +} diff --git a/gnovm/pkg/gnolang/values.go b/gnovm/pkg/gnolang/values.go index 0e2a378b855..b96f69a9652 100644 --- a/gnovm/pkg/gnolang/values.go +++ b/gnovm/pkg/gnolang/values.go @@ -2183,6 +2183,11 @@ func (tv *TypedValue) GetCapacity() int { return cv.GetCapacity() case *NativeValue: return cv.Value.Cap() + case PointerValue: + if av, ok := cv.TV.V.(*ArrayValue); ok { + return av.GetCapacity() + } + panic(fmt.Sprintf("unexpected pointer value for cap(): %s", tv.T.String())) default: panic(fmt.Sprintf("unexpected type for cap(): %s", tv.T.String())) diff --git a/gnovm/tests/files/cap1.gno b/gnovm/tests/files/cap1.gno new file mode 100644 index 00000000000..a834c17b474 --- /dev/null +++ b/gnovm/tests/files/cap1.gno @@ -0,0 +1,9 @@ +package main + +func main() { + exp := [...]int{1, 2, 3, 4, 5} + println(cap(exp)) +} + +// Output: +// 5