v4 / vlib / v / tests / pointers / offsetof_test.v
63 lines · 53 sloc · 1.3 KB · 34ecea37ceabcbdd214a0413b6491cd39efdb2e6
Raw
1import math.complex
2
3struct Cat {
4 name string
5 breed string
6 age int
7}
8
9struct OffsetInlineOnly {
10 a int
11 b int
12}
13
14struct OffsetConstOnly {
15 a int
16 b int
17}
18
19type Feline = Cat
20
21const offset_const_only_b = __offsetof(OffsetConstOnly, b)
22
23fn test_offsetof() {
24 cat := Cat{
25 name: 'Cthulhu'
26 breed: 'Great Old One'
27 age: 2147483647
28 }
29 unsafe {
30 assert *(&string(&u8(&cat) + __offsetof(Cat, name))) == 'Cthulhu'
31 assert *(&string(&u8(&cat) + __offsetof(Cat, breed))) == 'Great Old One'
32 assert *(&int(&u8(&cat) + __offsetof(Cat, age))) == 2147483647
33 }
34}
35
36fn test_offsetof_inline_only_marks_struct_as_used() {
37 assert __offsetof(OffsetInlineOnly, b) == 4
38}
39
40fn test_offsetof_const_marks_struct_as_used() {
41 assert offset_const_only_b == 4
42}
43
44fn test_offsetof_struct_from_another_module() {
45 num := complex.Complex{1.0, 1.0}
46 unsafe {
47 assert *(&f64(&u8(&num) + __offsetof(complex.Complex, re))) == 1.0
48 assert *(&f64(&u8(&num) + __offsetof(complex.Complex, im))) == 1.0
49 }
50}
51
52fn test_offsetof_alias() {
53 fel := Feline{
54 name: 'Cthulhu'
55 breed: 'Great Old One'
56 age: 2147483647
57 }
58 unsafe {
59 assert *(&string(&u8(&fel) + __offsetof(Feline, name))) == 'Cthulhu'
60 assert *(&string(&u8(&fel) + __offsetof(Feline, breed))) == 'Great Old One'
61 assert *(&int(&u8(&fel) + __offsetof(Feline, age))) == 2147483647
62 }
63}
64