-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathparse.go
125 lines (100 loc) · 2.09 KB
/
parse.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package pqinterval
import (
"fmt"
"strconv"
"strings"
)
// ParseErr is returned on a failure to parse a
// postgres result into an Interval or Duration.
type ParseErr struct {
String string
Cause error
}
func parse(s string) (Interval, error) {
chunks := strings.Split(s, " ")
ival := Interval{}
var negTime bool
// the space delimited sections of a postgres-formatted interval
// come in pairs until the time portion: "3 years 2 days 04:15:47"
if len(chunks)%2 == 1 {
t := chunks[len(chunks)-1]
chunks = chunks[:len(chunks)-1]
switch t[0] {
case '-':
negTime = true
t = t[1:]
case '+':
t = t[1:]
}
// hh:mm:ss[.uuuuuu]
if t[2] != ':' || t[5] != ':' || len(t) < 8 {
return ival, ParseErr{s, nil}
}
if len(t) > 8 && (t[8] != '.' || len(t) == 9) {
return ival, ParseErr{s, nil}
}
hrs, err := strconv.Atoi(t[:2])
if err != nil {
return ival, ParseErr{s, err}
}
if negTime {
hrs = -hrs
}
t = t[3:]
mins, err := strconv.Atoi(t[:2])
if err != nil {
return ival, ParseErr{s, err}
}
t = t[3:]
secs, err := strconv.Atoi(t[:2])
if err != nil {
return ival, ParseErr{s, err}
}
t = t[2:]
if len(t) > 0 {
t = t[1:]
}
var us int
if t != "" {
t += strings.Repeat("0", 6-len(t))
us, err = strconv.Atoi(t)
if err != nil {
return ival, ParseErr{s, err}
}
}
us += secs*usPerSec + mins*usPerMin
ival.hrs = int32(hrs)
ival.us = uint32(us)
}
for len(chunks) > 0 {
t := chunks[0]
unit := chunks[1]
chunks = chunks[2:]
n, err := strconv.Atoi(t)
if err != nil {
return Interval{}, ParseErr{s, err}
}
switch unit {
case "year", "years":
if n < 0 {
n *= -1
n |= yrSignBit
}
ival.yrs = uint32(n)
case "mon", "mons":
ival.hrs += int32(24 * daysPerMon * n)
case "day", "days":
ival.hrs += int32(24 * n)
default:
return Interval{}, ParseErr{s, nil}
}
}
if negTime {
ival.yrs |= usSignBit
}
return ival, nil
}
// Error implements the error interface.
func (pe ParseErr) Error() string {
return fmt.Sprintf("pqinterval: Error parsing %q: %s", pe.String, pe.Cause)
}