ParseVector parses the Postgres string representation of a vector.
(input string)
| 26 | |
| 27 | // ParseVector parses the Postgres string representation of a vector. |
| 28 | func ParseVector(input string) (T, error) { |
| 29 | input = strings.TrimSpace(input) |
| 30 | if !strings.HasPrefix(input, "[") || !strings.HasSuffix(input, "]") { |
| 31 | return T{}, pgerror.Newf(pgcode.InvalidTextRepresentation, |
| 32 | "malformed vector literal: Vector contents must start with \"[\" and"+ |
| 33 | " end with \"]\"") |
| 34 | } |
| 35 | |
| 36 | input = strings.TrimPrefix(input, "[") |
| 37 | input = strings.TrimSuffix(input, "]") |
| 38 | parts := strings.Split(input, ",") |
| 39 | |
| 40 | if len(parts) > MaxDim { |
| 41 | return T{}, pgerror.Newf(pgcode.ProgramLimitExceeded, "vector cannot have more than %d dimensions", MaxDim) |
| 42 | } |
| 43 | |
| 44 | vector := make([]float32, len(parts)) |
| 45 | for i, part := range parts { |
| 46 | part = strings.TrimSpace(part) |
| 47 | if part == "" { |
| 48 | return T{}, pgerror.New(pgcode.InvalidTextRepresentation, "invalid input syntax for type vector: empty string") |
| 49 | } |
| 50 | |
| 51 | val, err := strconv.ParseFloat(part, 32) |
| 52 | if err != nil { |
| 53 | return T{}, pgerror.Newf(pgcode.InvalidTextRepresentation, "invalid input syntax for type vector: %s", part) |
| 54 | } |
| 55 | |
| 56 | if math.IsInf(val, 0) { |
| 57 | return T{}, pgerror.New(pgcode.DataException, "infinite value not allowed in vector") |
| 58 | } |
| 59 | if math.IsNaN(val) { |
| 60 | return T{}, pgerror.New(pgcode.DataException, "NaN not allowed in vector") |
| 61 | } |
| 62 | vector[i] = float32(val) |
| 63 | } |
| 64 | |
| 65 | return vector, nil |
| 66 | } |
| 67 | |
| 68 | // AsSet returns this vector a set of one vector. |
| 69 | func (v T) AsSet() Set { |
no test coverage detected
searching dependent graphs…