File size: 1,238 Bytes
e36aeda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package test

import (
	"internal/testenv"
	"testing"
	"unsafe"
)

// Stack allocation size for variable-sized allocations.
// Matches constant of the same name in ../walk/builtin.go:walkMakeSlice.
const maxStackSize = 32

//go:noinline
func genericUse[T any](s []T) {
	// Doesn't escape s.
}

func TestStackAllocation(t *testing.T) {
	testenv.SkipIfOptimizationOff(t)

	type testCase struct {
		f        func(int)
		elemSize uintptr
	}

	for _, tc := range []testCase{
		{
			f: func(n int) {
				genericUse(make([]int, n))
			},
			elemSize: unsafe.Sizeof(int(0)),
		},
		{
			f: func(n int) {
				genericUse(make([]*byte, n))
			},
			elemSize: unsafe.Sizeof((*byte)(nil)),
		},
		{
			f: func(n int) {
				genericUse(make([]string, n))
			},
			elemSize: unsafe.Sizeof(""),
		},
	} {
		max := maxStackSize / int(tc.elemSize)
		if n := testing.AllocsPerRun(10, func() {
			tc.f(max)
		}); n != 0 {
			t.Fatalf("unexpected allocation: %f", n)
		}
		if n := testing.AllocsPerRun(10, func() {
			tc.f(max + 1)
		}); n != 1 {
			t.Fatalf("unexpected allocation: %f", n)
		}
	}
}