-
Notifications
You must be signed in to change notification settings - Fork 8
/
pgvector.go
77 lines (65 loc) · 1.68 KB
/
pgvector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package pgvector
import (
"database/sql"
"database/sql/driver"
"fmt"
"strconv"
"strings"
)
// Vector is a wrapper for []float32 to implement sql.Scanner and driver.Valuer.
type Vector struct {
vec []float32
}
// NewVector creates a new Vector from a slice of float32.
func NewVector(vec []float32) Vector {
return Vector{vec: vec}
}
// Slice returns the underlying slice of float32.
func (v Vector) Slice() []float32 {
return v.vec
}
// String returns a string representation of the vector.
func (v Vector) String() string {
buf := make([]byte, 0, 2+16*len(v.vec))
buf = append(buf, '[')
for i := 0; i < len(v.vec); i++ {
if i > 0 {
buf = append(buf, ',')
}
buf = strconv.AppendFloat(buf, float64(v.vec[i]), 'f', -1, 32)
}
buf = append(buf, ']')
return string(buf)
}
// Parse parses a string representation of a vector.
func (v *Vector) Parse(s string) error {
sp := strings.Split(s[1:len(s)-1], ",")
v.vec = make([]float32, 0, len(sp))
for i := 0; i < len(sp); i++ {
n, err := strconv.ParseFloat(sp[i], 32)
if err != nil {
return err
}
v.vec = append(v.vec, float32(n))
}
return nil
}
// statically assert that Vector implements sql.Scanner.
var _ sql.Scanner = (*Vector)(nil)
// Scan implements the sql.Scanner interface.
func (v *Vector) Scan(src interface{}) (err error) {
switch src := src.(type) {
case []byte:
return v.Parse(string(src))
case string:
return v.Parse(src)
default:
return fmt.Errorf("unsupported data type: %T", src)
}
}
// statically assert that Vector implements driver.Valuer.
var _ driver.Valuer = (*Vector)(nil)
// Value implements the driver.Valuer interface.
func (v Vector) Value() (driver.Value, error) {
return v.String(), nil
}