v2 / vlib / v / slow_tests / valgrind / comptime_selector.v
52 lines · 47 sloc · 937 bytes · 36bef926fb9642378f6514886af7ce16279357f5
Raw
1module main
2
3import encoding.binary
4import math
5
6fn main() {
7 value := Vector3D{
8 x: 1.0
9 y: 2.0
10 z: 3.0
11 v: 'bob'
12 }
13 mut buf := []u8{len: 0, cap: 12}
14 serialize_to(value, mut buf)!
15 println(buf)
16}
17
18type Primitive = f64 | f32 | rune | i32 | u32 | i16 | u16 | i8 | u8 | bool
19
20struct Vector3D {
21 x f32
22 y f32
23 z f32
24 v string
25}
26
27fn serialize_to[T](val T, mut output []u8) ! {
28 $for v in Primitive.variants {
29 $if v.typ is T {
30 output << binary.encode_binary(val, binary.EncodeConfig{
31 buffer_len: int(sizeof[T]())
32 big_endian: false
33 })!
34 return
35 }
36 }
37 $if T is string {
38 if val.len > math.maxof[u16]() {
39 return error('String too long to serialize')
40 }
41 bytes := val.bytes()
42 output << binary.encode_binary(u16(bytes.len), binary.EncodeConfig{
43 buffer_len: int(sizeof[u16]())
44 big_endian: false
45 })!
46 output << bytes
47 return
48 }
49 $for field in T.fields {
50 serialize_to(val.$(field.name), mut output)!
51 }
52}
53