-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpath.go
74 lines (59 loc) · 1.37 KB
/
path.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
package pgeo
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"regexp"
)
var closedPathRegexp = regexp.MustCompile(`^\(\(`)
// Path is represented by list of connected points.
// Paths can be open, where the first and last points in the list are considered not connected,
// or closed, where the first and last points are considered connected.
type Path struct {
Points []Point
Closed bool
}
func (p Path) Value() (driver.Value, error) {
return valuePath(p)
}
func (p *Path) Scan(src interface{}) error {
return scanPath(p, src)
}
func valuePath(p Path) (driver.Value, error) {
var val string
if p.Closed {
val = fmt.Sprintf(`(%s)`, formatPoints(p.Points))
} else {
val = fmt.Sprintf(`[%s]`, formatPoints(p.Points))
}
return val, nil
}
func scanPath(p *Path, src interface{}) error {
if src == nil {
return nil
}
val, err := iToS(src)
if err != nil {
return err
}
(*p).Points, err = parsePoints(val)
if err != nil {
return err
}
if len((*p).Points) < 1 {
return errors.New("wrong path")
}
(*p).Closed = closedPathRegexp.MatchString(val)
return nil
}
func (p *Path) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Points)
}
func (p *Path) UnmarshalJSON(data []byte) error {
var err = json.Unmarshal(data, p.Points)
if p.Points != nil && len(p.Points) > 1 {
p.Closed = p.Points[0] == p.Points[len(p.Points)-1]
}
return err
}