forked from fxtlabs/date
/
parse.go
239 lines (201 loc) · 6.51 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright 2015 Rick Beton. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package period
import (
"fmt"
"strconv"
"strings"
)
// MustParse is as per Parse except that it panics if the string cannot be parsed.
// This is intended for setup code; don't use it for user inputs.
// By default, the value is normalised.
// Normalisation can be disabled using the optional flag.
func MustParse(value string, normalise ...bool) Period {
d, err := Parse(value, normalise...)
if err != nil {
panic(err)
}
return d
}
// Parse parses strings that specify periods using ISO-8601 rules.
//
// In addition, a plus or minus sign can precede the period, e.g. "-P10D"
//
// By default, the value is normalised, e.g. multiple of 12 months become years
// so "P24M" is the same as "P2Y". However, this is done without loss of precision,
// so for example whole numbers of days do not contribute to the months tally
// because the number of days per month is variable.
//
// Normalisation can be disabled using the optional flag.
//
// The zero value can be represented in several ways: all of the following
// are equivalent: "P0Y", "P0M", "P0W", "P0D", "PT0H", PT0M", PT0S", and "P0".
// The canonical zero is "P0D".
func Parse(period string, normalise ...bool) (Period, error) {
return ParseWithNormalise(period, len(normalise) == 0 || normalise[0])
}
// ParseWithNormalise parses strings that specify periods using ISO-8601 rules
// with an option to specify whether to normalise parsed period components.
//
// This method is deprecated and should not be used. It may be removed in a
// future version.
func ParseWithNormalise(period string, normalise bool) (Period, error) {
if period == "" || period == "-" || period == "+" {
return Period{}, fmt.Errorf("cannot parse a blank string as a period")
}
if period == "P0" {
return Period{}, nil
}
p64, err := parse(period, normalise)
if err != nil {
return Period{}, err
}
return p64.toPeriod()
}
func parse(period string, normalise bool) (*period64, error) {
neg := false
remaining := period
if remaining[0] == '-' {
neg = true
remaining = remaining[1:]
} else if remaining[0] == '+' {
remaining = remaining[1:]
}
if remaining[0] != 'P' {
return nil, fmt.Errorf("%s: expected 'P' period mark at the start", period)
}
remaining = remaining[1:]
var integer, fraction, weekValue int64
result := &period64{input: period, neg: neg}
var years, months, weeks, days, hours, minutes, seconds itemState
var designator, previousFractionDesignator byte
var err error
nComponents := 0
years, months, weeks, days = Armed, Armed, Armed, Armed
isHMS := false
for len(remaining) > 0 {
if remaining[0] == 'T' {
if isHMS {
return nil, fmt.Errorf("%s: 'T' designator cannot occur more than once", period)
}
isHMS = true
years, months, weeks, days = Unready, Unready, Unready, Unready
hours, minutes, seconds = Armed, Armed, Armed
remaining = remaining[1:]
} else {
integer, fraction, designator, remaining, err = parseNextField(remaining, period)
if err != nil {
return nil, err
}
if previousFractionDesignator != 0 && fraction != 0 {
return nil, fmt.Errorf("%s: '%c' & '%c' only the last field can have a fraction", period, previousFractionDesignator, designator)
}
number := integer*10 + fraction
switch designator {
case 'Y':
years, err = years.testAndSet(number, 'Y', result, &result.years)
case 'W':
weeks, err = weeks.testAndSet(number, 'W', result, &weekValue)
case 'D':
days, err = days.testAndSet(number, 'D', result, &result.days)
case 'H':
hours, err = hours.testAndSet(number, 'H', result, &result.hours)
case 'S':
seconds, err = seconds.testAndSet(number, 'S', result, &result.seconds)
case 'M':
if isHMS {
minutes, err = minutes.testAndSet(number, 'M', result, &result.minutes)
} else {
months, err = months.testAndSet(number, 'M', result, &result.months)
}
default:
return nil, fmt.Errorf("%s: expected a number not '%c'", period, designator)
}
nComponents++
if err != nil {
return nil, err
}
if fraction != 0 {
previousFractionDesignator = designator
}
}
}
if nComponents == 0 {
return nil, fmt.Errorf("%s: expected 'Y', 'M', 'W', 'D', 'H', 'M', or 'S' designator", period)
}
result.days += weekValue * 7
if normalise {
result = result.normalise64(true)
}
return result, nil
}
//-------------------------------------------------------------------------------------------------
type itemState int
const (
Unready itemState = iota
Armed
Set
)
func (i itemState) testAndSet(number int64, designator byte, result *period64, value *int64) (itemState, error) {
switch i {
case Unready:
return i, fmt.Errorf("%s: '%c' designator cannot occur here", result.input, designator)
case Set:
return i, fmt.Errorf("%s: '%c' designator cannot occur more than once", result.input, designator)
}
*value = number
return Set, nil
}
//-------------------------------------------------------------------------------------------------
func parseNextField(str, original string) (int64, int64, byte, string, error) {
i := scanDigits(str)
if i < 0 {
return 0, 0, 0, "", fmt.Errorf("%s: missing designator at the end", original)
}
des := str[i]
integer, fraction, err := parseDecimalNumber(str[:i], original, des)
return integer, fraction, des, str[i+1:], err
}
// Fixed-point one decimal place
func parseDecimalNumber(number, original string, des byte) (int64, int64, error) {
dec := strings.IndexByte(number, '.')
if dec < 0 {
dec = strings.IndexByte(number, ',')
}
var integer, fraction int64
var err error
if dec >= 0 {
integer, err = strconv.ParseInt(number[:dec], 10, 64)
if err == nil {
number = number[dec+1:]
switch len(number) {
case 0: // skip
case 1:
fraction, err = strconv.ParseInt(number, 10, 64)
default:
fraction, err = strconv.ParseInt(number[:1], 10, 64)
}
}
} else {
integer, err = strconv.ParseInt(number, 10, 64)
}
if err != nil {
return 0, 0, fmt.Errorf("%s: expected a number but found '%c'", original, des)
}
return integer, fraction, err
}
// scanDigits finds the first non-digit byte after a given starting point.
// Note that it does not care about runes or UTF-8 encoding; it assumes that
// a period string is always valid ASCII as well as UTF-8.
func scanDigits(s string) int {
for i, c := range s {
if !isDigit(c) {
return i
}
}
return -1
}
func isDigit(c rune) bool {
return ('0' <= c && c <= '9') || c == '.' || c == ','
}