| 1 | import math.complex |
| 2 | |
| 3 | struct Cat { |
| 4 | name string |
| 5 | breed string |
| 6 | age int |
| 7 | } |
| 8 | |
| 9 | struct OffsetInlineOnly { |
| 10 | a int |
| 11 | b int |
| 12 | } |
| 13 | |
| 14 | struct OffsetConstOnly { |
| 15 | a int |
| 16 | b int |
| 17 | } |
| 18 | |
| 19 | type Feline = Cat |
| 20 | |
| 21 | const offset_const_only_b = __offsetof(OffsetConstOnly, b) |
| 22 | |
| 23 | fn 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 | |
| 36 | fn test_offsetof_inline_only_marks_struct_as_used() { |
| 37 | assert __offsetof(OffsetInlineOnly, b) == 4 |
| 38 | } |
| 39 | |
| 40 | fn test_offsetof_const_marks_struct_as_used() { |
| 41 | assert offset_const_only_b == 4 |
| 42 | } |
| 43 | |
| 44 | fn 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 | |
| 52 | fn 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 | |