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