| 1 | module main |
| 2 | |
| 3 | struct Decoder { |
| 4 | json string |
| 5 | } |
| 6 | |
| 7 | pub fn decode[T](val string) !T { |
| 8 | mut decoder := Decoder{ |
| 9 | json: val |
| 10 | } |
| 11 | |
| 12 | mut result := T{} |
| 13 | decoder.decode_value(mut &result)! |
| 14 | return result |
| 15 | } |
| 16 | |
| 17 | fn (mut decoder Decoder) decode_value[T](mut val T) ! { |
| 18 | $if T.unaliased_typ is $array { |
| 19 | mut array_element := create_array_element(val) |
| 20 | |
| 21 | decoder.decode_value(mut array_element)! |
| 22 | |
| 23 | val << array_element |
| 24 | |
| 25 | assert val.len == 1 |
| 26 | assert val[0] == array_element |
| 27 | } $else $if T.unaliased_typ is $map { |
| 28 | mut map_value := create_map_value(val) |
| 29 | |
| 30 | decoder.decode_value(mut map_value)! |
| 31 | |
| 32 | val['key'] = map_value |
| 33 | |
| 34 | assert val.len == 1 |
| 35 | assert val['key'] == map_value |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | fn create_array_element[T](array []T) T { |
| 40 | return T{} |
| 41 | } |
| 42 | |
| 43 | fn create_map_value[K, V](map_ map[K]V) V { |
| 44 | return V{} |
| 45 | } |
| 46 | |
| 47 | fn test_main() { |
| 48 | assert decode[[]int]('[1, 2, 3]')! == [0] |
| 49 | assert decode[[]string]('["1", "2", "3"]')! == [''] |
| 50 | assert decode[map[string]int]('{"a": 1}')! == { |
| 51 | 'key': 0 |
| 52 | } |
| 53 | assert decode[map[string]string]('{"val": "2"}')! == { |
| 54 | 'key': '' |
| 55 | } |
| 56 | } |
| 57 | |