v2 / vlib / v / tests / builtin_arrays / array_cast_test.v
53 lines · 48 sloc · 913 bytes · 5cf51fbfdd8d5b82635e3e39cc29951a84cc0612
Raw
1fn test_array_cast() {
2 mut keys := ['']
3 unsafe {
4 vp := voidptr(&keys)
5 mut p := &[]string(vp)
6 (*p)[0] = 'hi'
7 assert *p == ['hi']
8 }
9 assert keys[0] == 'hi'
10}
11
12fn test_int() {
13 mut arr := [2.3, 3]
14 unsafe {
15 vp := voidptr(&arr)
16 p := &[]f64(vp)
17 assert *p == arr
18 }
19}
20
21fn test_ref_array_cast_to_elem_ptr_uses_array_data() {
22 mut buf := []u8{len: 4}
23 p := unsafe { &u8(&buf) }
24 unsafe {
25 p[0] = `A`
26 p[1] = `B`
27 }
28 assert buf[0] == `A`
29 assert buf[1] == `B`
30}
31
32struct Header {
33mut:
34 first u8
35 second u8
36}
37
38fn test_ref_array_cast_to_struct_ptr_uses_array_data() {
39 mut buf := []u8{len: int(sizeof(Header))}
40 header := unsafe { &Header(&buf) }
41 unsafe {
42 header.first = `x`
43 header.second = `y`
44 }
45 assert buf[0] == `x`
46 assert buf[1] == `y`
47}
48
49fn test_ref_array_cast_to_array_header_keeps_header_address() {
50 mut arr := [1, 2]
51 header := unsafe { &array(&arr) }
52 assert unsafe { header.len } == 2
53}
54