v2 / vlib / v / tests / pointers / unsafe_test.c.v
104 lines · 93 sloc · 1.71 KB · 1411c2710b03c53fa0de08d39c656d98721783f6
Raw
1fn test_ptr_assign() {
2 v := [int(5), 6, 77, 1]
3 unsafe {
4 mut p := &v[0]
5 (*p)++
6 p++ // p now points to v[1]
7 (*p) += 2
8 p += 2 // p now points to v[3]
9 *p = 31
10 }
11 assert v[0] == 6
12 assert v[1] == 8
13 assert v[2] == 77
14 assert v[3] == 31
15}
16
17fn test_double_ptr() {
18 i := 5
19 j := 7
20 unsafe {
21 mut x := &i
22 mut p := &x
23 (*p) = &j
24 assert x == &j
25 }
26 // ///////
27 mut x := unsafe { &int(0) }
28 unsafe {
29 mut p := &x
30 (*p) = &int(1)
31 }
32 assert ptr_str(x) == ptr_str(unsafe { &int(1) })
33}
34
35fn test_ptr_infix() {
36 v := 4
37 mut q := unsafe { &v - 1 }
38 q = unsafe { q + 3 }
39 assert ptr_str(q) == ptr_str(unsafe { &v + 2 })
40}
41
42struct S1 {
43}
44
45@[unsafe]
46fn (s S1) f() {
47}
48
49fn test_funcs() {
50 s := S1{}
51 unsafe { s.f() }
52 _ = C.strerror(0) // @[trusted] function prototype in builtin/cfns.c.v
53}
54
55fn test_if_expr_unsafe() {
56 i := 4
57 ii := 123
58 p := if unsafe { true } { unsafe { &i } } else { unsafe { &ii } }
59 assert *p == 4
60}
61
62fn unsafe_if_stmt() int {
63 i := 4
64 unsafe {
65 if true {
66 return (&i)[0]
67 }
68 }
69 return i
70}
71
72fn test_unsafe_if_stmt() {
73 x := unsafe_if_stmt()
74 assert x == 4
75}
76
77const fixedbytes = [100]u8{}
78
79fn test_unsafe_pointers() {
80 fsize := fixedbytes.len
81 src := &fixedbytes[0]
82
83 b := []u8{}
84 eprintln('b.data before: ${b.data}')
85 eprintln('b.len before: ${b.len}')
86 eprintln('b.cap before: ${b.cap}')
87 assert b.len == 0
88 unsafe {
89 // here b will be setup to work with the mmaped region
90 mut pdata := &b.data
91 mut plen := &b.len
92 mut pcap := &b.cap
93 // note that pdata, plen, pcap are used here:
94 *pdata = src
95 *plen = int(fsize)
96 *pcap = int(fsize)
97 }
98 assert b.len == 100
99 assert b.cap == 100
100 assert b.data == src
101 eprintln('b.data after: ${b.data}')
102 eprintln('b.len after: ${b.len}')
103 eprintln('b.cap after: ${b.cap}')
104}
105