github.com/fluhus/gostuff@v0.4.1-0.20240331134726-be71864f2b5d/csvdec/fillslice.got (about) 1 {{/* Template for generating the slice-filling functions. */}} 2 3 {{$ints := slice 0 8 16 32 64}} 4 {{$floats := slice 32 64}} 5 6 package csvdec 7 8 import ( 9 "reflect" 10 "strconv" 11 ) 12 13 // Populates any slice value. 14 func fillSlice(value reflect.Value, fields []string) error { 15 kind := value.Type().Elem().Kind() 16 switch kind { 17 case reflect.String: 18 return fillStringSlice(value, fields) 19 {{range $ints -}} 20 case reflect.Int{{if .}}{{.}}{{end}}: 21 return fillInt{{if .}}{{.}}{{end}}Slice(value, fields) 22 {{end -}} 23 {{range $ints -}} 24 case reflect.Uint{{if .}}{{.}}{{end}}: 25 return fillUint{{if .}}{{.}}{{end}}Slice(value, fields) 26 {{end -}} 27 {{range $floats -}} 28 case reflect.Float{{.}}: 29 return fillFloat{{.}}Slice(value, fields) 30 {{end -}} 31 } 32 panic("Unsupported type: " + value.Type().String()) 33 } 34 35 {{range $ints}} 36 // Populates the given int{{if .}}{{.}}{{end}} slice with values parsed from fields. 37 // Returns an error if parsing fails. 38 func fillInt{{if .}}{{.}}{{end}}Slice(value reflect.Value, fields []string) error { 39 parsed := make([]int{{if .}}{{.}}{{end}}, len(fields)) 40 for i, field := range fields { 41 n, err := strconv.ParseInt(field, 0, {{.}}) 42 if err != nil { 43 return err 44 } 45 parsed[i] = int{{if .}}{{.}}{{end}}(n) 46 } 47 value.Set(reflect.ValueOf(parsed)) 48 return nil 49 } 50 {{end}} 51 52 {{range $ints}} 53 // Populates the given uint{{if .}}{{.}}{{end}} slice with values parsed from fields. 54 // Returns an error if parsing fails. 55 func fillUint{{if .}}{{.}}{{end}}Slice(value reflect.Value, fields []string) error { 56 parsed := make([]uint{{if .}}{{.}}{{end}}, len(fields)) 57 for i, field := range fields { 58 n, err := strconv.ParseUint(field, 0, {{.}}) 59 if err != nil { 60 return err 61 } 62 parsed[i] = uint{{if .}}{{.}}{{end}}(n) 63 } 64 value.Set(reflect.ValueOf(parsed)) 65 return nil 66 } 67 {{end}} 68 69 {{range $floats}} 70 // Populates the given float{{.}} slice with values parsed from fields. 71 // Returns an error if parsing fails. 72 func fillFloat{{.}}Slice(value reflect.Value, fields []string) error { 73 parsed := make([]float{{.}}, len(fields)) 74 for i, field := range fields { 75 n, err := strconv.ParseFloat(field, {{.}}) 76 if err != nil { 77 return err 78 } 79 parsed[i] = float{{.}}(n) 80 } 81 value.Set(reflect.ValueOf(parsed)) 82 return nil 83 } 84 {{end}} 85 86 87 // Populates the given string slice with values parsed from fields. 88 // Returns an error if parsing fails. 89 func fillStringSlice(value reflect.Value, fields []string) error { 90 // Fields may be a part of a bigger slice, so copying to allow the big 91 // slice to get CG'ed. 92 slice := make([]string, len(fields)) 93 copy(slice, fields) 94 value.Set(reflect.ValueOf(slice)) 95 return nil 96 }