v2 / vlib / v / tests / pointers / heap_struct_test.v
134 lines · 117 sloc · 1.77 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1@[heap]
2struct Abc {
3mut:
4 n int
5}
6
7struct St {
8 Abc
9}
10
11struct Qwe {
12mut:
13 f f64
14 a Abc
15}
16
17fn pass_abc(q &Abc) &Abc {
18 return q
19}
20
21fn pass_st(q &St) &St {
22 return q
23}
24
25fn pass_qwe(q &Qwe) &Qwe {
26 return q
27}
28
29fn get_ref_structs() (&Abc, &St, &Qwe) {
30 a := Abc{
31 n: 3
32 }
33 b := St{Abc{
34 n: 7
35 }}
36 x := Qwe{
37 f: 12.25
38 a: Abc{
39 n: 23
40 }
41 }
42 aa := pass_abc(&a)
43 bb := pass_st(&b)
44 xx := pass_qwe(&x)
45 return aa, bb, xx
46}
47
48fn overwrite_stack() f64 {
49 a := 12.5
50 b := 3.5
51 c := a + b
52 return c
53}
54
55fn test_ref_struct() {
56 u, v, w := get_ref_structs()
57 d := overwrite_stack()
58 assert u.n == 3
59 assert v.n == 7
60 assert w.a.n == 23
61 assert d == 16.0
62}
63
64fn return_heap_obj_value_as_ref(qpast Qwe) &Qwe {
65 return &qpast
66}
67
68fn test_value_ref_heap_struct() {
69 mut x := Qwe{
70 f: -13.25
71 a: Abc{
72 n: -129
73 }
74 }
75 y := return_heap_obj_value_as_ref(x)
76 x.f = 22.0625
77 d := overwrite_stack()
78 assert typeof(y).name == '&Qwe'
79 assert x.f == 22.0625
80 assert x.a.n == -129
81 assert y.f == -13.25
82 assert y.a.n == -129
83 assert d == 16.0
84}
85
86struct NotHeap {
87mut:
88 f f64
89}
90
91fn return_struct_value_as_ref(q NotHeap) &NotHeap {
92 return &q
93}
94
95fn test_value_ref_struct() {
96 mut x := NotHeap{
97 f: -17.125
98 }
99 y := return_struct_value_as_ref(x)
100 x.f = 91.0625
101 d := overwrite_stack()
102 assert typeof(y).name == '&NotHeap'
103 assert y.f == -17.125
104 assert x.f == 91.0625
105 assert d == 16.0
106}
107
108fn get_int_ref() &int {
109 i := 49154
110 return &i
111}
112
113fn test_int_ref() {
114 iptr := get_int_ref()
115 assert typeof(iptr).name == '&int'
116 d := overwrite_stack()
117 assert *iptr == 49154
118 assert d == 16.0
119}
120
121fn pass_f64_as_ref(f f64) &f64 {
122 return &f
123}
124
125fn test_value_as_ref() {
126 mut x := -31.75
127 y := pass_f64_as_ref(x)
128 assert typeof(y).name == '&f64'
129 x = 23.0625
130 d := overwrite_stack()
131 assert x == 23.0625
132 assert *y == -31.75
133 assert d == 16.0
134}
135