v2 / vlib / v / tests / pointers / pointers_multilevel_casts_test.v
105 lines · 95 sloc · 1.96 KB · 06c31c8aac51f02d246a1ec4a75b5d1315a9024c
Raw
1struct Struct {
2 name string
3 x int
4}
5
6struct EventA24309 {
7mut:
8 value int
9}
10
11struct EventB24309 {
12mut:
13 value int
14}
15
16type Event24309 = EventA24309 | EventB24309
17
18fn increment_sumtype_value_24309(event &Event24309) int {
19 unsafe {
20 mut event_a := &EventA24309(event)
21 event_a.value++
22 event_a.value++
23 return event_a.value
24 }
25}
26
27fn test_byte_pointer_casts() {
28 unsafe {
29 pb := &u8(1)
30 ppb := &&u8(2)
31 pppb := &&&u8(3)
32 ppppb := &&&&u8(4)
33 assert voidptr(pb).str() == '0x1'
34 assert voidptr(ppb).str() == '0x2'
35 assert voidptr(pppb).str() == '0x3'
36 assert voidptr(ppppb).str() == '0x4'
37 }
38}
39
40fn test_char_pointer_casts() {
41 unsafe {
42 pc := &char(5)
43 ppc := &&char(6)
44 pppc := &&&char(7)
45 ppppc := &&&&char(8)
46 assert voidptr(pc).str() == '0x5'
47 assert voidptr(ppc).str() == '0x6'
48 assert voidptr(pppc).str() == '0x7'
49 assert voidptr(ppppc).str() == '0x8'
50 }
51}
52
53fn test_struct_pointer_casts() {
54 unsafe {
55 ps := &Struct(9)
56 pps := &&Struct(10)
57 ppps := &&&Struct(11)
58 pppps := &&&&Struct(12)
59 assert voidptr(ps).str() == '0x9'
60 assert voidptr(pps).str() == '0xa'
61 assert voidptr(ppps).str() == '0xb'
62 assert voidptr(pppps).str() == '0xc'
63 }
64}
65
66fn test_struct_pointer_casts_with_field_selectors() {
67 ss := &Struct{
68 name: 'abc'
69 x: 123
70 }
71 dump(ss)
72 pss := voidptr(ss)
73 if unsafe { &Struct(pss).name } == 'abc' {
74 assert true
75 }
76 if unsafe { &Struct(pss).x } == 123 {
77 // &Struct cast and selecting .x
78 assert true
79 }
80 if unsafe { &&Struct(pss) != 0 } {
81 // &&Struct
82 assert true
83 }
84}
85
86fn test_pointer_casts_with_indexing() {
87 mut numbers := [5]u64{}
88 numbers[0] = 123
89 numbers[1] = 456
90 unsafe {
91 pnumbers := voidptr(&numbers[0])
92 assert &u64(pnumbers)[0] == 123
93 assert &u64(pnumbers)[1] == 456
94 idx := 1
95 assert &u64(pnumbers)[idx] == 456
96 }
97}
98
99fn test_sumtype_pointer_cast_uses_underlying_variant_pointer() {
100 mut event := Event24309(EventA24309{
101 value: 4
102 })
103 assert increment_sumtype_value_24309(&event) == 6
104 assert (event as EventA24309).value == 6
105}
106