Debian Codegraph @

internal/runtime/rtype_test.go

raw
1 package runtime
2
3 import (
4 "reflect"
5 "testing"
6 "unsafe"
7 )
8
9 // dataWord returns the data word of the interface value.
10 func dataWord(v any) unsafe.Pointer {
11 return (*emptyInterface)(unsafe.Pointer(&v)).ptr
12 }
13
14 // The expectation is not written by hand: it is what the compiler actually did to the value.
15 // If the type is stored directly, the data word of the interface is the pointer which the value consists of.
16 // Otherwise the data word points to a copy of the value, so it never equals the pointer.
17 func TestIfaceIndir(t *testing.T) {
18 type (
19 ptrStruct struct{ p *int }
20 nestedPtrStruct struct{ s ptrStruct }
21 mapStruct struct{ m map[string]int }
22 funcStruct struct{ f func() }
23 arrayStruct struct{ a [1]*int }
24 twoFieldStruct struct {
25 p *int
26 n int
27 }
28 blankFieldStruct struct {
29 _ struct{}
30 p *int
31 }
32 ifaceStruct struct{ v any }
33 )
34 var (
35 n = 1
36 p = &n
37 m = map[string]int{"a": 1}
38 ch = make(chan int)
39 fn = func() {}
40 up = unsafe.Pointer(p)
41 )
42 word := func(v unsafe.Pointer) unsafe.Pointer { return *(*unsafe.Pointer)(v) }
43
44 for _, test := range []struct {
45 name string
46 v any
47 // pointer is the pointer which the value consists of, or nil if the value is not a single pointer.
48 pointer unsafe.Pointer
49 }{
50 {"pointer", p, up},
51 {"map", m, word(unsafe.Pointer(&m))},
52 {"chan", ch, word(unsafe.Pointer(&ch))},
53 {"func", fn, word(unsafe.Pointer(&fn))},
54 {"unsafe.Pointer", up, up},
55 {"struct of a pointer", ptrStruct{p}, up},
56 {"struct of a struct of a pointer", nestedPtrStruct{ptrStruct{p}}, up},
57 {"struct of a map", mapStruct{m}, word(unsafe.Pointer(&m))},
58 {"struct of a func", funcStruct{fn}, word(unsafe.Pointer(&fn))},
59 {"struct of an array of a pointer", arrayStruct{[1]*int{p}}, up},
60 {"array of a pointer", [1]*int{p}, up},
61 {"array of a struct of a pointer", [1]ptrStruct{{p}}, up},
62 {"struct of a pointer and an int", twoFieldStruct{p, 1}, up},
63 {"struct of a blank field and a pointer", blankFieldStruct{p: p}, up},
64 {"struct of an interface", ifaceStruct{p}, up},
65 {"array of two pointers", [2]*int{p, p}, up},
66 {"empty array of pointers", [0]*int{}, nil},
67 {"empty struct", struct{}{}, nil},
68 {"int", 1, nil},
69 {"string", "a", nil},
70 {"slice", []*int{p}, nil},
71 {"float64", 1.5, nil},
72 {"bool", true, nil},
73 } {
74 t.Run(test.name, func(t *testing.T) {
75 wantIndir := test.pointer == nil || dataWord(test.v) != test.pointer
76 if got := IfaceIndir(reflect.TypeOf(test.v)); got != wantIndir {
77 t.Fatalf("IfaceIndir(%T) = %v, but the compiler stores it with indirect = %v", test.v, got, wantIndir)
78 }
79 })
80 }
81 }