| 1 | enum Flag { |
| 2 | usa_old_glory |
| 3 | all_other_bad_excuses_for_a_flag |
| 4 | } |
| 5 | |
| 6 | struct Test { |
| 7 | is_foo bool |
| 8 | name [5]u8 |
| 9 | } |
| 10 | |
| 11 | fn enc[T](item T) string { |
| 12 | $if T is $int { |
| 13 | len := match typeof(item).name { |
| 14 | 'i8', 'u8' { u8(2) } |
| 15 | 'i16', 'u16' { 4 } |
| 16 | 'int', 'u32', 'i32' { 8 } |
| 17 | 'i64', 'u64' { 16 } |
| 18 | else { return '' } |
| 19 | } |
| 20 | |
| 21 | return u64_to_hex(u64(item), len) |
| 22 | } $else $if T is $array { |
| 23 | mut hex := '' |
| 24 | for val in item { |
| 25 | hex += enc(val) |
| 26 | } |
| 27 | return hex |
| 28 | } $else $if T is $struct { |
| 29 | mut hex := '' |
| 30 | $for field in T.fields { |
| 31 | hex += enc(item.$(field.name)) + '_' |
| 32 | } |
| 33 | return hex |
| 34 | } $else { |
| 35 | if typeof(item).name == 'bool' { |
| 36 | return enc(int(item)) |
| 37 | } |
| 38 | $if debug { |
| 39 | println('cannot encode ${T}(s)') |
| 40 | } |
| 41 | return '' |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | @[direct_array_access; inline] |
| 46 | fn u64_to_hex(nn u64, len u8) string { |
| 47 | mut n := nn |
| 48 | mut buf := [17]u8{} |
| 49 | buf[len] = 0 |
| 50 | mut i := 0 |
| 51 | for i = len - 1; i >= 0; i-- { |
| 52 | d := u8(n & 0xF) |
| 53 | buf[i] = if d < 10 { d + `0` } else { d + 87 } |
| 54 | n = n >> 4 |
| 55 | } |
| 56 | return unsafe { tos(memdup(&buf[0], len + 1), len) } |
| 57 | } |
| 58 | |
| 59 | fn test_main() { |
| 60 | assert enc(Test{}) == '00000000_0000000000_' |
| 61 | assert enc(Test{ is_foo: true }) == '00000001_0000000000_' |
| 62 | assert enc(Test{ name: [u8(1), 2, 3, 4, 5]! }) == '00000000_0102030405_' |
| 63 | } |
| 64 | |