| 1 | module csv |
| 2 | |
| 3 | import strconv |
| 4 | |
| 5 | // decode csv to struct |
| 6 | pub fn decode[T](data string) []T { |
| 7 | mut result := []T{} |
| 8 | if data == '' { |
| 9 | return result |
| 10 | } |
| 11 | |
| 12 | mut parser := new_reader(data) |
| 13 | mut columns_names := []string{} |
| 14 | mut i := 0 |
| 15 | for { |
| 16 | items := parser.read() or { break } |
| 17 | if i == 0 { |
| 18 | for val in items { |
| 19 | columns_names << val |
| 20 | } |
| 21 | } else { |
| 22 | mut t_val := T{} |
| 23 | $for field in T.fields { |
| 24 | col := get_column(field.name, columns_names) |
| 25 | if col > -1 && col < items.len { |
| 26 | $if field.typ is string { |
| 27 | t_val.$(field.name) = items[col] |
| 28 | } $else $if field.typ is int { |
| 29 | t_val.$(field.name) = items[col].int() |
| 30 | } $else $if field.typ is f32 { |
| 31 | t_val.$(field.name) = f32(strconv.atof64(items[col]) or { f32(0.0) }) |
| 32 | } $else $if field.typ is f64 { |
| 33 | t_val.$(field.name) = strconv.atof64(items[col]) or { f64(0.0) } |
| 34 | } $else $if field.typ is bool { |
| 35 | t_val.$(field.name) = string_to_bool(items[col]) |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | result << t_val |
| 40 | } |
| 41 | i++ |
| 42 | } |
| 43 | |
| 44 | return result |
| 45 | } |
| 46 | |
| 47 | fn string_to_bool(val string) bool { |
| 48 | l_val := val.to_lower().trim_space() |
| 49 | if l_val == 'true' { |
| 50 | return true |
| 51 | } |
| 52 | |
| 53 | i_val := val.int() |
| 54 | if i_val != 0 { |
| 55 | return true |
| 56 | } |
| 57 | |
| 58 | return false |
| 59 | } |
| 60 | |
| 61 | fn get_column(name string, columns []string) int { |
| 62 | for i, val in columns { |
| 63 | if val == name { |
| 64 | return i |
| 65 | } |
| 66 | } |
| 67 | return -1 |
| 68 | } |
| 69 | |