v2 / vlib / v / tests / pointers / offsetof_test.v
43 lines · 38 sloc · 998 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import math.complex
2
3struct Cat {
4 name string
5 breed string
6 age int
7}
8
9type Feline = Cat
10
11fn test_offsetof() {
12 cat := Cat{
13 name: 'Cthulhu'
14 breed: 'Great Old One'
15 age: 2147483647
16 }
17 unsafe {
18 assert *(&string(&u8(&cat) + __offsetof(Cat, name))) == 'Cthulhu'
19 assert *(&string(&u8(&cat) + __offsetof(Cat, breed))) == 'Great Old One'
20 assert *(&int(&u8(&cat) + __offsetof(Cat, age))) == 2147483647
21 }
22}
23
24fn test_offsetof_struct_from_another_module() {
25 num := complex.Complex{1.0, 1.0}
26 unsafe {
27 assert *(&f64(&u8(&num) + __offsetof(complex.Complex, re))) == 1.0
28 assert *(&f64(&u8(&num) + __offsetof(complex.Complex, im))) == 1.0
29 }
30}
31
32fn test_offsetof_alias() {
33 fel := Feline{
34 name: 'Cthulhu'
35 breed: 'Great Old One'
36 age: 2147483647
37 }
38 unsafe {
39 assert *(&string(&u8(&fel) + __offsetof(Feline, name))) == 'Cthulhu'
40 assert *(&string(&u8(&fel) + __offsetof(Feline, breed))) == 'Great Old One'
41 assert *(&int(&u8(&fel) + __offsetof(Feline, age))) == 2147483647
42 }
43}
44