-
Notifications
You must be signed in to change notification settings - Fork 2
/
eface_test.go
114 lines (98 loc) · 2.1 KB
/
eface_test.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package jzon
import (
"log"
"reflect"
"runtime/debug"
"testing"
"unsafe"
"github.com/stretchr/testify/require"
)
func TestEface(t *testing.T) {
f := func(o interface{}) *eface {
return (*eface)(unsafe.Pointer(&o))
}
a := 1
b := 2
ef1 := f(&a)
ef2 := f(&b)
require.Equal(t, ef1.rtype, ef2.rtype)
// require.Equal(t, uintptr(strconv.IntSize/8), uintptr(ef2.data)-uintptr(ef1.data))
t.Logf("%x %x", ef1.rtype, ef1.data)
t.Logf("%x %x", ef2.rtype, ef2.data)
// with reflect
r := reflect.TypeOf(&a)
ef3 := (*eface)(unsafe.Pointer(&r))
require.Equal(t, ef1.rtype, uintptr(ef3.data))
require.Equal(t, ef1.rtype, rtypeOfType(r))
// pack
packed := packEFace(rtype(ef3.data), ef1.data)
t.Logf("%+v", packed)
v, ok := packed.(*int)
t.Logf("%+v %+v", v, ok)
require.True(t, ok)
require.Equal(t, &a, v)
}
func TestEface2(t *testing.T) {
func() {
i := 1
var o interface{} = i
ef := packEFace(rtypeOfType(reflect.TypeOf(i)), unsafe.Pointer(&i))
t.Log("o", o)
t.Log("ef", ef)
i2 := ef.(int)
t.Log("i2", i2)
i = 2
t.Log("o", o)
t.Log("ef", ef)
t.Log("i2", i2)
}()
debug.FreeOSMemory()
}
type testEFstruct struct {
a int
}
func (t testEFstruct) Foo() {
log.Printf("calling %x", unsafe.Pointer(&t))
t.a++
}
func (t testEFstruct) Int() int {
return t.a
}
func TestEface3(t *testing.T) {
var f func(o interface{}, i int)
f = func(o interface{}, i int) {
ef := (*eface)(unsafe.Pointer(&o))
log.Println("->", i, ef.data)
if i > 0 {
f(o, i-1)
}
}
f2 := func(o interface{}) {
v := reflect.ValueOf(o)
o2 := v.Interface()
f(o2, 1)
}
func() {
var st testEFstruct
f(st, 1)
log.Printf("&st, %p", &st)
log.Printf("st.a, %d", st.a)
f2(st)
type ifoo interface {
Foo()
Int() int
}
var foo ifoo = st
log.Println("iface data", (*iface)(unsafe.Pointer(&foo)).data)
foo.Foo()
log.Printf("st.a, %d", st.a)
log.Printf("foo.Int(), %d", foo.Int())
foo.Foo()
log.Printf("foo.Int(), %d", foo.Int())
ef := packEFace(rtypeOfType(reflect.TypeOf(st)), unsafe.Pointer(&st))
foo = ef.(ifoo)
foo.Foo()
log.Printf("st.a, %d", st.a)
}()
debug.FreeOSMemory()
}