parseVFloat(s) will generate a slice of float64 values, as long as s is either an empty string, or if it is formatted according to the following ebnf: floatArray ::= "[" [floatList] [whitespace] "]" floatList := float32Val | float32Val floatSpaceList | float32Val float
(s string)
| 36 | // floatCommaList := ([whitespace] "," [whitespace] float32Val)+ |
| 37 | // float32Val := < a string rep of a float32 value > |
| 38 | func ParseVFloat(s string) ([]float32, error) { |
| 39 | // TODO Check if this can be done using lexer |
| 40 | s = strings.ReplaceAll(s, "\n", " ") |
| 41 | s = strings.ReplaceAll(s, "\t", " ") |
| 42 | s = strings.TrimSpace(s) |
| 43 | if len(s) == 0 { |
| 44 | return []float32{}, nil |
| 45 | } |
| 46 | trimmedPre := strings.TrimPrefix(s, "[") |
| 47 | if len(trimmedPre) == len(s) { |
| 48 | return nil, cannotConvertToVFloat(s) |
| 49 | } |
| 50 | trimmed := strings.TrimRight(trimmedPre, "]") |
| 51 | if len(trimmed) == len(trimmedPre) { |
| 52 | return nil, cannotConvertToVFloat(s) |
| 53 | } |
| 54 | if len(trimmed) == 0 { |
| 55 | return []float32{}, nil |
| 56 | } |
| 57 | if strings.Contains(trimmed, ",") { |
| 58 | // Splitting based on comma-separation. |
| 59 | values := strings.Split(trimmed, ",") |
| 60 | result := make([]float32, len(values)) |
| 61 | for i := range values { |
| 62 | trimmedVal := strings.TrimSpace(values[i]) |
| 63 | val, err := strconv.ParseFloat(trimmedVal, 32) |
| 64 | if err != nil { |
| 65 | return nil, cannotConvertToVFloat(s) |
| 66 | } |
| 67 | result[i] = float32(val) |
| 68 | } |
| 69 | return result, nil |
| 70 | } |
| 71 | values := strings.Split(trimmed, " ") |
| 72 | result := make([]float32, 0, len(values)) |
| 73 | for i := range values { |
| 74 | if len(values[i]) == 0 { |
| 75 | // skip if we have an empty string. This can naturally |
| 76 | // occur if input s was "[1.0 2.0]" |
| 77 | // notice the extra whitespace in separation! |
| 78 | continue |
| 79 | } |
| 80 | if len(values[i]) > 0 { |
| 81 | val, err := strconv.ParseFloat(values[i], 32) |
| 82 | if err != nil { |
| 83 | return nil, cannotConvertToVFloat(s) |
| 84 | } |
| 85 | result = append(result, float32(val)) |
| 86 | } |
| 87 | } |
| 88 | return result, nil |
| 89 | } |
| 90 | |
| 91 | func cannotConvertToVFloat(s string) error { |
| 92 | return errors.Errorf("cannot convert %s to vfloat", s) |
no test coverage detected